0
0
FastAPIframework~5 mins

Route decorator syntax in FastAPI

Choose your learning style9 modes available
Introduction

Route decorators tell FastAPI which web address should run a specific function. They connect URLs to your code.

When you want to create a web page or API endpoint for users to visit.
When you need to handle different HTTP methods like GET or POST for a URL.
When you want to organize your web app by linking URLs to functions clearly.
When you want to add parameters to URLs and get data from users.
When you want to build REST APIs that respond to client requests.
Syntax
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.

Examples
This creates a GET route at the root URL that returns a simple message.
FastAPI
@app.get("/")
def read_root():
    return {"message": "Hello World"}
This creates a POST route at /items that accepts data and returns it.
FastAPI
@app.post("/items")
def create_item(item: dict):
    return {"item": item}
This route uses a path parameter to get a user ID from the URL.
FastAPI
@app.get("/users/{user_id}")
def read_user(user_id: int):
    return {"user_id": user_id}
Sample Program

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.

FastAPI
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}!"}
OutputSuccess
Important Notes

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.

Summary

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.