top of page

Exploring Request Parameters in FastAPI - FastAPI Tutorial


Introduction:

In the previous blog post of FastAPI series, we built a simple Student Information System using FastAPI. Now, In this blog we will the discuss various types of request parameters it supports. Understanding how to handle parameters be it in the path, query, or request body is crucial for building robust and dynamic APIs. Also, we'll demonstrate the different types of request parameters in FastAPI and illustrate how to handle them effectively. We'll leverage our example from the previous project, making it clear and easy to understand.


If you haven't already read our previous blog of Fas, here is the link Click Here. You can access it by clicking on the provided link. Additionally, you'll find the complete code of the previous project there as well.


Types of Request Parameters in FastAPI:


1. Path Parameters:

Path parameters are included in the URL path and are used to capture values from the URL itself. They are enclosed in curly braces {} in the route definition.




# Importing necessary modules
from fastapi import FastAPI, HTTPException

# ... (Previous code)

# Route with path parameter
@app.get("/students/{id}")
def get_student_by_id(id: int):
    if id < 0 or id >= len(db):
        raise HTTPException(status_code=404, detail="Student not found")
    return db[id]

In the above code, we introduced a new route /students/{id} that takes an id as a path parameter. FastAPI automatically converts the path parameter to the specified type (int in this case), allowing us to retrieve a specific student by their ID


Output :


2. Query Parameters:

Query parameters are included in the URL after the ? symbol. They are used for optional parameters and can be added to the route function with default values.



# Route with query parameters
@app.get("/students/")
def get_students(skip: int = 0, limit: int = 10):
    return db[skip : skip + limit]

In the above code, we added a route /students/ that takes optional query parameters skip and limit. These parameters allow us to skip a certain number of students and limit the number of students returned in the response.


Explore the API and Execute the Endpoint:

  • In the documentation, find the endpoint corresponding to the route with query parameters. In this case, it should be /students/ with the method GET.

  • Click on the endpoint to expand it and reveal the input parameters.

  • You will see the skip and limit parameters as optional query parameters.


Execute the Endpoint:

  • To see the output, you can enter values for the skip and limit parameters in the provided input fields.

  • Click on the "Execute" button to send a request to the endpoint with the specified parameters.


View the Response:

  • After executing the endpoint, scroll down to the "Response" section to view the output.

  • The response will include the list of students based on the provided skip and limit parameters.

For example, if you set skip to 1 and limit to 2, the response may look like this:



3. Request Body Parameters:

Request body parameters are used to send data in the request body, typically for POST or PUT requests. They can be of various types, including JSON, form data, or other content types.




# ... (Previous code)

# Request body model for adding a student
class NewStudent(BaseModel):
    name: str
    age: int
    grade: str

# Route with request body parameter
@app.post("/students/")
def add_student(new_student: NewStudent):
    student = Student(name=new_student.name, age=new_student.age, 	grade=new_student.grade)
    db.append(student)
    return {"message": "Student added successfully"}


In the above code, we introduced a new Pydantic model NewStudent to represent the data structure expected when adding a new student. The route /students/ now takes a request body parameter new_student of type NewStudent. FastAPI automatically validates and parses the incoming JSON data into the specified model.


Explore the API and Execute the Endpoint:

  • In the documentation, find the endpoint corresponding to the route with the request body parameter. In this case, it should be /students/ with the method POST.

  • Click on the endpoint to expand it and reveal the input parameters.

  • You will see the new_student parameter, which is a request body parameter of type NewStudent.


Execute the Endpoint:

  • To see the output, scroll down to the "Request Body" section and provide values for the name, age, and grade parameters.

  • Click on the "Execute" button to send a request to the endpoint with the specified request body.


View the Response:

  • After executing the endpoint, scroll down to the "Response" section to view the output.

  • The response will include a message indicating the success of the operation. For example:



4. Form Parameters:

Form parameters are used for handling form data from requests, typically in POST requests. FastAPI simplifies this with the Form class:




from fastapi import FastAPI, Form

app = FastAPI()

@app.post("/login/")
def login(username: str = Form(...), password: str = Form(...)):
    return {"username": username, "password": password}


In the above example, the login route handles form data with username and password parameters, both annotated with the Form class.


Explore the API and Execute the Endpoint:

  • In the documentation, find the endpoint corresponding to the route with form parameters. In this case, it should be /login/ with the method POST.

  • Click on the endpoint to expand it and reveal the input parameters.

  • You will see the username and password parameters as form parameters.


Execute the Endpoint:

  • To see the output, you can enter values for the username and password parameters in the provided input fields.

  • Click on the "Execute" button to send a request to the endpoint with the specified parameters.


View the Response:

  • After executing the endpoint, scroll down to the "Response" section to view the output.

  • The response will include the username and password values provided in the form parameters.


For example, if you set codersarts to "john_doe" and password to "codersarts@123" the response may look like this:



Now that we have explored the various types of request parameters supported by FastAPI and demonstrated how to handle them effectively, you've gained valuable insight into building robust and dynamic APIs. By understanding path parameters, query parameters, request body parameters, and form parameters, you have the necessary tools to create versatile and user-friendly endpoints.


With the implementation of these features into our Student Information System, you've taken a significant step forward in master FastAPI. This foundational knowledge provides a solid base from which you can expand and customize your API to meet more complex requirements. Whether you're building a small-scale application or a large-scale system, FastAPI empowers you to develop efficient and scalable APIs with ease.



If you require assistance with the implementation of Fast API, or if you need help with related projects, please don't hesitate to reach out to us.

Comentários


bottom of page