Module 2 — Path & Query Parameters
This module teaches you how to handle path parameters and query parameters in FastAPI. FastAPI automatically validates types and auto-documents your API.
1. Path Parameters
Path parameters are part of the URL structure.
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def get_item(item_id: int): return {"item_id": item_id}
2. Query Parameters
Query parameters come after the ? in the URL.
from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/search") async def search_items(q: Optional[str] = None, limit: int = 10): return {"query": q, "limit": limit}
3. Combining Path + Query Parameters
from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/products/{product_id}") async def read_product(product_id: int, q: Optional[str] = None, short: bool = False): return { "product_id": product_id, "query": q, "short_description": short }
No comments:
Post a Comment