mirror of https://github.com/tiangolo/fastapi.git
Improve error handling for item retrieval
Fix: Return 404 for non-existent items instead of null response Previously, valid ID formats with non-existent items returned 200 OK with null values, creating ambiguous API responses. Now properly returns 404 Not Found when items don't exist in the database.
This commit is contained in:
parent
cbe5bdb85f
commit
13440986a1
|
|
@ -1,7 +1,7 @@
|
||||||
import random
|
import random
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI, HTTPException
|
||||||
from pydantic import AfterValidator
|
from pydantic import AfterValidator
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
@ -25,6 +25,8 @@ async def read_items(
|
||||||
):
|
):
|
||||||
if id:
|
if id:
|
||||||
item = data.get(id)
|
item = data.get(id)
|
||||||
|
if item is None:
|
||||||
|
raise HTTPException(status_code=404, detail=f"Item with id '{id}' not found")
|
||||||
else:
|
else:
|
||||||
id, item = random.choice(list(data.items()))
|
id, item = random.choice(list(data.items()))
|
||||||
return {"id": id, "name": item}
|
return {"id": id, "name": item}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue