new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

FastAPI · Tutorial · all subjects

path-parameters

26 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Path parameter declaration syntax

Path parameters are declared using curly braces in the path string, with the same syntax as Python format strings. For example, a path like /items/{item_id} declares a path parameter named item_id.

Path parameter passed as function argument

The value of a path parameter is automatically passed to the function as an argument with the same name as the parameter declared in the path.

Type annotation enables parsing and validation

By declaring a type annotation for a path parameter (such as int, str, float, or bool), FastAPI automatically parses the path parameter value to that type and validates it. If validation fails, FastAPI returns a JSON error response.

Type parsing example - int to string conversion

When a path parameter is typed as int, FastAPI automatically converts the URL string to an integer. For example, /items/3 returns {"item_id": 3} as an integer, not the string "3".

Validation error response format

When a path parameter fails validation, FastAPI returns a JSON error response with detail array containing objects with type (e.g. "int_parsing"), loc array indicating the location ["path", "parameter_name"], msg describing the validation failure, and input showing the value that failed.

Automatic documentation at /docs endpoint

FastAPI generates automatic interactive API documentation using Swagger UI at the /docs endpoint. The documentation reflects declared path parameter types and constraints based on the OpenAPI schema.

Alternative documentation at /redoc endpoint

FastAPI provides alternative API documentation using ReDoc, accessible at the /redoc endpoint. Both documentation UIs are generated from the OpenAPI standard schema.

Path operations order matters

Path operations are evaluated in order. When multiple paths could match a request, the first matching path operation is used. Fixed paths like /users/me must be declared before parameterized paths like /users/{user_id} to prevent incorrect parameter matching.

Cannot redefine path operation

Once a path operation is defined, it cannot be redefined with the same path and method. The first definition will always be used since the path matches first.

Predefined path parameter values using Enum

To restrict a path parameter to predefined valid values, create a Python Enum class that inherits from both str and Enum. Each class attribute represents a valid value. Use this Enum class as the type annotation for the path parameter.

Enum parameter receives enumeration member

When a path parameter is typed as an Enum, the function receives an enumeration member object. You can compare it with the enum class members or access the actual string value using the .value attribute (e.g. model_name.value).

Enum members returned in JSON response

When you return an enumeration member from a path operation (including nested in JSON), FastAPI automatically converts it to its corresponding string value in the response before sending to the client.

Path parameter containing paths with :path converter

To allow a path parameter to contain slash characters and match multiple path segments, use the :path converter syntax in the URL pattern, such as /files/{file_path:path}. This uses Starlette's internal path convertor.

Path parameter with leading slash requires double slash

When using :path converter, if the parameter value needs a leading slash (e.g. /home/johndoe/myfile.txt), the URL must use a double slash between the fixed part and the parameter (e.g. /files//home/johndoe/myfile.txt).

OpenAPI limitation for path parameters containing paths

OpenAPI does not support declaring a path parameter to contain paths inside it, as this could lead to scenarios that are difficult to test and define. FastAPI can still implement this using Starlette's internal tools, but the automatic documentation will not include documentation for this constraint.

Pydantic performs all data validation

All path parameter data validation in FastAPI is performed under the hood by Pydantic, providing comprehensive validation capabilities.

FastAPI benefits from type declarations

Using Python type declarations for path parameters provides: editor support with error checks and autocompletion, automatic data parsing from URL strings to Python types, data validation with clear error messages, and automatic API documentation.

Query parameters definition

Function parameters that are not part of the path parameters are automatically interpreted as query parameters. Query parameters are the set of key-value pairs that go after the `?` in a URL, separated by `&` characters.

Query parameters type conversion

Query parameters declared with Python types are automatically converted to that type and validated against it. FastAPI performs parsing (converting strings from HTTP requests into Python data), data validation, and provides editor support automatically for query parameters.

Optional query parameters with None default

You can declare optional query parameters by setting their default value to `None`. In this case, the function parameter will be optional and will be `None` by default.

Query parameter boolean type conversion

FastAPI supports `bool` type for query parameters. The following values are converted to `True`: 1, True, true, on, yes, and any other case variation (uppercase, first letter in uppercase, etc). Any other value is converted to `False`.

Required query parameters

To make a query parameter required, declare it without providing a default value. When a required query parameter is missing from the URL, FastAPI returns an error with type "missing" and message "Field required".

Query parameter default values

Query parameters can have default values. Since query parameters are not a fixed part of a path, they are optional by default and can have default values. If a query parameter is not provided in the URL, the default value is used.

FastAPI distinguishes path and query parameters automatically

FastAPI automatically detects whether a function parameter is a path parameter or query parameter based on name matching. Path parameters are matched to the path template, while other parameters are treated as query parameters. Parameters do not need to be declared in any specific order.

Multiple path and query parameters together

You can declare multiple path parameters and query parameters at the same time. FastAPI knows which is which based on name matching. You do not have to declare them in any specific order.

Python types supported in query parameters

FastAPI supports automatic parameter validation for query parameters using Python types including: `int`, `float`, `str`, `bool`, and other types. Parameters declared with Python types are automatically converted from URL strings and validated.

Give your agent this brain