Generating API Requests & Endpoints — Guided Lab
Scenario:
You want your Python application to communicate with an external API, but writing all the request handling code manually is tedious. Your AI assistant can generate API requests, endpoints, and example usage quickly and safely.
Step 0: Define Your Goal
Example: You want to fetch weather data from a public API and process the results.
- API:
https://api.openweathermap.org/data/2.5/weather - Task: Send request, handle JSON response, and extract temperature
Step 1: Craft the AI Prompt
Treat AI as a backend developer. Include:
- API endpoint and purpose
- Desired language (Python, JavaScript, etc.)
- Optional: error handling, headers, authentication
Example Prompt:
Write a Python function that fetches weather data from
https://api.openweathermap.org/data/2.5/weather
using the requests library. Include API key authentication, error handling, and return temperature in Celsius.
Step 2: AI Output Example
import requests
def get_temperature(city, api_key):
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
try:
response = requests.get(url)
response.raise_for_status() # Raises HTTPError for bad responses
data = response.json()
temp = data['main']['temp']
return temp
except requests.exceptions.HTTPError as errh:
print(f"HTTP error occurred: {errh}")
except requests.exceptions.ConnectionError as errc:
print(f"Connection error: {errc}")
except requests.exceptions.Timeout as errt:
print(f"Timeout error: {errt}")
except requests.exceptions.RequestException as err:
print(f"Something went wrong: {err}")
# Example usage
# api_key = "YOUR_API_KEY"
# print(get_temperature("London", api_key))
Step 3: Test the Function
- Replace
YOUR_API_KEYwith a valid OpenWeatherMap API key - Run the function and verify the temperature output
Step 4: Mini Lab Challenges
- Modify the function to return weather description along with temperature.
- Generate a JavaScript version using
fetch()for the same endpoint. - Add retry logic in case of connection failures.
- Create a function that fetches multiple cities and returns a dictionary of temperatures.
Step 5: Pro Tips
- Always provide API documentation or endpoint details in the prompt
- Ask AI to include error handling and response validation
- For authenticated APIs, instruct AI to handle API keys or tokens securely
- Test AI-generated requests to ensure correct data extraction
Lab Summary
- AI can generate API request functions and endpoints for multiple programming languages
- Clear prompts + API details = working code quickly
- AI helps reduce boilerplate and enforces best practices
- Combining AI with testing ensures reliable integration with external services






