
FastAPI
Path converters allow FastAPI to automatically convert path parameters to specific types and validate them.
Path converters are rules that transform URL path segments into Python objects. FastAPI handles this automatically using type hints.
@app.get("/items/{item_name}")
async def get_item(item_name: str):
# item_name is always a string
return {"item": item_name}URL Examples:
@app.get("/items/{item_id}")
async def get_item(item_id: int):
# item_id must be an integer
return {"id": item_id}URL Examples:
@app.get("/coordinates/{latitude}")
async def get_location(latitude: float):
return {"lat": latitude}URL Examples:
from uuid import UUID
@app.get("/users/{user_id}")
async def get_user(user_id: UUID):
# Validates UUID format
return {"user_id": user_id}URL Examples:
from fastapi import FastAPI
app = FastAPI()
@app.get("/files/{file_id}")
async def get_file(file_id: int):
'''
FastAPI automatically:
1. Extracts "file_id" from URL path
2. Validates it's an integer
3. Converts it to Python int
4. Returns 422 if validation fails
'''
return {"file_id": file_id, "type": type(file_id).__name__}# Product catalog with different parameter types
@app.get("/products/{product_id}")
async def get_product(product_id: int):
# ID as integer
return {"product_id": product_id}
@app.get("/search/{query}")
async def search(query: str):
# Search term as string
return {"search": query, "results": []}
@app.get("/prices/{price}")
async def filter_by_price(price: float):
# Price as float for decimal values
return {"min_price": price}from typing import Optional
@app.get("/users/{user_id}")
async def get_user(user_id: int):
# This type hint: int
# Automatically creates an integer converter
# Works: /users/123
# Fails: /users/abc
return {"user_id": user_id}When validation fails, FastAPI returns detailed error:
@app.get("/items/{item_id}")
async def get_item(item_id: int):
return {"item_id": item_id}
# Request: GET /items/invalid
# Response: 422 Unprocessable Entity
# Detail: "value is not a valid integer"Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward