🍎Unit 10: Path Parameters and Validations
Introduction
The Annotated
type, introduced in Python 3.9 from the typing
module, allows for extending type hints with Python objects, which can be particularly useful for providing extra metadata or validation in FastAPI.
With the Annotated
type, you can add metadata to your path parameters, making your API self-documenting and enabling automatic request validation. This is particularly useful for enhancing the functionality of path parameters with validations or constraints directly in your FastAPI endpoints.
Path Parameters
Let's take a quick look of using query parameter in FastAPI:
In the above program, the title
is a metadata of the item_id
path parameter. And you should note that the query parameter q
is defined by an alias item-query
, it thus makes the URL to this API endpoint is as follows:
Order the parameters
Considering the following error program that produces an error message Non-default argument follows default argument
since Python does not allow you to put a value with a default
value before a value that doesn't have one.
To overcome this issue, you can re-order them, and have the value without a default value (the query parameter q
) first. But it doesn't matter for FastAPI. It will detect the parameters by their names, types and default declarations (Query
, Path
, etc), since it doesn't care about the order.
Number validations with Annotated
Annotated
Let's take a look in the below program:
Program explanation:
item_id
: This is a path parameter. It's expected to be an integer (int
) between 1 and 1000 (inclusive). ThePath
function provides extra information and validation for this parameter.q
: This is a query parameter. It's expected to be a string (str
) orNone
. TheQuery
function provides an alias for this parameter, so in the URL it will beitem-query
instead ofq
.
The explanation is generated by KamiMind.ai
You can declare numeric validations by using following syntaxes:
gt
:g
reatert
hange
:g
reater than ore
quallt
:l
esst
hanle
:l
ess than ore
qual
Let's take a look at another example:
You should note that:
Number validations also work for
float
values.gt
is more strictly thange
. So,0.5
would be a valid value, but0.0
or0
would not.
Summary
Using Annotated
with FastAPI allows for sophisticated validation and metadata enhancements directly in the function signatures of your API endpoints. This can significantly improve the robustness, readability, and documentation of your API by leveraging Python's type hints and FastAPI's powerful validation capabilities.
Last updated