Skip to content
AgenticAIWiki
  1. Learn
  2. Part 0
  3. 1. Engineering prerequisites for AI apps
  4. 1.4

Lesson 1.4 · 4 of 7 · 7 min read · Reviewed 24 Nov 2026

HTTP APIs: methods, status codes and JSON Schema

By the end, you can

  • Read an HTTP request and response: method, path, headers, status code and JSON body.
  • Decide what to do for each family of status codes, and describe a request body with JSON Schema.

Every model SDK is a thin wrapper over HTTP. When something breaks, the SDK shows you an HTTP status code and a JSON error. Knowing how to read them saves hours.

Anatomy of a request

POST /v1/messages HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer <token from an environment variable>

{"model": "<model id>", "max_tokens": 300, "messages": [{"role": "user", "content": "Hi"}]}
Part What it says
Method What kind of action. GET reads, POST creates or runs something, PUT/PATCH update, DELETE removes
Path Which resource or endpoint
Headers Metadata: content type, authentication, API version
Body The JSON payload (usually only on POST, PUT, PATCH)

GET should be safe to repeat. A POST that sends a message or charges a card may not be, which matters when you retry (lesson 1.7).

Status codes by family

Code Meaning What your code should do
200 Worked Parse the body
400 Bad request: missing field, wrong type Fix the request. Do not retry unchanged
401 Not authenticated: missing or invalid key Check the key. Do not retry
403 Authenticated, but not allowed Check permissions or the account
404 No such endpoint or resource Check the URL or id
413 Request too large Send less
429 Rate limited Wait (honour retry-after) and retry
500, 502, 503 Server-side failure Retry with backoff
529 or other overload codes Provider overloaded (some APIs) Retry with backoff

The rule of thumb: 4xx means you, 5xx means them. The one 4xx you retry is 429429 error: The HTTP status for too many requests: you hit a rate limit., because “too many requests” fixes itself with time.

Read the error body too. Most APIs return JSON like {"type": "error", "error": {"type": "invalid_request_error", "message": "..."}}. Log the message and any request id the response carries: support teams ask for it.

JSON Schema

JSON Schema is a standard way to describe what a JSON value must look like. You will meet it every time you define a tool:

{
  "type": "object",
  "properties": {
    "city": { "type": "string", "description": "City name, for example Lisbon" },
    "days": { "type": "integer", "minimum": 1, "maximum": 7 }
  },
  "required": ["city"]
}

This says: an object, with a string city that must be present and an optional whole number days from 1 to 7. The model reads the schema to decide what to send. Your code should still validate the input it receives (lesson 1.2): the schema guides the model, validation protects your code.

Common mistakes

  • Retrying every error, including 400s and 401s, which burns quota and hides the bug.
  • Ignoring the error message and logging only the status code.
  • Forgetting Content-Type: application/json, so the server cannot read the body.
  • Writing a schema with no required list, so every field is optional by accident.

Key points

  • A request has a method (GET reads, POST creates or runs something), a URL, headers and an optional JSON body.
  • Status codes come in families: 2xx worked, 4xx your request was wrong, 5xx the server had a problem.
  • Retry 429 and most 5xx errors. Do not retry other 4xx errors: fix the request, the key or the permissions instead.
  • JSON Schema describes the shape of a JSON value. Model APIs use it for tool inputs and structured output.
Hands-on labRuns in the Playground

Map status codes to actions

Decide what code should do for each HTTP status, and check a request body against a small JSON Schema.

You will have: An action function for nine status codes and a validator for a tool input schema with required fields and ranges.

Steps

  1. Write action(status): parse on 2xx, retry on 429 and 5xx, fix access on 401 and 403, fix the request on other 4xx.
  2. Run it over the list of codes and check each answer against the lesson's table.
  3. Write check(value, schema) for type, required, minimum and maximum.
  4. Run it on the four sample bodies and read each error.

Done when

  • 429 and every 5xx map to retry; 400 and 413 map to fixing the request.
  • The body with no city reports "missing required field: city".
  • days of 10 is reported as above the maximum of 7.

Open in the Playground No API key needed.

Starter code (Python)
def action(status):
    # TODO: 2xx -> "parse the body"; 429 or 5xx -> "retry with backoff";
    #       401/403 -> "fix key or access"; any other 4xx -> "fix the request"
    return "unknown"

for code in [200, 400, 401, 403, 413, 429, 500, 503, 529]:
    print(f"{code} -> {action(code)}")

SCHEMA = {
    "type": "object",
    "properties": {
        "city": {"type": "string"},
        "days": {"type": "integer", "minimum": 1, "maximum": 7},
    },
    "required": ["city"],
}

def check(value, schema):
    errors = []
    # TODO: report "missing required field: <name>" for each name in schema["required"]
    # TODO: for each property present, check its type and any minimum/maximum
    return errors

for body in [{"city": "Lisbon", "days": 3}, {"days": 3}, {"city": "Oslo", "days": 10}, {"city": 42}]:
    print(body, "->", check(body, SCHEMA) or "valid")
Show a solution
def action(status):
    if 200 <= status < 300:
        return "parse the body"
    if status == 429 or status >= 500:
        return "retry with backoff"
    if status in (401, 403):
        return "fix key or access"
    return "fix the request"

for code in [200, 400, 401, 403, 413, 429, 500, 503, 529]:
    print(f"{code} -> {action(code)}")

SCHEMA = {
    "type": "object",
    "properties": {
        "city": {"type": "string"},
        "days": {"type": "integer", "minimum": 1, "maximum": 7},
    },
    "required": ["city"],
}
TYPES = {"string": str, "integer": int, "object": dict}

def check(value, schema):
    """A tiny subset of JSON Schema: type, properties, required, minimum, maximum."""
    errors = []
    if not isinstance(value, TYPES[schema["type"]]) or isinstance(value, bool):
        return [f"expected {schema['type']}"]
    for name in schema.get("required", []):
        if name not in value:
            errors.append(f"missing required field: {name}")
    for name, sub in schema.get("properties", {}).items():
        if name in value:
            v = value[name]
            if not isinstance(v, TYPES[sub["type"]]) or isinstance(v, bool):
                errors.append(f"{name}: expected {sub['type']}")
            elif "minimum" in sub and v < sub["minimum"]:
                errors.append(f"{name}: below minimum {sub['minimum']}")
            elif "maximum" in sub and v > sub["maximum"]:
                errors.append(f"{name}: above maximum {sub['maximum']}")
    return errors

for body in [{"city": "Lisbon", "days": 3}, {"days": 3}, {"city": "Oslo", "days": 10}, {"city": 42}]:
    print(body, "->", check(body, SCHEMA) or "valid")
Quick checkA call to a model API returns 400 with the message "max_tokens: field required". What should your code do?
How sure are you?
Pick an answer and how sure you are