FastAPIpath-query-parameters detailed explanation
📂 Daoman PythonAI · FastAPI foundation building column | Stage 1 🔗 Pre-chapters: fastapi-intro-advantages · environment-setup · 前置Pydantic入门
If you are developing a mini e-commerce API, users may access addresses like this:
/categories/electronics/items/123?q=iPhone&min_price=1999
At the same time, the administrator will also send a piece of JSON via POST to update the product data.
How does FastAPI automatically capture these parameters in milliseconds, convert types accurately, and reject data immediately when it is unqualified? This article focuses on path parameters, query parameters, and request body parameters. In conjunction with the latest Pydantic V2, it explains the core knowledge of FastAPI parameter processing in one go.
Table of contents
Three core parameter types
One of the biggest charms of FastAPI is: as long as you use Python type annotation to write the parameter type clearly, FastAPI will automatically complete the following three things for you:
- Know where this parameter is in the request (path, query, request body...)
- Convert the string into the corresponding Python type (such as
int、float、bool) - Generate beautiful automatic documentation (visit
/docscan be seen)
Let’s break it down one by one.
Path parameters
Path parameters are dynamic parts embedded in the URL path, usually used to locate a unique resource. for example/items/123inside123It's the product ID.
Basic usage + automatic type conversion
- Visit
/items/123→item_idWhat you get is an integer123 - Visit
/items/abc→ FastAPI will directly return 422 error because it cannot be converted to int
This saves you the need to manuallyint()And the process of catching exceptions is clean and safe.
Use enumerations to limit optional values
When path parameters can only be chosen from a few fixed values, use Python'sEnummatchstrTypes can both constrain values and present clear options in documents.
access/categories/electronics/items/correct,/categories/cars/items/An error will be reported directly.
Special path: match content with slashes
Sometimes you need to have a path parameter contain/, such as file path/files/home/user/report.pdf, then you can use{param:path}model:
This whole/home/user/report.pdfwill be regarded asfile_pathvalue.
Query parameters
Query parameters are in the URL?The bunch of key-value pairs at the back are usually used for filtering, sorting, and paging, and will not change the location of the resource.
The default value determines whether it is optional
Among the function parameters, FastAPI will automatically recognize any parameters that are not placed in path curly braces as query parameters. Parameters with default values are optional, and parameters without default values are required.
- Visit
/items/?q=phone&skip=20&limit=5→ All three parameters are available - Visit
/items/→qforNone,skipfor0,limitfor10, the request was successful
Tip: Starting from FastAPI 0.95, it is recommended to use
AnnotatedExplicitly declare required or optional for better readability.
Advanced scenario: list parameters and aliases
Query parameters often need to pass multiple values, or the parameter name is different from the Python variable name, then you can findAnnotated + Queryconvenience.
tagsMultiple identical parameter values received will be automatically packed into a list.aliasThis solves the problem of inconsistency between "external naming" and "internal naming".
Request body parameters
When the amount of data is large and the structure is complex, JSON is usually sent through the request body of POST and PUT requests. FastAPI requires using Pydantic V2's BaseModel to define the structure of the request body, so that parsing, verification, and type conversion can be automatically completed.
Basic model definition
Once the request body does not meet the model requirements, FastAPI will immediately return a 422 error with a detailed verification failure reason.
Nested models: dealing with complex structures
Real business data is often layered within one layer, and you can directly reference one model to another.
This is like building blocks. You can add as many layers as you want, and FastAPI can automatically verify it.
Full-link parameter verification: Decorator + model two-pronged approach
FastAPI's verification system is 100% built on Pydantic V2.
Paths and query parameters can be usedPath、QueryWait for the decorator to set the rules; the request body parameters are completely constrained by the Pydantic model. The two writing methods are very similar to each other.
Parameter level verification: Path/Query/Body
RecommendedAnnotated+ The corresponding decorator writes all the rules in one line, which is clear and conducive to generating API documentation.
ge、le、gt、ltThese parameters are the same as Pydantic’sFieldThe usage is consistent, and once you learn one, you can draw inferences about other cases.
Model-level verification: Pydantic V2
When you need to perform complex validation on a model and combine multiple field judgments, you should write it in the Pydantic model. Pydantic V2 provides three levels of custom validation:
1. Global configuration + field rules
passmodel_configSet the behavior of the entire model and then useFieldPrecisely describe the constraints for each field.
2. Single field custom verification:@field_validator
When additional logical judgment needs to be made on a certain field, such as checking whether the category name is in the whitelist:
Note that the validator for V2 must be a class method and use@classmethoddecorate.
3. Multi-field joint verification:@model_validator
Some rules need to rely on multiple fields at the same time to determine, such as "Tax cannot exceed 30% of the price":
Through the combination of these three methods, almost all verification requirements on the business side can be covered.
Mixing parameters and basic dependencies: combination boxing
A real interface usually has path parameters, query parameters, request body parameters, and even calls to common logic (such as query string preprocessing) in one path. FastAPI's Dependency Injection (Depends) function can make these mashup scenarios organized.
Complete example of multi-parameter mashup
FastAPI can automatically distinguish which parameter comes from the path, which comes from the query, and which comes from the request body, without you having to write it manually at all.request.query_params.get()code like that.
Use dependency preprocessing to search for keywords
Extract reusable logic (such as string cleaning) into dependent functions so that multiple routes can share them.
In this way, any route that requires the same preprocessing logic can just addDepends(preprocess_query)That’s it, to avoid reinventing the wheel.
Error handling and debugging: novice friendly
FastAPI provides developers with very thoughtful error handling and debugging tools, which is one of the reasons why it is so popular.
1. Automatic 422 error feedback
When the parameter type is incorrect or verification fails, FastAPI will return422 Unprocessable Entity, and clearly stated in the response body:
- Which request parameter is the problem?
- Specific reasons for failure
- What value did you actually pass in?
You can do this in Swagger UI (/docs) or Redoc(/redoc), you can see these error messages directly, and the debugging efficiency is extremely high.
2. Manually throw business exceptions
For business logic errors, such as resource not found, useHTTPExceptionManually return the appropriate HTTP status code.
3. Turn on debugging mode with one click
- Visit
http://127.0.0.1:8000/docs(Swagger UI) or/redoc(Redoc), you can directly call the interface online and view parameter descriptions. - Add when starting the service
--reload --debug, enable code hot reloading and detailed error pages, a must during the development stage.
Related tutorials
Summary: Ending of small e-commerce example
Going back to the e-commerce API scenario at the beginning, we used the knowledge we learned today to assemble it into a complete small example. This example also includes path parameters, query parameters, request body, dependency preprocessing, and Pydantic V2’s validation functionality.
As long as you master the three core concepts of path parameters, query parameters, and request body parameters, plus the verification routine of Pydantic V2, you can already develop most RESTful APIs. The subsequent cookie processing, header extraction, file upload and other knowledge are essentially extended functions grown from this basis.
Adhere to the idea of "type hints + model verification", and your road to FastAPI will become smoother and smoother!

