Home > front end >  FAST API- error-value is not valid integer
FAST API- error-value is not valid integer

Time:02-04

Doing a tutorial to create a rest API and my get("posts/latest") isn't working. The tutorial says it could be because fast API reads from top to bottom and the it thinks the path is the (posts/{id}) path. I understand that, however: I have moved it to be ahead of that function and i'm still getting the 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}  

CodePudding user response:

I bet you just forgot starting slash in path name, so the path doesn't match

Following

@app.get("posts/latest")

Should have slash at the beginning of the path

@app.get("/posts/latest")
  •  Tags:  
  • Related