2.5 Hours

3. Routing & HTTP Methods

Core Concepts

Routing is how your API maps incoming HTTP requests to specific functions that handle them. Each route consists of a URL path and an HTTP method. FastAPI provides decorators for all standard HTTP methods, making it intuitive to build RESTful APIs. To test these examples locally, save the code to main.py and run uvicorn main:app --reload.

What is an HTTP Method?

HTTP methods (also called verbs) indicate the desired action to be performed on a resource. Each method has a specific meaning and use case in RESTful API design.

  • GET — Retrieve data. Should never change anything on the server. GET requests are idempotent (making the same request multiple times has the same effect).
  • POST — Create new resources. Sends data to the server to create something new. POST requests are NOT idempotent.
  • PUT — Replace an entire resource. Requires the complete resource data. PUT is idempotent.
  • PATCH — Partially update a resource. Only sends the fields that need to change. PATCH is NOT idempotent.
  • DELETE — Remove a resource. DELETE is idempotent.

Idempotency Explained

An idempotent operation means that making the same request multiple times produces the same result as making it once. GET, PUT, and DELETE are idempotent. POST is not — sending the same POST request twice typically creates two separate resources.

Basic Route Decorators

FastAPI uses Python decorators to associate HTTP methods with functions. The decorator name matches the HTTP method you want to handle. To test these, save to main.py and run uvicorn, then use curl or visit http://localhost:8000/docs.

Python 3
from fastapi import FastAPI

app = FastAPI()

# GET method - retrieve data
@app.get("/users")
def get_users():
    return [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]

# POST method - create data
@app.post("/users")
def create_user(name: str, email: str):
    return {"id": 3, "name": name, "email": email}

# PUT method - replace entire resource
@app.put("/users/{user_id}")
def update_user(user_id: int, name: str, email: str):
    return {"id": user_id, "name": name, "email": email, "updated": True}

# DELETE method - remove resource
@app.delete("/users/{user_id}")
def delete_user(user_id: int):
    return {"message": f"User {user_id} deleted"}
Local Testing: Run uvicorn main:app --reload, then open http://localhost:8000/docs. You can test all HTTP methods directly from the interactive documentation.

Route Paths and Organization

Routes should be organized logically around resources (nouns), not actions (verbs). This is a core principle of RESTful API design.

Python 3
# GOOD RESTful design (resources as nouns)
@app.get("/users")           # Get all users
@app.get("/users/{id}")      # Get one user
@app.post("/users")          # Create a user
@app.put("/users/{id}")      # Replace a user
@app.delete("/users/{id}")   # Delete a user

# BAD design (actions as verbs) - DO NOT DO THIS
# @app.get("/getAllUsers")
# @app.post("/createUser")
# @app.post("/deleteUser")
Never put verbs in your URLs! The HTTP method already indicates the action. /getUsers should just be /users with a GET request.

Nested Resources

When resources have relationships, you can nest routes to show hierarchy. For example, a user has many posts.

Python 3
# Nested routes show relationships
@app.get("/users/{user_id}/posts")
def get_user_posts(user_id: int):
    return {"user_id": user_id, "posts": ["Post 1", "Post 2"]}

@app.post("/users/{user_id}/posts")
def create_user_post(user_id: int, title: str):
    return {"user_id": user_id, "post": {"title": title, "id": 1}}

@app.get("/users/{user_id}/posts/{post_id}")
def get_specific_post(user_id: int, post_id: int):
    return {"user_id": user_id, "post_id": post_id, "content": "Post content"}

Customizing Response Status Codes

By default, FastAPI returns 200 OK for successful GET requests and 201 Created for POST requests. You can customize status codes using the status_code parameter.

Python 3
from fastapi import FastAPI, status

app = FastAPI()

# Custom status code for successful creation
@app.post("/items", status_code=status.HTTP_201_CREATED)
def create_item(name: str):
    return {"name": name, "id": 1}

# Custom status code for deletion (204 No Content)
@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item(item_id: int):
    return None

# Custom status code for accepted but not processed yet
@app.post("/jobs", status_code=status.HTTP_202_ACCEPTED)
def create_job(task: str):
    return {"message": "Job accepted", "job_id": 123}

Route Order Matters

FastAPI evaluates routes in the order they are defined. More specific routes should come before more general ones.

Python 3
# CORRECT: Specific route first
@app.get("/users/me")
def get_current_user():
    return {"user": "current logged in user"}

@app.get("/users/{user_id}")
def get_user(user_id: int):
    return {"user_id": user_id}

# WRONG: General route first would capture "/users/me"
# @app.get("/users/{user_id}")
# def get_user(user_id: int):
# return {"user_id": user_id}

Tags for API Documentation Organization

Use the tags parameter to group related endpoints in the automatic documentation. This makes your API documentation much more organized.

Python 3
# Group endpoints by feature using tags
@app.get("/users", tags=["Users"])
def get_users():
    return [{"id": 1, "name": "Alice"}]

@app.post("/users", tags=["Users"])
def create_user(name: str):
    return {"id": 2, "name": name}

@app.get("/products", tags=["Products"])
def get_products():
    return [{"id": 1, "name": "Laptop"}]

@app.post("/orders", tags=["Orders"])
def create_order(product_id: int):
    return {"order_id": 1, "product_id": product_id}
Local Testing: After adding tags, visit http://localhost:8000/docs. You will see your endpoints grouped into collapsible sections by tag name.

Summary of HTTP Method Best Practices

  • GET — Use for reading data. Never modify state. Cacheable. Safe and idempotent.
  • POST — Use for creating new resources. Not idempotent. Request body contains the data to create.
  • PUT — Use for completely replacing an existing resource. Requires full resource data. Idempotent.
  • PATCH — Use for partial updates. Only send the fields that need to change. Not idempotent.
  • DELETE — Use for removing resources. Idempotent. Usually returns 204 No Content on success.
To run these examples: Save the code to main.py, run uvicorn main:app --reload, and open http://localhost:8000/docs to test all endpoints interactively.

Knowledge Check

Ready to test your understanding of 3. Routing & HTTP Methods?

Back