Skip to main content

API Routing and HTTP Verbs for RESTful Endpoints

Following our first API with FastAPI in Creating Your First Web API with FastAPI, this article explores API Routing and HTTP Verbs for RESTful Endpoints. We'll learn how to structure our API with different routes and how to use the correct HTTP methods for each action.


📚 Prerequisites

  • A running FastAPI application.
  • Understanding of the basic structure of a FastAPI app.

🎯 Article Outline: What You'll Master

  • Path Operations: Using decorators like @app.post, @app.put, and @app.delete.
  • Path Parameters: Defining and validating parameters in the URL path.
  • Query Parameters: Defining and validating parameters in the URL query string.
  • Request Body: Receiving data in the request body for POST and PUT requests.

🧠 Section 1: The Core Concepts of Routing and HTTP Verbs

In a RESTful API, the combination of a URL endpoint and an HTTP verb defines a specific action.

  • GET: Retrieve a resource.
  • POST: Create a new resource.
  • PUT: Update an existing resource.
  • DELETE: Delete a resource.

FastAPI provides decorators for all these verbs.


💻 Section 2: Deep Dive - Implementation and Walkthrough

Let's build a simple in-memory "database" of items to demonstrate these concepts.

# main.py
from fastapi import FastAPI

app = FastAPI()

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]

@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]

@app.get("/items/{item_id}")
async def read_item(item_id: str):
# In a real app, you would fetch the item from a database
return {"item_id": item_id}

@app.post("/items/")
async def create_item(item: dict):
fake_items_db.append(item)
return item

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: dict):
return {"item_id": item_id, **item}

@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
return {"item_id": item_id}

Step-by-Step Code Breakdown:

  • @app.get("/items/"): This route handles GET requests to /items/ and uses query parameters skip and limit for pagination.
  • @app.post("/items/"): This route handles POST requests to create a new item. The item is received in the request body.
  • @app.put("/items/{item_id}"): This route handles PUT requests to update an item. It has a path parameter item_id and receives the updated data in the request body.
  • @app.delete("/items/{item_id}"): This route handles DELETE requests to delete an item.

💡 Conclusion & Key Takeaways

You've learned how to create a variety of routes in FastAPI using different HTTP verbs, path parameters, query parameters, and request bodies.

Let's summarize the key takeaways:

  • FastAPI provides decorators for all standard HTTP methods.
  • Path parameters are defined in the URL path with curly braces.
  • Query parameters are defined as function arguments with default values.
  • The request body is also defined as a function argument, typically using a Pydantic model (which we'll cover next).

➡️ Next Steps

In the next article, "Request and Response Bodies: Pydantic models", we will see how to define and validate the data we send and receive in our API.


Glossary

  • Routing: The process of directing an incoming request to the correct function to handle it.
  • Path Parameter: A parameter that is part of the URL path.
  • Query Parameter: A parameter that is part of the URL query string.
  • Request Body: The data sent in the body of an HTTP request, typically for POST and PUT requests.

Further Reading