FastAPI - Path Parameters
Last Updated :
11 Dec, 2023
In this exploration, we'll dive into the realm of FastAPI Path Parameters, unraveling their pivotal role in constructing dynamic and versatile APIs. FastAPI stands out as a contemporary web framework celebrated for its speed, tailor-made for crafting APIs in Python 3.7 and beyond. Leveraging standard Python-type hints, FastAPI simplifies the comprehension of a web service's functionality for developers, automating the generation of comprehensive documentation.
What are Path Parameters in FastAPI?
Unlike traditional file-based URLs, modern web frameworks integrate routes or endpoints directly into the URL structure, enhancing user recall of application URLs. In FastAPI, this integral part of the URL is denoted as the path, appearing after the initial "/". Path parameters in FastAPI empower developers to extract variable values from the URL's path, introducing dynamicity to routes and enhancing API adaptability. This functionality proves invaluable in several scenarios:
- Dynamic Routing: FastAPI's path parameters enable the creation of a singular route capable of accommodating a spectrum of inputs. This significantly reduces the necessity for defining numerous identical routes, ultimately amplifying the flexibility of your API.
- Data Retrieval: Frequently utilized for obtaining specific resources or data, path parameters prove instrumental by leveraging unique IDs provided within the URL. This dynamic approach streamlines the retrieval process and enhances the overall efficiency of the API.
- Clean and Readable URLs: Path parameters contribute to the formation of intuitive, human-readable URLs. This not only facilitates user understanding but also aids developers in comprehending the purpose of a particular route. The resulting URLs are clear and concise and enhance both consumer and developer experiences.
In essence, by harnessing the capabilities of FastAPI Path Parameters, developers can architect APIs that are not only dynamic and adaptable but also boast clean and user-friendly URL structures. This not only enhances the functionality of the API but also contributes to improved maintainability and user satisfaction.
Types of Path Parameters in FastAPI
To ensure the accuracy of provided values and enforce expected data types in FastAPI, path parameters with specific types can be employed. This practice facilitates validation, guarding against potential issues arising from the use of incorrect parameter types. Here's an illustrative example of utilizing path parameters with types in FastAPI:
String Path Parameter
In this example, the path parameter item_id
is of type str
Python3
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str):
return {"item_id": item_id}
Run the below command
uvicorn main:app --reload
Output
String Integer Path Parameter
In this case, the path parameter item_id
is of type int
Python3
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
Run the below command
uvicorn main:app --reload
Output
Output Float Path Parameter
The path parameter item_price
is of type float
Python3
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_price}")
async def read_item(item_price: float):
return {"item_price": item_price}
Output
Output Custom Data Type Path Parameter
In this example , a custom data type (Path
) is used for the path parameter item_name
, with additional metadata like a title
Python3
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_name}")
async def read_item(item_name: str = Path(..., title="The name of the item")):
return {"item_name": item_name}
Run the below command :
uvicorn main:app --reload
Output
CustomExample
This Python code uses FastAPI to create a basic web API with two asynchronous endpoints. The first endpoint ("/") responds to a GET request with a JSON message "Hello World." The second endpoint ("/gfg/{name}") responds to a GET request with a JSON message containing the provided name parameter. FastAPI handles routing and generates API documentation based on function signatures. The code runs the web application using the ASGI server, Uvicorn.
Python3
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def index():
return {"message": "Hello World"}
@app.get("/gfg/{name}")
async def gfg(name):
return {"name": name}
Now, run the UVICORN server in terminal using below command
uvicorn main:app --reload
Output

Conclusion
In conclusion, FastAPI's robust support for path parameters provides a powerful mechanism for handling dynamic data in API routes. Path parameters, coupled with type annotations, not only enhance code clarity but also contribute to effective data validation and error prevention. The framework's automatic documentation generation based on parameter types further aids developers in creating well-documented APIs. Whether dealing with strings, integers, floats, or custom data types, FastAPI's flexibility in handling path parameters facilitates the development of reliable and efficient web APIs. As a result, leveraging FastAPI's path parameters proves instrumental in building scalable and maintainable applications.
Similar Reads
FastAPI - Query Parameters
In this article, we will learn about FastAPI Query Parameters, what are query parameters, what they do in FastAPI, and how to use them. Additionally, we will see examples of query parameters for best practices. What is FastAPI - Query Parameters?Query parameters stand as a formidable asset in bolste
6 min read
POST Query Parameters in FastAPI
FastAPI is a powerful and efficient Python web framework for building APIs with ease. For most of the applications getting data from a user is done through a POST request and this is a common task for developers is consume query parameters from POST requests. In this article, we'll explore the conce
4 min read
FastAPI - Header Parameters
FastAPI is the fastest-growing Python API development framework, It is easy to lightweight, and user-friendly and It is based on standard Python-type hints, which makes it easier to use and understand. FastAPI supports header parameters, these are used to validate and process incoming API calls. In
4 min read
Send Parameters to POST Request FastAPI
In the world of web development and API creation, sending parameters via a POST request is a fundamental operation. FastAPI, a modern Python web framework, simplifies this process and allows developers to build efficient and scalable APIs. In this article, we will explore the theory and practical as
3 min read
How to Handle Route Parameters in Angular?
In Angular, routing plays an important role in building single-page applications (SPAs). Often, you need to pass data between components through the URL using route parameters. Route parameters allow you to define dynamic segments in your routes, which can be extracted and used in your components. T
3 min read
Python | os.DirEntry.path attribute
Path attribute of os.DirEntry object is used to get the entryâs full path name. The full path is absolute only if the path parameter used in the method is absolute. Also if the method path parameter was a file descriptor then the value of os.DirEntry.path the attribute is the same as os.DirEntry.nam
3 min read
Node.js fs.realpath() Method
The fs.realPath() method is used to compute the canonical pathname of the given path. It does so by resolving the ., .. and the symbolic links in the path. Syntax: fs.realpath( path, options, callback ) Parameters: This method accept three parameters as mentioned above and described below: path: It
3 min read
Python | os.path.getatime() method
OS module in Python provides functions for interacting with the operating system. OS comes under Pythonâs standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name man
2 min read
How to pass parameters in Postman requests?
Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. It can make various types of HTTP requests(GET, POST, PUT, PATCH), save environments for later use, and convert the API to code for various languages(like JavaScript, and Python). In this
2 min read
Python | os.path.isabs() method
OS module in Python provides functions for interacting with the operating system. OS comes under Pythonâs standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name man
2 min read