Skip to main content

Route parameters and data types

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. In this tutorial, we are going to cover an essential aspect of FastAPI: Route Parameters and Data Types.

Route Parameters

Route parameters are parts of the URL path that can vary and are sent as parameters to your path operation function.

Let's consider a simple example. We'll create a FastAPI application that has an endpoint which returns a greeting to a user based on the username provided in the URL:

from fastapi import FastAPI

app = FastAPI()

@app.get("/greet/{username}")
async def greet_user(username: str):
return {"message": f"Hello, {username}!"}

Here, username acts as a route parameter. When you access the URL, for example /greet/John, FastAPI understands that username is John and sends it as an argument to the greet_user function.

Data Types

FastAPI is smart enough to understand Python standard types. It will automatically validate parameters based on their type.

Let's extend the previous example by adding an age parameter:

@app.get("/greet/{username}/{age}")
async def greet_user(username: str, age: int):
return {"message": f"Hello, {username}! You are {age} years old."}

In this case, FastAPI will validate that age is indeed an integer. If you try accessing /greet/John/thirty, FastAPI will respond with a detailed error about the incorrect data type.

Query Parameters

In addition to path parameters, FastAPI supports query parameters, which are usually optional parameters that come after the question mark in the URL.

For instance, consider the following code:

@app.get("/greet/{username}")
async def greet_user(username: str, morning: bool = False):
if morning:
return {"message": f"Good morning, {username}!"}
else:
return {"message": f"Hello, {username}!"}

The morning parameter is a query parameter. It's optional and has a default value of False. If you access /greet/John?morning=true, FastAPI will greet John with "Good morning".

Path Parameters with Predefined Values

You can also define path parameters with predefined values. FastAPI will validate that the parameter value matches one of the predefined values.

from typing import Literal
from fastapi import FastAPI

app = FastAPI()

@app.get("/model/{model_name}")
async def get_model(model_name: Literal["alexnet", "resnet", "vgg"]):
if model_name == "alexnet":
# return alexnet model
elif model_name == "resnet":
# return resnet model
elif model_name == "vgg":
# return vgg model

In the above code, the model_name parameter is limited to the values "alexnet", "resnet", and "vgg". If another value is provided, FastAPI will return an error.

This tutorial covered the basics of route parameters and the data types supported by FastAPI. By mastering these concepts, you'll be able to create more dynamic and flexible APIs that can handle a wide range of requests. Happy coding!