-1

I'm just having a go at using fastapi for hobbyiest purposes. I am getting the 422 unprocessable entity error with my post request

I've created a pydantic model for my products

class post_products(BaseModel):
    id: int
    description: str
    price: int

Then have a post endpoint created

@app.post('/send/data', status_code=201)
async def process_data(product: post_products):
    products_list.append(product)
    if(product in products_list):
        return True

which i believe functions like, it takes in a post_products instance adds it to the products_list and then returns true if the add was successful, I then call this endPoint with

product = post_products(id=12,description='hello', price=93) creates and instance of the class
product = product.model_dump() makes this instance into a dictionary

response = requests.post("http://127.0.0.1:8000/send/data", data= product)

Sorry Gordon i've updated it with the result. The product is a dict and its this

{'id': 12, 'description': 'hello', 'price': 93}
Darman
  • 175
  • 10

1 Answers1

0

You're sending your request using form data, while your post endpoint accepts json. Changing to

response = requests.post("http://127.0.0.1:8000/send/data", json=product)

should do the trick.

M.O.
  • 1,712
  • 1
  • 6
  • 18
  • That managed to do the trick, can i just ask where i went wrong like as in how were you able to spot that mistake so easily – Darman Aug 10 '23 at 17:13
  • Form data is a format used when submitting HTML `
    `s (which can also be [used in FastAPI](https://fastapi.tiangolo.com/tutorial/request-forms/#__tabbed_2_1)), while in most other cases, APIs will use a JSON format, which is what FastAPI defaults to. Here is [another question comparing the two](https://stackoverflow.com/questions/23118249/whats-the-difference-between-request-payload-vs-form-data-as-seen-in-chrome).
    – M.O. Aug 10 '23 at 19:00
  • As for how I could spot it so quickly, I've made the same mistake many times, so that's one of the things I always look for when seeing FastAPI return 422 errors. – M.O. Aug 10 '23 at 19:01
  • 1
    @Darman The body of the 422 error message will also tell you _what_ fields was expected that were missing. – MatsLindh Aug 10 '23 at 20:43
  • @MatsLindh Thank you guys so much, its really an uphill battle with coding. I've had a look at what youo both suggested and now i feel comfortable with this error going forward – Darman Aug 11 '23 at 11:52
  • @M.O. Thank you also, it wasn't letting me at two users at the same time – Darman Aug 11 '23 at 11:52