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.
Practice
@app.get("/items") decorator do in FastAPI?Solution
Step 1: Understand the decorator purpose
The@app.get()decorator in FastAPI is used to create a route that listens for HTTP GET requests.Step 2: Match the URL path
The string inside the parentheses, here '/items', specifies the URL path this route will respond to.Final Answer:
It creates a route that responds to GET requests at the URL path '/items'. -> Option DQuick Check:
@app.get() = GET route [OK]
- Confusing @app.get with @app.post
- Thinking it runs on server start
- Assuming it deletes routes
Solution
Step 1: Identify the correct decorator for POST
FastAPI uses@app.post()to define routes that handle POST requests.Step 2: Check the path argument
The path '/submit' should be passed as a string inside the parentheses.Final Answer:
@app.post('/submit') -> Option AQuick Check:
POST route syntax = @app.post(path) [OK]
- Using @app.get for POST routes
- Trying to pass method='POST' inside @app.post
- Using @app.route which is not FastAPI syntax
from fastapi import FastAPI
app = FastAPI()
@app.get('/hello')
def say_hello():
return {"message": "Hello, FastAPI!"}Solution
Step 1: Identify the route and method
The route '/hello' is defined with@app.get('/hello'), so GET requests to '/hello' will callsay_hello().Step 2: Check the function return value
The function returns a dictionary with key 'message' and value 'Hello, FastAPI!'. FastAPI automatically converts this to JSON.Final Answer:
"{\"message\": \"Hello, FastAPI!\"}" -> Option CQuick Check:
Route returns dict = JSON response [OK]
- Expecting plain string instead of JSON
- Assuming 404 error without route
- Confusing error codes with correct response
from fastapi import FastAPI
app = FastAPI()
@app.get('/data')
def get_data():
print("Fetching data")
return {"data": 123}Solution
Step 1: Check function body indentation
Python requires the function body to be indented. Here,print("Fetching data")is not indented properly.Step 2: Verify decorator and path syntax
The decorator@app.get('/data')is correct, and the path starting with '/' is valid in FastAPI.Final Answer:
Indentation error in the function body. -> Option AQuick Check:
Python functions need indented bodies [OK]
- Ignoring Python indentation rules
- Thinking path cannot start with '/'
- Assuming decorator needs no parentheses
Solution
Step 1: Understand FastAPI route decorators
FastAPI does not have a combined decorator for multiple methods. Instead, you add multiple decorators for each method on the same function.Step 2: Check each option's validity
@app.get('/process') @app.post('/process') uses two decorators@app.getand@app.poston the same function, which is correct. @app.route('/process', methods=['GET', 'POST']) uses Flask-style syntax which is invalid in FastAPI. Options A and D use non-existent decorators or invalid parameters.Final Answer:
@app.get('/process') @app.post('/process') -> Option BQuick Check:
Multiple decorators for multiple methods [OK]
- Trying to use Flask-style @app.route
- Assuming combined decorator exists
- Passing methods param to @app.get
Ready to prove it?
Pass the test and this pattern moves unknown
