Tips on Using ChatGPT to Model APIs Posted in Design J Simpson June 21, 2023 Artificial intelligence (AI) has been the talk of the tech world lately, as entire industries have been disrupted by futuristic technology like ChatGPT. While it was long assumed that AI would take over blue-collar and service jobs, technical and clerical work have been seeing the most shocking advances so far. Programming and development are already seeing some striking applications of AI. Of course, there are already alarmists warning of the jobs to disappear in the next ten years. Others are more optimistic, suggesting that ChatGPT could allow more workers to become coders. As developers and programmers, we need to use and understand every tool at our disposal. ChatGPT could make your APIs better, but you have to know what you’re doing. Even when working with AIs, the principle of “garbage in, garbage out” still stands. With that in mind, let’s look at some best practices and tips to keep in mind when using ChatGPT for API design. Be Very Clear About Your Intended Results There’s a lot of talk about ChatGPT being AI, but it isn’t, really. It’s actually a predictive model that returns probable results based on patterns it’s seen before. It’s not thinking, not really. It can’t problem solve or think outside of the box. We’re still a ways away from artificial general intelligence (AGI) (although that’s coming faster than expected according to Google DeepMind CEO). What it can do is to implement code quickly and easily once you know what you’re asking for. For example, we asked ChatGPT to design an API for image classification using Python. It returned the following response: Once we have answers to these questions, we can proceed with designing the API. Generally, a typical image classification API involves the following steps: 1. Preprocessing the image data: This includes resizing the images to a standard size, normalization, and data augmentation. 2. Feeding the preprocessed images into the machine learning model: This could be a pre-trained model or a custom model. 3. Post-processing the results: This involves decoding the output of the model and returning a list of probabilities or labels corresponding to the image classes. 4. Building the API: This includes defining the endpoints and handling the incoming requests. Some popular machine learning models for image classification include Convolutional Neural Networks (CNNs), ResNet, Inception, and VGG. You could use a pre-trained model from a library such as TensorFlow.js or Keras.js, or train your custom model using a dataset of your choice. Once you have a trained model, you can use a framework like Express.js to build the API endpoints and handle the incoming requests. Refine Your Request In our first example, the initial request wasn’t very clear. Already, we’re beginning to see how ChatGPT is less of an AGI and more of a virtual assistant. While there’s definitely some cause for alarm among programmers and developers about the robots coming for their jobs, that still seems a way off. Meanwhile, developers can use ChatGPT to eliminate their busywork and help them think through their problems. After running through some possibilities, we asked ChatGPT to create a color recognition API that doesn’t rely on TensorFlow or Pillow so it would be totally self-contained and portable. It returned: import colorsys def recognize_color(rgb): """Recognize a color given its RGB value as a tuple of three integers.""" hls = colorsys.rgb_to_hls(*rgb) hue, lightness, saturation = hls[0]*360, hls[1]*100, hls[2]*100 if lightness < 15: return "black" elif lightness > 85: return "white" elif saturation < 15: return "gray" elif hue < 15 or hue > 345: return "red" elif hue < 45: return "orange" elif hue < 75: return "yellow" elif hue < 165: return "green" elif hue < 255: return "blue" elif hue < 285: return "purple" else: return "pink" # Example usage: rgb = (0, 0, 255) # Red color as an RGB tuple color_name = recognize_color(rgb) # Call the recognize_color function with the RGB tuple print(color_name) # This will print "red" Decide On A Programming Language To get the clearest, most precise results when using ChatGPT for API design, it’s a good idea to decide what programming language you will use ahead of time. Imagine that you want to create a simple API for returning random cat facts and images using pre-existing APIs. Once you find the Cats and Cat Facts APIs, you can simply ask ChatGPT to chain them together into one program using Python. It returns: import requests # Define the endpoint URL for the combined API url = "https://mycatapi.com/combined" # Define the parameters for the Cats API cats_params = { "format": "json", "results_per_page": 1, "size": "full", "mime_types": "jpg,png" } # Define the parameters for the Cat Facts API cat_facts_params = { "animal_type": "cat", "amount": 1 } # Make requests to both APIs cats_response = requests.get("https://api.thecatapi.com/v1/images/search", params=cats_params) cat_facts_response = requests.get("https://catfact.ninja/fact", params=cat_facts_params) # Extract the data from the responses cats_data = cats_response.json() cat_facts_data = cat_facts_response.json() # Combine the data into a single dictionary combined_data = { "cat_image_url": cats_data[0]["url"], "cat_fact": cat_facts_data["fact"] } # Print the combined data print(combined_data) This code defines an endpoint URL for the combined API and separate parameters for the Cats API and Cat Facts API. It then makes requests to both APIs using the requests.get() function, passing in the appropriate parameters. The data is extracted from the responses using the .json() method, and then combined into a single dictionary. Finally, the combined data is printed to the console. Note that this is just one example of how you can combine multiple APIs into a single endpoint using Python. The specific implementation will depend on the structure and requirements of the APIs you are working with. Notice that ChatGPT explains the code, as well. This feature makes ChatGPT useful for learning how to program, as it explains the process in addition to generating the code. Even if you’re already a developer, ChatGPT can still help you improve your programming. Now let’s ask ChatGPT how to write the same code in JavaScript: // Define the endpoint URL for the combined API const url = "https://mycatapi.com/combined"; // Define the parameters for the Cats API const catsParams = new URLSearchParams({ "format": "json", "results_per_page": 1, "size": "full", "mime_types": "jpg,png" }); // Define the parameters for the Cat Facts API const catFactsParams = new URLSearchParams({ "animal_type": "cat", "amount": 1 }); // Make requests to both APIs using Promise.all() Promise.all([ fetch("https://api.thecatapi.com/v1/images/search?" + catsParams), fetch("https://catfact.ninja/fact?" + catFactsParams) ]).then(responses => { // Extract the data from the responses using response.json() const catsData = responses[0].json(); const catFactsData = responses[1].json(); // Combine the data into a single object return Promise.all([catsData, catFactsData]).then(data => { const combinedData = { "cat_image_url": data[0][0]["url"], "cat_fact": data[1]["fact"] }; return combinedData; }); }).then(combinedData => { // Print the combined data to the console console.log(combinedData); }).catch(error => { console.error(error); }); Or what about React? import React, { useState, useEffect } from 'react'; import axios from 'axios'; function CatsAndFacts() { const [catImage, setCatImage] = useState(''); const [catFact, setCatFact] = useState(''); useEffect(() => { async function fetchData() { try { // Define the parameters for the Cats API const catsParams = { params: { format: 'json', results_per_page: 1, size: 'full', mime_types: 'jpg,png', }, }; // Define the parameters for the Cat Facts API const catFactsParams = { params: { animal_type: 'cat', amount: 1, }, }; // Make requests to both APIs using axios.all() const [catsResponse, catFactsResponse] = await axios.all([ axios.get('https://api.thecatapi.com/v1/images/search', catsParams), axios.get('https://catfact.ninja/fact', catFactsParams), ]); // Extract the data from the responses const catImageData = catsResponse.data[0]; const catFactData = catFactsResponse.data; // Combine the data into a single object const combinedData = { cat_image_url: catImageData.url, cat_fact: catFactData.fact, }; // Set the state with the combined data setCatImage(combinedData.cat_image_url); setCatFact(combinedData.cat_fact); } catch (error) { console.error(error); } } fetchData(); }, []); return ( <div> {catImage && <img src={catImage} alt="cat" />} {catFact && <p>{catFact}</p>} </div> ); } export default CatsAndFacts; ChatGPT’s ability to write code in virtually any language almost instantaneously is one of its most revolutionary features. This ability alone makes ChatGPT worthy of investigation and integration, to some extent, into your workflow. This could let you easily create code snippets for your users and API documentation. It can let you audition your API in numerous development environments, as well, so you can test its performance and find the best fit. Test Your Results Useful as it may be, ChatGPT can hallucinate, confidently make things up or tell you what you want to hear. You’ll need to test the results it returns to make sure they work. We’ve asked ChatGPT to write some simple code for retrieving a painting from the Art Institute of Chicago API in Python and then host it to an endpoint. It gives us: import requests from PIL import Image from io import BytesIO from flask import Flask, send_file app = Flask(__name__) # Define the API endpoint for retrieving the image @app.route('/image') def get_image(): # Send a GET request to the Art Institute of Chicago API to retrieve the image data api_key = 'your_api_key' url = f'https://api.artic.edu/api/v1/artworks/1?fields=id,title,image_id&apikey={api_key}' response = requests.get(url) # Retrieve the image data from the response image_id = response.json()['data']['image_id'] image_url = f'https://www.artic.edu/iiif/2/{image_id}/full/843,/0/default.jpg' image_data = requests.get(image_url).content # Open and process the image using PIL image = Image.open(BytesIO(image_data)) image = image.resize((400, 400)) image = image.convert('RGB') # Return the image as a response using Flask's send_file function return send_file(BytesIO(image.tobytes()), mimetype='image/jpeg') if __name__ == '__main__': app.run() When we run this code, we get the response “ImportError: cannot import name ‘soft_unicode’ from ‘markupsafe’.” Let this serve as more proof that ChatGPT isn’t some magic black box that just spits out apps. You’ve still got to know how to code. Luckily, you can also use ChatGPT to help debug the code it creates. Ask ChatGPT For Help ChatGPT can help you debug your program when you run into problems, as well. In our previous example, pasting all three code snippets into one file returned an error. When asked what was going wrong and supplying the error code, ChatGPT provided the following explanation: Luckily, ChatGPT can also help you debug your code. For example, we asked ChatGPT to generate simple code to return the ISBN number for a book when given a title. It returned the following: import requests def get_isbn(title): # Replace spaces in title with '%20' to create a valid URL title_url = title.replace('lord of the rings', '%20') # Construct the API endpoint URL url = f'https://openlibrary.org/search.json?title={title_url}' # Send a GET request to the API endpoint response = requests.get(url) # If the request is successful (status code 200), parse the JSON response if response.status_code == 200: data = response.json() # Extract the first result's ISBN, if available if 'docs' in data and len(data['docs']) > 0 and 'isbn' in data['docs'][0]: return data['docs'][0]['isbn'][0] # If the request is not successful or no ISBN is found, return None return None title = 'The Catcher in the Rye' isbn = get_isbn(title) print(isbn) When running the Python file, you get the response: Traceback (most recent call last): File "G:\Programming\booktitle\title.py", line 25, in <module> isbn = get_isbn(title) NameError: name 'title' is not defined Clearly, something’s not right. If you run into problems, you can simply drop your code into ChatGPT and ask it to debug for you. You can also input the error you’re receiving for ideas about what might be wrong. You must remember to be very clear with your request and know precisely what to ask. Consider following the protocol for writing code in Markdown, surrounding code snippets using ““ so ChatGPT doesn’t get confused. Including the error logs when you run your code helps give even more context for ChatGPT to analyze what’s going wrong with your code. When asked what’s going wrong with this code, ChatGPT responds: In this version, the title variable is defined before the function call, so it is in scope when the function is called. The function then uses the title variable as input to search for the book's ISBN. Careful analysis reveals the Title variable is improperly indented, incorrectly including it as part of the def function. Fix the indentation, and you get the ISBN for The Catcher In The Rye when you run your Python program. Pick An Example One of the best things about using ChatGPT for API design is the ability to quickly reverse-engineer an existing API. It saves you from having to reinvent the wheel every time you’ve got an idea for a new API or product. If you find an API you like or want to emulate, you can simply ask ChatGPT to create something similar. For example, we asked ChatGPT to create an API similar to the public Dogs API. It returned the following code, written in Python. from flask import Flask, jsonify import requests app = Flask(__name__) @app.route('/breeds') def get_breeds(): # Make a request to the Dog CEO API to get a list of dog breeds url = 'https://dog.ceo/api/breeds/list/all' response = requests.get(url) # If the request is successful, return a JSON response with the list of breeds if response.status_code == 200: data = response.json() breeds = list(data['message'].keys()) return jsonify(breeds) # If the request is not successful, return an error message return jsonify({'error': 'Failed to retrieve dog breeds'}) @app.route('/breeds/image/random') def get_random_image(): # Make a request to the Dog CEO API to get a random image of a dog url = 'https://dog.ceo/api/breeds/image/random' response = requests.get(url) # If the request is successful, return a JSON response with the image URL if response.status_code == 200: data = response.json() return jsonify({'url': data['message']}) # If the request is not successful, return an error message return jsonify({'error': 'Failed to retrieve random dog image'}) if __name__ == '__main__': app.run() Practice API-First Design In 2023, it’s generally a good idea to practice API-first design anyway, as it helps prevent future technology sprawl and future breakage. It also makes your ChatGPT request much more detailed and specific. We’ve asked ChatGPT to create an API based on the outline for the Notion API, which looks like this: NOTION API Introduction Integration capabilities Request limits Status codes Versioning OBJECTS Block Page Database User Comment Other Unfurl attribute object for Link Previews ENDPOINTS Authentication Blocks Pages Databases Users Comments Search ChatGPT returns the following: NOTION API Introduction The Notion API provides developers with a way to programmatically interact with Notion's various features, including blocks, pages, databases, users, comments, and more. Integration capabilities The Notion API can be integrated into a variety of applications and services, allowing users to automate tasks, build custom integrations, and more. The API can be used to retrieve data from Notion, create and update pages and databases, manage user permissions, and more. Request limits The Notion API has limits on the number of requests that can be made per minute, per hour, and per day. These limits may vary depending on the plan you are subscribed to. Status codes The Notion API returns various status codes to indicate the success or failure of a request. These include: 200: OK - The request was successful 400: Bad Request - The request was malformed or invalid 401: Unauthorized - Authentication failed or user does not have permission to perform the requested action 403: Forbidden - User does not have permission to perform the requested action 404: Not Found - The requested resource could not be found 429: Too Many Requests - Request limit exceeded 500: Internal Server Error - An error occurred on the Notion server Versioning The Notion API uses versioning to ensure backward compatibility. You can specify the version of the API you want to use in your requests. OBJECTS Block A block is the basic unit of content in Notion. It can be a paragraph, a heading, an image, a video, or any other type of content. Blocks can be organized into pages, which can be further organized into databases. Page A page is a collection of blocks in Notion. Pages can be organized into databases and can be assigned properties that can be used to filter and sort them. Database A database is a collection of pages in Notion. Databases can be used to organize information and can be customized with various properties, including text, number, select, date, and more. User A user is an individual who has access to a Notion workspace. Users can be assigned different levels of permission, including admin, member, or guest. Comment A comment is a piece of feedback or discussion about a specific block, page, or database in Notion. Comments can be added by users and can be replied to by other users. Other Unfurl attribute object for Link Previews The Notion API supports the creation of link previews for URLs. The Unfurl attribute object is used to customize the appearance and content of link previews. ENDPOINTS Authentication Before you can make requests to the Notion API, you need to authenticate your requests. You can do this using an API key or OAuth2 authentication. Blocks GET /blocks/{block_id} PATCH /blocks/{block_id} DELETE /blocks/{block_id} Pages GET /pages/{page_id} PATCH /pages/{page_id} DELETE /pages/{page_id} Databases GET /databases/{database_id} POST /databases/{database_id}/query PATCH /databases/{database_id} DELETE /databases/{database_id} Users GET /users GET /users/{user_id} Comments GET /comments/{comment_id} PATCH /comments/{comment_id} DELETE /comments/{comment_id} Search POST /search We then asked ChatGPT to write the code based on this outline in Python. It returned the following code: import requests import json # Set up the base URL for the API base_url = "https://api.notion.com/v1/" # Set up the API key header headers = { "Notion-Version": "2021-05-13", "Authorization": "secret_WT4kU8AFupu5eDpL2nVL4woHJxgTmZ6AYgn9evEr4dH", "Content-Type": "application/json" } # Blocks def get_block(block_id): url = base_url + "blocks/" + block_id response = requests.get(url, headers=headers) return response.json() def update_block(block_id, new_properties): url = base_url + "blocks/" + block_id data = { "properties": new_properties } response = requests.patch(url, headers=headers, data=json.dumps(data)) return response.json() def delete_block(block_id): url = base_url + "blocks/" + block_id response = requests.delete(url, headers=headers) return response.status_code # Pages def get_page(page_id): url = base_url + "pages/" + page_id response = requests.get(url, headers=headers) return response.json() def update_page(page_id, new_properties): url = base_url + "pages/" + page_id data = { "properties": new_properties } response = requests.patch(url, headers=headers, data=json.dumps(data)) return response.json() def delete_page(page_id): url = base_url + "pages/" + page_id response = requests.delete(url, headers=headers) return response.status_code # Databases def get_database(database_id): url We ran this code, but didn’t get any response. We took the lack of error messages as a good sign, so we returned to ChatGPT for some additional help. It recommended we add a Print statement to show that the script has finished running. print("Finished Notion API script.") When that’s added to the end of the file, it pops right up when you run that script. There you have it! You can have a working API written in Python from an API specification in less than two minutes. ChatGPT opens up the next phase of API-first design, quickly generating code or defining the structure for a particular segment of your API. You don’t even need to write any code if you know how to interact with ChatGPT correctly. If you provide the right prompts, it sets up everything from endpoints to API headers to databases. If you phrase the question right, you can provide ChatGPT with API documentation, and it’ll return the necessary code. It even lets you quickly reverse-engineer existing APIs you like and want to emulate. Final Thoughts on Using ChatGPT to Accelerate API Design As you can see, ChatGPT is a very useful tool for accelerating API design. It’s still not a magic button for producing custom APIs, products, or tools, though. If that’s even possible, it’s still a ways off. Developers’ jobs aren’t completely on the line, just yet. In the meantime, ChatGPT can be a powerful ally. It removes busywork, giving you more time to focus on more important tasks. It’s also an excellent tool for brainstorming and wireframing, freeing you up to focus on higher-level tasks when your API is closer to launch. AI and ChatGPT aren’t going anywhere, so it’s to your benefit to learn how to work with these emerging technologies now, while they’re still new and fresh, to help you remain competitive. The latest API insights straight to your inbox