无法处理的实体,使用 fastapi 发送 POST 请求?

huangapple go评论124阅读模式
英文:

Unprocessable entity with fastapi post request?

问题

我只会为你提供代码的翻译部分,以下是代码的翻译:

我只是尝试在业余时间使用fastapi我在我的POST请求中遇到了422无法处理的实体错误

我为我的产品创建了一个pydantic模型

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

然后创建了一个POST端点

@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

我相信这个函数的功能是它接受一个post_products实例将其添加到products_list中然后如果添加成功则返回True然后我使用以下代码调用这个端点

product = post_products(id=12, description='hello', price=93)  # 创建一个类的实例
product = product.model_dump()  # 将这个实例转换为字典

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

请注意,代码中的注释和变量名没有翻译,保持原样。

英文:

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}

答案1

得分: 0

你正在使用表单数据发送请求,而您的POST端点接受JSON。更改为

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

应该解决问题。

英文:

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.

huangapple
  • 本文由 发表于 2023年8月11日 00:08:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76877536.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定