0Pricing
AI Agents · Lesson

REST API Fundamentals for Agent Developers

HTTP methods, status codes, headers, and JSON request/response format.

REST API Fundamentals for Agent Developers is a free AI Agents lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is an HTTP Request?

Every agent that connects to an external service uses HTTP — the language of the web. An HTTP request has three key parts: a method, a URL, and optional headers and a body.

Think of the method as a verb telling the server what you want to do, and the URL as the address of the resource.

import requests

# A simple GET request to a public API
response = requests.get('https://api.example.com/users')
print(response.status_code)  # 200
print(response.text)          # raw JSON string

GET — Fetching Data

GET retrieves data from a server. It should never modify anything. Agents use GET to read user profiles, fetch task lists, or pull configuration data.

You can pass parameters in the URL as a query string using the params argument.

import requests

# Fetch users filtered by role
params = {'role': 'admin', 'page': 1, 'limit': 10}
response = requests.get(
    'https://api.example.com/users',
    params=params
)
# URL becomes: /users?role=admin&page=1&limit=10
data = response.json()
print(data['users'])

POST — Creating Resources

POST sends data to the server to create a new resource. Agents use POST to submit tasks, send messages, or trigger actions. The data goes in the request body as JSON.

Always set the Content-Type: application/json header — most APIs require it.

import requests
import json

payload = {
    'title': 'Research competitors',
    'assignee': 'agent-001',
    'priority': 'high'
}

response = requests.post(
    'https://api.example.com/tasks',
    json=payload  # sets Content-Type automatically
)
print(response.status_code)  # 201 Created
new_task = response.json()
print('Created task ID:', new_task['id'])

PUT and PATCH — Updating Data

PUT replaces an entire resource with new data. PATCH updates only specific fields. Agents use PUT when they have the full updated object, and PATCH for partial changes like updating a task's status.

import requests

task_id = '42'

# PATCH: only update the status field
response = requests.patch(
    f'https://api.example.com/tasks/{task_id}',
    json={'status': 'completed'}
)
print(response.status_code)  # 200

# PUT: replace the whole task object
full_task = {
    'title': 'Research competitors',
    'assignee': 'agent-001',
    'priority': 'low',
    'status': 'completed'
}
response = requests.put(
    f'https://api.example.com/tasks/{task_id}',
    json=full_task
)
print(response.status_code)  # 200

DELETE — Removing Resources

DELETE removes a resource from the server. Agents use DELETE to clean up temporary data, remove processed tasks, or cancel scheduled jobs. Most DELETE requests have no body.

A successful delete typically returns 204 No Content — no body in the response.

import requests

task_id = '42'

response = requests.delete(
    f'https://api.example.com/tasks/{task_id}'
)

if response.status_code == 204:
    print('Task deleted successfully')
elif response.status_code == 404:
    print('Task not found — already deleted?')
else:
    print('Unexpected status:', response.status_code)

Status Codes: 2xx Success

Status codes tell your agent whether a request succeeded or failed. The 2xx range means success:

  • 200 OK — GET/PUT/PATCH returned data
  • 201 Created — POST created a new resource
  • 204 No Content — DELETE succeeded, no body returned

Always check the status code before processing the response body.

import requests

response = requests.post(
    'https://api.example.com/tasks',
    json={'title': 'New task'}
)

if response.status_code == 201:
    task = response.json()
    print('Created:', task['id'])
elif response.status_code == 200:
    print('Updated existing resource')
else:
    print('Unexpected code:', response.status_code)

Status Codes: 4xx Client Errors

4xx errors mean your agent sent a bad request. Common ones:

  • 400 Bad Request — invalid JSON or missing required field
  • 401 Unauthorized — missing or invalid API key
  • 404 Not Found — resource doesn't exist
  • 429 Too Many Requests — rate limit exceeded

These require your agent to fix the request, not retry blindly.

import requests

response = requests.get(
    'https://api.example.com/tasks/9999',
    headers={'Authorization': 'Bearer YOUR_KEY'}
)

if response.status_code == 401:
    print('AUTH ERROR: Check your API key')
elif response.status_code == 404:
    print('Task not found')
