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:
dualtribesman 2025-11-22 10:11:18 +01:00 committed by GitHub
parent cbe5bdb85f
commit 13440986a1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 3 additions and 1 deletions

View File

@ -1,7 +1,7 @@
import random
from typing import Annotated
from fastapi import FastAPI
from fastapi import FastAPI, HTTPException
from pydantic import AfterValidator
app = FastAPI()
@ -25,6 +25,8 @@ async def read_items(
):
if id:
item = data.get(id)
if item is None:
raise HTTPException(status_code=404, detail=f"Item with id '{id}' not found")
else:
id, item = random.choice(list(data.items()))
return {"id": id, "name": item}