Creating Multiple Endpoints¶
🎯 Goal¶
Learn how to define multiple endpoints in FastAPI, understand how routing works, and explore how different HTTP methods map to different actions.
🧠 Key Concepts¶
- Endpoint: A URL path that triggers a specific function in your API.
- Route: The combination of an HTTP method (GET, POST, etc.) and a path (e.g.,
/status) that defines how the server responds. - Decorator: A Python syntax (
@app.get(...)) used to register a function as a route handler.
🛠️ Step-by-Step: Defining Multiple Routes¶
Let’s start with a basic FastAPI app and add several endpoints.
📄 main.py¶
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def home():
return {"message": "Welcome to the FastAPI course!"}
@app.get("/status")
def status():
return {"status": "OK", "uptime": "24h"}
@app.get("/about")
def about():
return {"author": "Enrico", "course": "FastAPI Mastery"}
🧪 Try It Out¶
Run the server:
uvicorn main:app --reload
Then visit these URLs in your browser or use a tool like httpie or curl:
http://127.0.0.1:8000/→ Welcome messagehttp://127.0.0.1:8000/status→ Status infohttp://127.0.0.1:8000/about→ Course metadata
🔄 Using Different HTTP Methods¶
FastAPI supports all major HTTP methods. Let’s add a POST endpoint.
@app.post("/feedback")
def submit_feedback():
return {"message": "Feedback received!"}
@app.post(...)handles POST requests.- You can also use
@app.put,@app.delete,@app.patch, etc.
🧪 Try sending a POST request with httpie:
http POST http://127.0.0.1:8000/feedback
🧩 Organizing Routes Logically¶
As your app grows, group endpoints by purpose:
@app.get("/users")
def list_users():
return {"users": ["Alice", "Bob"]}
@app.get("/tasks")
def list_tasks():
return {"tasks": ["Buy milk", "Write code"]}
This structure makes it easier to scale and modularize later.
🧠 Practice Challenge¶
Add these endpoints to your app:
/ping→ returns{"pong": true}/version→ returns{"version": "1.0.0"}/time→ returns current server time (usedatetime.now())