簡體   English   中英

postman api 說“422 無法處理的實體” - value_error.missing

[英]postman api says "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"}

   

除了最后的放置/更新 function 之外,其他一切都有效。 與教程一起進行字面編碼並且有不間斷的惱人問題-.-'' Python 控制台說:422 無法處理的實體。

postman 說:“詳細信息”:“loc”:“body”,“msg”:“必填字段”,“type”:“value_error.missing”

“422 無法處理的實體”錯誤准確地告訴您請求的哪一部分與預期的格式不匹配。 在您的情況下,它說“身體”丟失了。 當使用 Pydantic 模型時,您基本上聲明了一個 JSON“對象”(或 Python 字典),因此,您的端點需要一個帶有該 object 的請求正文 因此,您發送的請求必須包含與 model 匹配的 JSON 有效負載。 下面是使用 Python 請求的示例,但您也可以通過http://127.0.0.1:8000/docs的 OpenAPI 對其進行測試。

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())

此外,請確保在您的端點中正確獲取 Post object。 也就是說,行post_dict = my_post.dict()應該替換為post_dict = post.dict()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM