Junior — Middle
How can you determine the HTTP request method in an application using FastAPI?
sobes.tech AI
Answer from AI
In FastAPI, the HTTP request method is specified using decorators that correspond to the methods: @app.get(), @app.post(), @app.put(), @app.delete(), etc.
Example:
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/items")
async def read_items():
return {"method": "GET"}
@app.post("/items")
async def create_item():
return {"method": "POST"}
# To define a method dynamically inside a handler
@app.api_route("/items", methods=["GET", "POST"])
async def handle_items(request: Request):
return {"method": request.method}
Thus, the HTTP request method is set via the decorator, and inside the handler, it can be accessed through the Request object.