Send Data via Body of HTTP Request
We are using Postman to create the HTTP Request with Body data
Go to the Body of the POST request

Go to RAW under the Body section and usually you want to select JSON

How it would look:

{
"title": "top gun",
"content": "check out my top gun"
}
Now that we have our HTTP packet set up, we can move on to the FastAPI code
You will have to import the Body parameter from
fastapi.params
from fastapi.params import Body
Once this is imported you are able to set up the function so that it converts the JSON sent via HTTP request to a python dictionary and stores it into the
payload
variable
def create_posts(payload: dict = Body(...)):
Then you can return the variable
def create_posts(payload: dict = Body(...)):
return payload
Full Code:
from fastapi.params import Body
@app.post("/createpost")
def create_posts(payload: dict = Body(...)):
return payload
Alternatively you can print this to the screen:
@app.post("/createpost")
def create_posts(payload: dict = Body(...)):
print(payload)
return {"message": "successfully created post"}
Once you run this via uvicorn and send the packet via postman you should get the dictionary printed in the terminal:
Note on line 8 that the dictionary got printed
INFO: Shutting down
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
INFO: Finished server process [29399]
INFO: Started server process [29594]
INFO: Waiting for application startup.
INFO: Application startup complete.
{'title': 'top gun', 'content': 'check out my top gun'}
INFO: 127.0.0.1:37532 -"POST /createpost HTTP/1.1" 200 OK
Even better you could return the results via an f string referencing the dictionary key
@app.post("/createpost")
def create_posts(payload: dict = Body(...)):
print(payload)
return {"new_post": f"title: {payload['title']} content: {payload['content']}"}
Note that the
payload
dictionary can be referenced normally by key
Postman Results:

Last updated