API Request and Response
Every AI API interaction involves a request (what you send) and a response (what you get back). Understanding the structure of these helps you read documentation and debug issues.
10 min•By Priygop Team•Updated 2026
Structure of an API Request
Structure of an API Request
# Structure of an OpenAI API request
import json
# This is the structure of a request to the OpenAI Chat Completions API
# It is a Python dictionary that gets sent as JSON over HTTP
request_body = {
# The model you want to use
"model": "gpt-4o-mini",
# The conversation history (messages)
"messages": [
{
"role": "system",
"content": "You are a helpful assistant that explains technical concepts simply."
},
{
"role": "user",
"content": "Explain what an API is in one paragraph."
}
],
# Optional settings
"max_tokens": 200, # Maximum length of the response in tokens
"temperature": 0.7, # Creativity level: 0.0 = predictable, 1.0 = creative
"n": 1, # How many response variations to generate
}
print("API Request Structure:")
print(json.dumps(request_body, indent=2))Diagram
Loading diagram…
Deep Learning ⊂ Machine Learning ⊂ Artificial Intelligence
Structure of an API Response
Structure of an API Response
# Structure of an OpenAI API response
import json
# This is what the API sends back to your code
example_response = {
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1699565290,
"model": "gpt-4o-mini",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "An API (Application Programming Interface) is a set of rules that allows different software programs to communicate with each other. Think of it as a waiter in a restaurant: you place your order (send a request), the waiter takes it to the kitchen (the API communicates with the service), and returns with your food (the response). APIs allow developers to use powerful services without knowing how those services work internally."
},
"finish_reason": "stop" # Why the model stopped generating
}
],
"usage": {
"prompt_tokens": 42, # Tokens in your request
"completion_tokens": 78, # Tokens in the response
"total_tokens": 120 # Total (determines cost)
}
}
print("API Response Structure:")
print(json.dumps(example_response, indent=2))
# Extracting the text response from the JSON
response_text = example_response["choices"][0]["message"]["content"]
print()
print("Extracted response text:")
print(response_text)