Open In App

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 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:



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.






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!“.

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”.

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.


Article Tags :