FastAPI and Python requests 422 error problem

Question:

I am trying to use FastAPI for a new application that looks at events in the town I live in.

Here’s my FastAPI backend:

from fastapi import FastAPI
from utils import FireBaseConnection
from pydantic import BaseModel

app = FastAPI()

class Data(BaseModel):
    name: str

@app.post("/event")
async def create_events(event: Data):
    return event

and here’s how I use Python requests to test the API:

import requests
import json

mode = "DEV"
dev_server = "http://127.0.0.1:8000"

with open("data/data.json", "r") as f:
    events = json.load(f)

for event in events: 
    if mode == "DEV":
        requests.post(dev_server + "/event", 
                     headers={"ContentType": "application/json"}, 
                     data={"name": event["name"].encode("utf-8")})

I keep getting 422 Unprocessable Entity errors. Anyone know any fixes?

Asked By: Jack Gee

||

Answers:

The error seems in how do you send the Json data to the server. requests.get() has an json= parameter, so you don’t have to set HTTP headers and encode the payload manually.

Simply call

requests.post(dev_server + "/event", json={'name': event["name"]})

and requests will handle the details for you.

Answered By: Andrej Kesely
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.