Route decorators tell FastAPI which web address should run a specific function. They connect URLs to your code.
Route decorator syntax in FastAPI
@app.<http_method>("/path") def function_name(): # code to run return response
The @app.get(), @app.post(), etc., are decorators that tell FastAPI which HTTP method and path to use.
The function below the decorator runs when someone visits that URL with that method.
@app.get("/") def read_root(): return {"message": "Hello World"}
@app.post("/items") def create_item(item: dict): return {"item": item}
@app.get("/users/{user_id}") def read_user(user_id: int): return {"user_id": user_id}
This FastAPI app has two routes: one at the root URL that welcomes users, and one that greets a user by name from the URL.
from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"message": "Welcome to FastAPI!"} @app.get("/hello/{name}") def say_hello(name: str): return {"greeting": f"Hello, {name}!"}
Route decorators must be placed directly above the function they decorate.
Use different HTTP methods like get, post, put, delete depending on what action you want.
Path parameters are defined with curly braces in the route string and become function arguments.
Route decorators link URLs and HTTP methods to Python functions.
They help build web APIs by defining what code runs on each URL.
FastAPI uses simple syntax with @app.get(), @app.post(), etc. to create routes.