Search code examples
pythonfastapicrud

FastAPI server returns "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"}

   

Everything else works, but the put/update function at the end. Literally coding along with a tutorial and have non-stop irritating issues.

Python console says: 422 Unprocessable Entity.

Postman says:

"detail": 
"loc":
"body","msg": "field required",
"type": "value_error.missing"

Solution

  • The 422 unprocessable entity error tells exactly which part of your request doesn't match the expected format or is missing. In your case, it says that the body is missing. When using Pydantic models, you essentially declare a JSON object (or Python dict), and hence, your endpoint expects a request body in JSON format. Thus, the request you send must include a JSON payload matching the Pydantic model. Below is an example using Python requests (more details can be found in this answer), but you could also use OpenAPI/Swagger UI autodocs at http://127.0.0.1:8000/docs to test the API. Also, please have a look at this answer for more details and examples on 422 unprocessable entity error when posting JSON data.

    Example

    app.py

    from pydantic import BaseModel
    
    class Post(BaseModel):
        title: str
        content: str
        published: bool = True
        rating: Optional[int] = None
    
    # ...
    
    @app.put('/posts/{id}')
    def update_post(id: int , post: Post):
        pass
    

    test.py

    import requests
    
    post_id = 2
    url = f'http://127.0.0.1:8000/posts/{post_id}'
    payload = {"title": "string", "content": "string", "published": True, "rating": 0}
    resp = requests.put(url, json=payload)
    print(resp.json())