Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.1K
Visualizações
El servidor FastAPI devuelve "422 entidad no procesable" - 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"}

Todo lo demás funciona, excepto la función de put/update al final. Literalmente codificar junto con un tutorial y tener problemas irritantes sin parar.

La consola de Python dice: 422 Unprocessable Entity .

cartero dice:

 "detail": "loc": "body","msg": "field required", "type": "value_error.missing"
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

El error de 422 unprocessable entity indica exactamente qué parte de su solicitud no coincide con el formato esperado. En tu caso, dice que falta el body . Cuando usa modelos Pydantic, esencialmente declara un objeto JSON (o dictado de Python) y, por lo tanto, su punto final espera un cuerpo de solicitud con ese objeto. Por lo tanto, la solicitud que envíe debe incluir una carga útil JSON que coincida con el modelo. A continuación se muestra un ejemplo con solicitudes de Python, pero también puede probarlo a través de OpenAPI en http://127.0.0.1:8000/docs .

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

Además, asegúrese de obtener el objeto Publicar correctamente en su punto final. Es decir, la línea post_dict = my_post.dict() debe reemplazarse por post_dict = post.dict() .

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda