개발하자
FastAPI 서버가 "422 unprocessable entity"를 반환함 - value_error.missing
Cuire
2023. 3. 6. 02:52
반응형
FastAPI 서버가 "422 unprocessable entity"를 반환함 - value_error.missing
from http.client import responses
from random import randrange
from tkinter.tix import STATUS
from typing import Optional
from urllib import response
from fastapi import Body, FastAPI, Response ,status, HTTPException
from pydantic import BaseModel
app= FastAPI()
class Post(BaseModel):
title: str
content: str
Published: bool = True
rating: Optional[int] = None
my_post = [{"title": "title of post 1", "content": "content of post 1", "id": 2},{"title": "title of post 2","content":"content of post 2", "id":3}]
def find_post(id):
for p in my_post:
if p["id"] == id:
return p
def find_index_post(id):
for i,p in enumerate(my_post):
if p["id"]== id:
return i
@app.get("/posts/{id}")
def get_posts(id: int , response: Response):
post= find_post(id)
if not post :
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail= f"post with id {id} not found bludd")
# response.status_code=status.HTTP_404_NOT_FOUND
# return {"message": f" post with id : {id} not found"}
return{"here is the post": post}
@app.delete("/posts/{id}", status_code= status.HTTP_204_NO_CONTENT)
def delete_post(id: int):
index= find_index_post(id)
if index == None:
raise HTTPException(status_code= status.HTTP_404_NOT_FOUND, detail= f"post with id {id} does not exist")
my_post.pop(index)
return Response(status_code= status.HTTP_204_NO_CONTENT)
@app.put("/posts/{id}")
def update_post(id: int , post: Post):
index = find_index_post(id)
if index == None :
raise HTTPException(status_code= status.HTTP_404_NOT_FOUND, detail= f"post with id {id} does not exist")
post_dict = my_post.dict()
post_dict["id"]= id
my_post[index]= post_dict
return {"message" : "updated post"}
다른 모든 것들은 작동하지만, 기능은 마지막에 있습니다. 문자 그대로 튜토리얼과 함께 코딩하고 짜증나는 문제가 끊이지 않습니다.
파이썬 콘솔은 다음과 같이 말합니다.
우체부는 말한다:
"detail":
"loc":
"body","msg": "field required",
"type": "value_error.missing"
이 오류는 요청의 어느 부분이 예상된 형식과 일치하지 않는지 정확히 알려줍니다. 당신의 경우, 그것은 누락되었다고 쓰여 있습니다. Pydantic 모델을 사용할 때, 당신은 본질적으로 객체(또는 Python dict)를 선언하고, 따라서 당신의 엔드포인트는 JSON 형식의 것을 기대한다. 따라서, 당신이 보내는 요청은 피단틱 모델과 일치하는 페이로드를 포함해야 한다. 아래는 Python 요청을 사용하는 예이지만(자세한 내용은 에서 확인할 수 있다) OpenAPI/Swager UI autodocsat를 사용하여 API를 테스트할 수도 있습니다.
예
import requests
url = 'http://127.0.0.1:8000/posts/2'
payload = {"title": "string", "content": "string", "Published": True,"rating": 0}
resp = requests.put(url, json=payload)
print(resp.json())
반응형