elif response.status_code == 429:
    retry_after = response.headers.get('Retry-After', 60)
    print(f'Rate limited. Wait {retry_after}s')
elif response.status_code == 400:
    print('Bad request:', response.json().get('error'))

Status Codes: 5xx Server Errors

5xx errors mean something went wrong on the server side — your agent did nothing wrong. Common ones:

  • 500 Internal Server Error — server bug or crash
  • 502 Bad Gateway — upstream service failure
  • 503 Service Unavailable — server overloaded or down

These are safe to retry after a short wait.

import requests
import time

def get_with_retry(url, headers, max_retries=3):
    for attempt in range(max_retries):
        response = requests.get(url, headers=headers)
        if response.status_code < 500:
            return response  # success or client error
        wait = 2 ** attempt
        print(f'Server error {response.status_code}, retrying in {wait}s...')
        time.sleep(wait)
    return response  # return last response after retries

Request Headers

Headers carry metadata with every request. The most important ones for agents:

  • Content-Type: application/json — tells the server your body is JSON
  • Authorization: Bearer TOKEN — authenticates your request
  • Accept: application/json — tells server you expect JSON back
  • User-Agent — identifies your client (some APIs require it)
import requests

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer sk-proj-abc123xyz',
    'Accept': 'application/json',
    'User-Agent': 'MyAgent/1.0'
}

response = requests.post(
    'https://api.example.com/analyze',
    headers=headers,
    json={'text': 'Analyze this document'}
)

print(response.json())

JSON Request and Response Body

Most modern APIs exchange data as JSON. When sending, use json=payload in requests (it serializes and sets headers automatically). When receiving, call response.json() to parse the body into a Python dict.

Always validate that the expected keys exist before accessing them.

import requests

# Send JSON body
response = requests.post(
    'https://api.example.com/summarize',
    json={
        'content': 'Long article text here...',
        'max_length': 150,
        'format': 'bullet_points'
    }
)

# Parse JSON response
result = response.json()

# Always check keys exist
summary = result.get('summary', 'No summary returned')
tokens_used = result.get('usage', {}).get('total_tokens', 0)

print('Summary:', summary)
print('Tokens used:', tokens_used)

Putting It All Together

A well-written agent wraps API calls with method selection, proper headers, status code checking, and JSON parsing in a clean helper function. This makes every API interaction consistent and easy to debug.

Use a Session object to reuse connections and share headers across multiple requests.

import requests

class APIClient:
    def __init__(self, base_url, api_key):
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        })

    def get(self, path, params=None):
        r = self.session.get(f'{self.base_url}{path}', params=params)
        r.raise_for_status()
        return r.json()

    def post(self, path, payload):
        r = self.session.post(f'{self.base_url}{path}', json=payload)
        r.raise_for_status()
        return r.json()

# Usage
client = APIClient('https://api.example.com', 'sk-proj-abc123')
tasks = client.get('/tasks', params={'status': 'open'})
new_task = client.post('/tasks', {'title': 'Write report'})

Quick Check: HTTP Methods

Test your understanding of HTTP methods and status codes.

HTTP Fundamentals Recap

You now know the HTTP foundation every agent relies on:

  • GET fetches, POST creates, PUT/PATCH updates, DELETE removes
  • 2xx = success, 4xx = your agent's fault, 5xx = server's fault
  • Headers carry auth (Authorization: Bearer) and format (Content-Type: application/json)
  • Use response.json() to parse the body and .get() to safely access fields
  • A Session object shares headers and connections across requests

With these basics solid, you can connect your agent to any REST API confidently.

Frequently asked questions

Is the “REST API Fundamentals for Agent Developers” lesson free?

Yes — the full text of “REST API Fundamentals for Agent Developers” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.

What will I learn in “REST API Fundamentals for Agent Developers”?

HTTP methods, status codes, headers, and JSON request/response format. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AI Agents?

No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “REST API Fundamentals for Agent Developers” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AI Agents lesson?

Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. REST API Fundamentals for Agent Developers
  2. Authentication: API Keys and OAuth
  3. Handling API Responses and Errors
  4. Rate Limiting and Retry Logic
← Back to AI Agents