/hello?from fastapi import FastAPI app = FastAPI() @app.get('/hello') async def say_hello(): return {'message': 'Hello, FastAPI!'}
The @app.get('/hello') decorator creates a GET route at '/hello'. The function returns a dictionary, which FastAPI automatically converts to JSON. So the response is JSON with the key 'message' and value 'Hello, FastAPI!'.
/submit. Which decorator syntax is correct?FastAPI uses decorators like @app.post() for POST routes. The syntax @app.route() is from Flask, not FastAPI. There is no @app.post_method() in FastAPI.
from fastapi import FastAPI app = FastAPI() @app.get('/items/{item_id}') async def read_item(item_id: int): return {'item_id': item_id} @app.get('/items/{item_id}') async def read_item_duplicate(item_id: int): return {'item_id_duplicate': item_id}
FastAPI does not allow two routes with the same path and HTTP method. Defining two @app.get('/items/{item_id}') routes causes a runtime error about duplicate routes.
/users/42?active=true?from fastapi import FastAPI app = FastAPI() @app.get('/users/{user_id}') async def get_user(user_id: int, active: bool = False): return {'user_id': user_id, 'active': active}
The path parameter user_id is 42 as an integer. The query parameter active is passed as 'true' and converted to boolean True. So the response JSON reflects these values.
@app.get() and @app.post() on the same function?from fastapi import FastAPI app = FastAPI() @app.get('/multi') @app.post('/multi') async def multi_method(): return {'message': 'Works for GET and POST'}
FastAPI allows stacking multiple HTTP method decorators on the same function. This creates multiple routes for the same path but different methods. So the function handles both GET and POST requests at '/multi'.