2

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?

Chris
  • 18,724
  • 6
  • 46
  • 80
Jack Gee
  • 136
  • 6

1 Answers1

2

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.

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91