Type Validation and Automatic Docs¶
🎯 What You’ll Learn¶
- How FastAPI uses Python type hints to validate inputs
- What happens when invalid data is sent
- How FastAPI automatically generates interactive documentation
- What Swagger UI and ReDoc are, and how to use them
✅ Type Validation with Python Type Hints¶
FastAPI is built on top of Pydantic and Starlette, which allow it to use Python’s type hints to validate incoming data automatically.
This means:
- You define the expected type of each input (e.g.,
int,str,bool) - FastAPI converts and validates inputs for you
- If the input is invalid, FastAPI returns a helpful error message
🔢 Example: Validating Query Parameters¶
Let’s define an endpoint that adds two numbers:
from fastapi import FastAPI
app = FastAPI()
@app.get("/add")
def add(x: int, y: int):
return {"sum": x + y}
🧪 Try:
/add?x=3&y=4→ ✅{"sum": 7}/add?x=three&y=4→ ❌ Returns a 422 error
FastAPI automatically checks that x and y are integers. If not, it returns a structured error response:
{
"detail": [
{
"loc": ["query", "x"],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}
This is incredibly useful for frontend developers and API consumers — they know exactly what went wrong.
🔗 Example: Validating Path Parameters¶
@app.get("/square/{number}")
def square(number: int):
return {"result": number ** 2}
🧪 Try:
/square/5→ ✅{"result": 25}/square/five→ ❌ 422 error:"five"is not an integer
FastAPI enforces that number must be an integer and returns a clear error if it’s not.
🧠 Optional Parameters with Defaults¶
You can make parameters optional by assigning default values:
@app.get("/greet")
def greet(name: str = "Guest"):
return {"message": f"Hello, {name}!"}
🧪 Try:
/greet?name=Enrico→ ✅{"message": "Hello, Enrico!"}/greet→ ✅{"message": "Hello, Guest!"}
FastAPI will:
- Convert
"Enrico"to a string - Use
"Guest"if no name is provided
📚 Automatic API Documentation¶
FastAPI automatically generates documentation for your API using the OpenAPI standard (formerly known as Swagger). This includes:
- All endpoints
- Input and output types
- Example requests and responses
- Error formats
You get two documentation interfaces out of the box:
🔍 Swagger UI (/docs)¶
Swagger UI is an interactive web interface that lets you:
- Explore all your API endpoints
- See required parameters and types
- Try out requests directly from the browser
🧪 Visit: http://127.0.0.1:8000/docs
You’ll see something like this:
- A list of endpoints (e.g.,
/add,/square/{number}) - Each endpoint expands to show:
- Parameters
- Example values
- A “Try it out” button to test the endpoint
This is incredibly useful for developers and testers.
📘 ReDoc (/redoc)¶
ReDoc is another documentation interface, focused on readability and structure. It’s less interactive than Swagger UI but great for reference.
🧪 Visit: http://127.0.0.1:8000/redoc
You’ll see:
- A sidebar with all endpoints
- Detailed descriptions of parameters and responses
- Type annotations and schema definitions
🧠 Why This Matters¶
- You don’t need to write separate documentation — FastAPI does it for you
- Your API is self-documenting and easy to test
- Validation errors are clear and standardized
- Frontend developers can explore and test endpoints without needing Postman or curl
🧪 Combined Example¶
@app.get("/profile/{user_id}")
def get_profile(user_id: int, show_email: bool = False):
return {
"user_id": user_id,
"email": "user@example.com" if show_email else "hidden"
}
🧭 Try:
/profile/42→{"user_id": 42, "email": "hidden"}/profile/42?show_email=true→{"user_id": 42, "email": "user@example.com"}- Visit
/docs→ See this endpoint with type info and test it interactively
🧠 Practice Challenge¶
Create endpoints that:
- Accept a float and return its square root
- Accept a boolean flag to toggle a feature
- Accept a string and an integer, and return a formatted message
Then:
- Visit
/docsand/redoc - Try sending invalid inputs
- Observe how FastAPI handles validation and documents your API