Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

python - post reguest '422 Unprocessable Entity' with fast api

I have a fast api application, where I want to have a post request.

from pydantic import BaseModel
from fastapi import FastAPI


class Data(BaseModel):
    num: str

app = FastAPI()

@app.post("/set/")
def set_param(data: Data):
    return data

When I send request from another file:

import requests,json

req = requests.post('http://0.0.0.0:5000/set/',data={'num':'1'}).json()

I have an error:

INFO:     127.0.0.1:54236 - "POST /set/ HTTP/1.1" 422 Unprocessable Entity

I don;t know what should I change to eliminate this error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are not sending a valid JSON.

You should use json instead of data.

json={"num":"1"}

Use it like this

req = requests.post('http://0.0.0.0:5000/set/',json={'num':'1'}).json()

Or you can use json.dumps()

req = requests.post('http://0.0.0.0:5000/set/', json.dumps(data={'num':'1'})).json()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...