Haciendo un tutorial para crear una API de descanso y mi get("posts/latest") no funciona. El tutorial dice que podría deberse a que la API rápida lee de arriba a abajo y cree que la ruta es la ruta (posts/{id}). Sin embargo, lo entiendo: lo moví para que esté por delante de esa función y todavía recibo el error.
from random import randrange from typing import Optional from fastapi import Body, FastAPI, Response , status 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 @app.post("/posts") def create_post(post: Post): post_dict= post.dict() post_dict['id']= randrange(0,10000) my_post.append(post_dict) print(post) return { "new_post": post_dict } @app.get("/posts") async def get_a_post(): return {"message": "Welcome to my API"} @app.get("posts/latest") def get_latest(): latest_post=my_post[len(my_post-1)] latest_id= latest_post["id"] print(latest_post) return {"post":f"here you go - latest post has an id of { latest_id}"} @app.get("/posts/{id}") def get_posts(id: int , respose: Response): post= find_post(id) print(post) return{"here is the post": post}
Apuesto a que olvidaste comenzar con la barra inclinada en el nombre de la ruta, por lo que la ruta no coincide
Siguiendo
@app.get("posts/latest")
Debería tener una barra al principio de la ruta.
@app.get("/posts/latest")