Open In App

FastAPI – Path Parameters

Last Updated : 11 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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-

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

inteter

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

floar-

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

custom

Custom

Example

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

first

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads