Working with APIs
HTTP Basics
2 min read
HTTP (HyperText Transfer Protocol) is how your code talks to AI services. Understanding it is essential for working with any API.
The Request-Response Model
Your Code ──[Request]──> API Server
<──[Response]──
Every API interaction follows this pattern:
- Your code sends a request
- The server processes it
- The server returns a response
HTTP Methods
| Method | Purpose | AI Use Case |
|---|---|---|
| GET | Retrieve data | List models, check status |
| POST | Send data | Chat completions, embeddings |
| PUT | Update data | Update fine-tuned models |
| DELETE | Remove data | Delete files, cancel jobs |
Most AI API calls use POST because you're sending prompts/messages.
Request Structure
POST /v1/chat/completions HTTP/1.1
Host: api.openai.com
Authorization: Bearer sk-your-key
Content-Type: application/json
{
"model": "gpt-4",
"messages": [{"role": "user", "content": "Hello!"}]
}
Key components:
- Method + Path: What action and where
- Headers: Metadata (auth, content type)
- Body: The actual data (JSON for AI APIs)
Response Structure
HTTP/1.1 200 OK
Content-Type: application/json
{
"choices": [
{"message": {"content": "Hello! How can I help?"}}
]
}
HTTP Status Codes
| Code | Meaning | What to Do |
|---|---|---|
| 200 | Success | Process the response |
| 400 | Bad request | Check your request format |
| 401 | Unauthorized | Check API key |
| 429 | Rate limited | Wait and retry |
| 500 | Server error | Retry or contact support |
Headers You'll Use Often
headers = {
"Authorization": "Bearer sk-your-api-key",
"Content-Type": "application/json",
"Accept": "application/json"
}
Next, we'll use the requests library to make these calls in Python. :::