Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
FastAPI - Path Parameters
Next article icon

FastAPI - Path Parameters

Last Updated : 11 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
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.


Next Article
FastAPI - Path Parameters

A

anishvv212002
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • FastAPI
  • Geeks Premier League 2023
Practice Tags :
  • python

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 - OpenAPI
    FastAPI is a modern, fast, and web framework for creating APIs with Python. It is built on top of the popular web framework Starlette and includes built-in support for OpenAPI. In this article, we'll learn about OpenAPI and FastAPI and how to use them to create robust, widely documented APIs. What i
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences