To define routes, we attach an HTTP method decorator (like
@app.get()or@app.post()) to a standard Python function and use type hints to declare inputs.In FastAPI, decorators (such as @app.get("/") or @app.post("/items/")) are routing wrappers that bind a standard Python function to a specific HTTP URL path and request method. They tell FastAPI which code to run when a client sends a request to that endpoint, while automatically handling data parsing, validation, and API documentation.
Handling Different Types of Route Inputs:
Path Parameters (Dynamic URL segments)
Query Parameters (URL key-value pairs)
Request Body (JSON Payloads)
Basic Route Definition: Every path operation combines two parts: the path (the URL endpoint starting with /) and the operation (the HTTP method).
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello")
async def say_hello():
return {"message": "Hello World"}