#fastapi
Вопрос:
Я пытаюсь отправить некоторые данные в метод API с помощью браузера. Когда я использую fastAPI's
Request
объект, все работает. Но когда я использую педантичную модель, я получаю:
422 (Unprocessable Entity)
Я протестировал свой код, curl
и снова все работает.
Вот мой фастАПИ:
from typing import Optional
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = 'N/A'
@app.post("/test_request")
async def create_item(request:Request):
json = request.json()
return await json
@app.post("/test_pydantic")
async def create_item(item:Item):
return item
if __name__ == '__main__':
uvicorn.run(app='main:app', reload=True, debug=True)
И вот мой index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>test</h1>
<script>
const person = {
name: 'XXX',
description: 'XXX Desc',
price:200,
tax: 400123598
}
fetch('http://127.0.0.1:8000/test_request', {
method: 'POST',
body: JSON.stringify(person),
contentType: "application/json",
dataType: 'json',
}).then(function(respones) {
return respones.json();
}).then(function(data) {
console.log('Using request', data);
})
fetch('http://127.0.0.1:8000/test_pydantic', {
method: 'POST',
body: JSON.stringify(person),
contentType: "application/json",
dataType: 'json',
}).then(function(respones) {
return respones.json();
}).then(function(data) {
console.log('Using pydantic', data);
})
</script>
</body>
</html>
При звонке test_pydantic
из браузера я получаю 422
сообщение .
Комментарии:
1. Ошибка 422 будет содержать текст с фактическим сообщением об ошибке, т. Е. Какое поле не проходит проверку.
2. ОК. Ошибка в том, что
value is not a valid dict
Ответ №1:
Вы неправильно устанавливаете значение content-type
при вызове fetch
с данными JSON. content-type
Заголовок находится под headers
ключом:
fetch('http://127.0.0.1:8000/test_pydantic', {
method: 'POST',
body: JSON.stringify(person),
headers: {"content-type": "application/json"},
dataType: 'json',
}).then(function(respones) {
return respones.json();
}).then(function(data) {
console.log('Using pydantic', data);
})