【问题标题】:FAST API- error-value is not valid integerFAST API-错误值不是有效的整数
【发布时间】:2023-03-24 03:50:02
【问题描述】:

做一个教程来创建一个休息 API,我的 get("posts/latest") 不起作用。该教程说这可能是因为快速 API 从上到下读取并且它认为路径是 (posts/{id}) 路径。但是,我明白这一点:我已将其移至该功能之前,但仍然出现错误?

    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}  

【问题讨论】:

  • 您收到的错误信息是什么?
  • len(my_post-1)也有错误....应该是len(my_post) - 1 但你可以全部替换为my_post[-1]
  • @daniboy000 谢谢,我想就是这样,它说值不是整数。我以为它指的是类参数

标签: python api rest backend fastapi


【解决方案1】:

我打赌你只是忘记了路径名中的斜杠,所以路径不匹配

关注

@app.get("posts/latest")

路径的开头应该有斜线

@app.get("/posts/latest")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多