英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论