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

Handling Missing and Invalid Parameters

Implement clear error responses for missing required fields, invalid types, and out-of-range values in API requests.

Handling Missing and Invalid Parameters

What You'll Learn

You'll learn how to implement clear, actionable error responses when API requests have missing required fields, invalid data types, or values outside acceptable ranges.

Why Error Handling Matters

Think of your API like a restaurant order form. If someone submits an order with no dish selected, asks for "seven" pizzas (when you need an integer), or requests -3 servings, you need to politely explain what went wrong before sending it to the kitchen.

In LLM APIs, bad requests waste tokens, processing time, and frustrate users. Clear error messages help developers fix issues immediately.

Core Error Categories

Missing Required Fields: A request arrives without a prompt or model_name that your endpoint expects.

Invalid Types: Someone sends temperature: "hot" instead of temperature: 0.7.

Out-of-Range Values: A max_tokens value of -50 or a temperature of 5.0 (when valid range is 0.0-2.0).

Implementation Pattern

Pydantic (covered in lesson 975) already validates types and required fields automatically. For custom range validation, use Pydantic's validators:

from pydantic import BaseModel, Field, field_validator

class LLMRequest(BaseModel):
    prompt: str
    temperature: float = Field(ge=0.0, le=2.0)
    max_tokens: int = Field(gt=0, le=4000)
    
    @field_validator('prompt')
    def prompt_not_empty(cls, v):
        if not v.strip():
            raise ValueError("Prompt cannot be empty or whitespace")
        return v

FastAPI automatically returns HTTP 422 with detailed error descriptions showing which field failed and why.

Key Takeaway: Use Pydantic's Field constraints and custom validators to catch missing, invalid, or out-of-range parameters before they reach your LLM, returning clear, structured error messages that developers can act on immediately.