How to Create Routes in FastAPI: Simple Guide
In FastAPI, you create a route by defining a path operation function decorated with
@app.get(), @app.post(), or other HTTP method decorators on an FastAPI app instance. The decorator specifies the URL path, and the function defines the response for that route.Syntax
To create a route in FastAPI, you use a decorator on a function that handles requests. The decorator defines the HTTP method and the URL path. The function returns the response data.
- @app.get(path): Handles GET requests to the given path.
- @app.post(path): Handles POST requests.
- path: The URL path as a string, e.g.,
"/items/{item_id}". - function: The function runs when the route is accessed and returns the response.
python
from fastapi import FastAPI app = FastAPI() @app.get("/path") def function_name(): return {"message": "response"}
Example
This example shows how to create a simple GET route at /hello that returns a greeting message as JSON.
python
from fastapi import FastAPI app = FastAPI() @app.get("/hello") def say_hello(): return {"message": "Hello, FastAPI!"}
Output
When you run this FastAPI app and visit http://localhost:8000/hello in a browser or API client, you get the JSON response: {"message": "Hello, FastAPI!"}
Common Pitfalls
Common mistakes when creating routes in FastAPI include:
- Forgetting to create the
FastAPI()app instance before defining routes. - Using the wrong decorator for the HTTP method (e.g., using
@app.getfor POST requests). - Not including the path string in the decorator.
- Defining functions without returning a valid response (like a dict or Pydantic model).
Example of a wrong and right way:
python
from fastapi import FastAPI app = FastAPI() # Wrong: missing path string # @app.get() def no_path(): return {"error": "No path defined"} # Right: @app.get("/correct") def correct_path(): return {"message": "This works"}
Quick Reference
| Decorator | Purpose | Example |
|---|---|---|
| @app.get(path) | Handles GET requests | @app.get("/items") |
| @app.post(path) | Handles POST requests | @app.post("/items") |
| @app.put(path) | Handles PUT requests | @app.put("/items/{id}") |
| @app.delete(path) | Handles DELETE requests | @app.delete("/items/{id}") |
Key Takeaways
Create routes by decorating functions with HTTP method decorators on a FastAPI app instance.
Always specify the URL path as a string in the decorator.
Return JSON-serializable data like dicts from route functions.
Use the correct decorator matching the HTTP method you want to handle.
Initialize your FastAPI app before defining routes.