Description
Routes define API endpoints and the HTTP methods used to access them.
In FastAPI, you can create different routes for different operations. For example, you can use:
GETto retrieve dataPOSTto create dataDELETEto delete data
Each route is connected to a Python function that runs when the endpoint is requested.
Code
from fastapi import FastAPI
app = FastAPI()
@app.get("/users")
def get_users():
return {"message": "Get users"}
@app.post("/users")
def create_user():
return {"message": "Create user"}
@app.delete("/users")
def delete_users():
return {"message": "Delete users"}
GET Route
@app.get("/users")
def get_users():
return {"message": "Get users"}
This creates a GET endpoint at:
/users
When a client sends a GET request to /users, the get_users() function is executed.
POST Route
@app.post("/users")
def create_user():
return {"message": "Create user"}
This creates a POST endpoint at:
/users
The create_user() function is executed when a client sends a POST request.
DELETE Route
@app.delete("/users")
def delete_users():
return {"message": "Delete users"}
This creates a DELETE endpoint at:
/users
The delete_users() function is executed when a client sends a DELETE request.
Output
The available API routes are:
GET /users
POST /users
DELETE /users
Each HTTP method performs a different operation on the /users endpoint.
Summary
FastAPI allows you to define API routes using decorators such as:
@app.get()
@app.post()
@app.delete()
The route determines which URL the client accesses, while the HTTP method determines what type of operation is being performed.