Open In App

POST Query Parameters in FastAPI

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

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 concepts behind this process and provide practical examples to illustrate how it’s done.

Query Parameters in FastAPI

Below are the key concepts related to this:

  • POST Requests: Post requests are mainly used for sending data to the server. Before delving into consuming query parameters, it’s essential to grasp the basics of POST requests. In FastAPI, POST requests are commonly used for submitting data to the server.
  • Query Parameters in POST Requests: In traditional GET requests query parameters are part of the URL, but in a POST request, query parameters are typically sent in the request body. FastAPI simplifies this process, allowing developers to access these parameters effortlessly. In FastAPI, there is a request object in every endpoint that has info about all query parameters sent by the user, so we can use that request object and extract info from that object.
  • FastAPI’s Request Object: In FastAPI there is a Request object that encapsulates the incoming HTTP request. This object includes all the necessary information about the request, making it easy to extract query parameters. we can extract all info from this request object and use them in our application as needed.

Consume Query Parameters from POST in FastAPI

In this example, we created a FastAPI app, and defined “/submit_data” as an API endpoint that accepts a POST request from a user and simply returns the username and age parameter of this POST request to the user as a response.

app.py: Here we can note that we had accessed the POST request parameter named “username” and “age“. In the below code, we can see that in FastAPI there is a request object which contains info about the POST request, we can acceess that object and get required from POST request. Below is the code example which done what we mentioned above with proper comments to understand.

Python3




from fastapi import FastAPI, HTTPException, Request
 
# creating fatsAPI app
app = FastAPI()
 
"""
    Endpoint to submit user data using a POST request in FastAPI.
 
    Parameters:
    - request: FastAPI Request object containing information
                about the HTTP request.
 
    Returns:
    A simple confirmation message with the submitted user data.
"""
 
 
@app.post("/submit_data")
async def submit_data(request: Request):
    try:
        # Extracting user data from the request body
        data = await request.json()
 
        # Validate the presence of required fields
        if "username" not in data or "age" not in data:
            raise HTTPException(
                status_code=422, detail="Incomplete data provided")
 
        # Extracting username and age from the request JSON body
        username = data["username"]
        age = data["age"]
 
        # Returning a confirmation message
        return {"message": "User data submitted successfully!",
                "user_data": {"username": username, "age": age}}
 
    except HTTPException as e:
        # Re-raise HTTPException to return the specified
        # status code and detail
        raise e
    except Exception as e:
        # Handle other unexpected exceptions and return a
        # 500 Internal Server Error
        raise HTTPException(
            status_code=500, detail=f"An error occurred: {str(e)}")
 
if __name__ == "__main__":
    import uvicorn
    # Run the FastAPI application using uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)


Run the Code

We can run this code as we run simple python file. server will start on the “http://127.0.0.1:8000” (localhost). we can test this code by sending Post request to the endpoint “/submit_data“. Here, we had used a Postman to test API endpoints.

Output

Case 1: Sending both username and age as parameter in POST request

Here we can se that username and age passed in request body, we got proper response from server with message “User data submitted successfully!“.
Screenshot-2023-11-18-124115

Case 2: Any one info missing (either username or age)

Here in this case we don’t send some info(either username or age) so as mentiond in our code’s try block if both field are not there we simply raise a error “Incomplete data provided”.

Screenshot-2023-11-18-124356

So this is how we can consume a query parameter from a POST request in fastAPI. we can simply convert the request object into JSON format and then we can use it, as required.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads