Defining routes
FastAPI provides an intuitive way to define routes, which are the different endpoints or paths your app will respond to. Understanding how to define routes is crucial to building your applications. In this tutorial, we will cover how to define routes.
What is a Route?
A route is a specific endpoint in your application. It's defined by a URL pattern, and when that URL is requested, a specific function is executed. The function is also known as the route handler. In FastAPI, you define routes using Python's decorator syntax.
Basic Route Definition
Here's how to define a basic route in FastAPI:
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def home():
return {"message": "Hello, World!"}
In this example, we're using the get
decorator to tell FastAPI that this function should be called when a GET
request is made to the /
URL. When a GET
request is made to the root URL (/
), FastAPI will call the home
function and return the resulting dictionary as a JSON response.
Route Parameters
You can define routes that include parameters. This allows you to capture values from the path itself. Here's an example:
@app.get('/items/{item_id}')
def read_item(item_id: int):
return {"item_id": item_id}
In this example, item_id
is a parameter that's part of the URL. When you make a request to /items/42
, FastAPI will call read_item
with item_id
set to 42
.
Optional Parameters
You can define optional parameters by giving them a default value in your function:
@app.get('/items/{item_id}')
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
In this example, q
is an optional query parameter. If you don't provide it when making a request, its value will be None
.
More HTTP Methods
FastAPI supports all the common HTTP methods. You can define routes for POST
, PUT
, DELETE
, and others just like you do for GET
:
@app.post('/items/')
def create_item(item: dict):
return {"item": item}
In this example, we're defining a POST
route that accepts a JSON body (represented as a Python dictionary).
Summary
We've covered the basics of defining routes in FastAPI. You learned how to define GET
and POST
routes, how to include parameters in your routes, and how to handle optional parameters. Practice these concepts and experiment with defining different kinds of routes. That's the best way to get comfortable with them.