Course contentsShow
← AI Engineering
Lesson 978 of 1,88624. Building AI APIsFree lesson

Error Response Standards and HTTP Status Codes

Design consistent error response schemas with appropriate HTTP status codes (400, 422, 500) for different failure types.

Error Response Standards and HTTP Status Codes

What you'll learn: How to design consistent, informative error responses with the right HTTP status codes for different types of failures in your LLM API.

Why Error Standards Matter

When your LLM API encounters problems—invalid input, model failures, or server crashes—clients need clear, actionable feedback. A consistent error response format helps developers debug issues quickly and build robust error handling into their applications.

Core HTTP Status Codes for AI APIs

400 Bad Request: The client sent something fundamentally wrong—malformed JSON, missing required fields, or invalid parameter types. This is a client-side error they can fix immediately.

422 Unprocessable Entity: The request was well-formed, but semantically invalid. For example, the prompt exceeds your token limit (which you validated in the previous lesson), or temperature is set to 5.0 when max is 2.0. The client needs to adjust their values.

500 Internal Server Error: Something broke on your side—the LLM service crashed, a database connection failed, or an unexpected exception occurred. The client can't fix this; they should retry later or contact support.

Standard Error Response Schema

Design a consistent structure using Pydantic:

from pydantic import BaseModel

class ErrorDetail(BaseModel):
    error_type: str
    message: str
    field: str | None = None

This gives clients predictable information: what went wrong (error_type), a human-readable explanation (message), and optionally where it happened (field).

Analogy

Think of HTTP status codes like traffic signs: a red light (400) means you took a wrong turn, a yield sign (422) means you need to adjust your approach, and a detour (500) means the road itself has problems.

Key Takeaway: Use 400 for malformed requests, 422 for validation failures, and 500 for server-side errors, with a consistent JSON schema that helps clients understand and fix issues.