fromtypingimportAnnotatedfromfastapiimportDepends,FastAPI,HTTPExceptionapp=FastAPI()data={"plumbus":{"description":"Freshly pickled plumbus","owner":"Morty"},"portal-gun":{"description":"Gun to create portals","owner":"Rick"},}classOwnerError(Exception):passdefget_username():try:yield"Rick"exceptOwnerErrorase:raiseHTTPException(status_code=400,detail=f"Owner error: {e}")@app.get("/items/{item_id}")defget_item(item_id:str,username:Annotated[str,Depends(get_username)]):ifitem_idnotindata:raiseHTTPException(status_code=404,detail="Item not found")item=data[item_id]ifitem["owner"]!=username:raiseOwnerError(username)returnitem
🤓 Other versions and variants
fromfastapiimportDepends,FastAPI,HTTPExceptionfromtyping_extensionsimportAnnotatedapp=FastAPI()data={"plumbus":{"description":"Freshly pickled plumbus","owner":"Morty"},"portal-gun":{"description":"Gun to create portals","owner":"Rick"},}classOwnerError(Exception):passdefget_username():try:yield"Rick"exceptOwnerErrorase:raiseHTTPException(status_code=400,detail=f"Owner error: {e}")@app.get("/items/{item_id}")defget_item(item_id:str,username:Annotated[str,Depends(get_username)]):ifitem_idnotindata:raiseHTTPException(status_code=404,detail="Item not found")item=data[item_id]ifitem["owner"]!=username:raiseOwnerError(username)returnitem
Tip
Prefer to use the Annotated version if possible.
fromfastapiimportDepends,FastAPI,HTTPExceptionapp=FastAPI()data={"plumbus":{"description":"Freshly pickled plumbus","owner":"Morty"},"portal-gun":{"description":"Gun to create portals","owner":"Rick"},}classOwnerError(Exception):passdefget_username():try:yield"Rick"exceptOwnerErrorase:raiseHTTPException(status_code=400,detail=f"Owner error: {e}")@app.get("/items/{item_id}")defget_item(item_id:str,username:str=Depends(get_username)):ifitem_idnotindata:raiseHTTPException(status_code=404,detail="Item not found")item=data[item_id]ifitem["owner"]!=username:raiseOwnerError(username)returnitem
fromtypingimportAnnotatedfromfastapiimportDepends,FastAPI,HTTPExceptionapp=FastAPI()classInternalError(Exception):passdefget_username():try:yield"Rick"exceptInternalError:print("Oops, we didn't raise again, Britney 😱")@app.get("/items/{item_id}")defget_item(item_id:str,username:Annotated[str,Depends(get_username)]):ifitem_id=="portal-gun":raiseInternalError(f"The portal gun is too dangerous to be owned by {username}")ifitem_id!="plumbus":raiseHTTPException(status_code=404,detail="Item not found, there's only a plumbus here")returnitem_id
🤓 Other versions and variants
fromfastapiimportDepends,FastAPI,HTTPExceptionfromtyping_extensionsimportAnnotatedapp=FastAPI()classInternalError(Exception):passdefget_username():try:yield"Rick"exceptInternalError:print("Oops, we didn't raise again, Britney 😱")@app.get("/items/{item_id}")defget_item(item_id:str,username:Annotated[str,Depends(get_username)]):ifitem_id=="portal-gun":raiseInternalError(f"The portal gun is too dangerous to be owned by {username}")ifitem_id!="plumbus":raiseHTTPException(status_code=404,detail="Item not found, there's only a plumbus here")returnitem_id
Tip
Prefer to use the Annotated version if possible.
fromfastapiimportDepends,FastAPI,HTTPExceptionapp=FastAPI()classInternalError(Exception):passdefget_username():try:yield"Rick"exceptInternalError:print("Oops, we didn't raise again, Britney 😱")@app.get("/items/{item_id}")defget_item(item_id:str,username:str=Depends(get_username)):ifitem_id=="portal-gun":raiseInternalError(f"The portal gun is too dangerous to be owned by {username}")ifitem_id!="plumbus":raiseHTTPException(status_code=404,detail="Item not found, there's only a plumbus here")returnitem_id
fromtypingimportAnnotatedfromfastapiimportDepends,FastAPI,HTTPExceptionapp=FastAPI()classInternalError(Exception):passdefget_username():try:yield"Rick"exceptInternalError:print("We don't swallow the internal error here, we raise again 😎")raise@app.get("/items/{item_id}")defget_item(item_id:str,username:Annotated[str,Depends(get_username)]):ifitem_id=="portal-gun":raiseInternalError(f"The portal gun is too dangerous to be owned by {username}")ifitem_id!="plumbus":raiseHTTPException(status_code=404,detail="Item not found, there's only a plumbus here")returnitem_id
🤓 Other versions and variants
fromfastapiimportDepends,FastAPI,HTTPExceptionfromtyping_extensionsimportAnnotatedapp=FastAPI()classInternalError(Exception):passdefget_username():try:yield"Rick"exceptInternalError:print("We don't swallow the internal error here, we raise again 😎")raise@app.get("/items/{item_id}")defget_item(item_id:str,username:Annotated[str,Depends(get_username)]):ifitem_id=="portal-gun":raiseInternalError(f"The portal gun is too dangerous to be owned by {username}")ifitem_id!="plumbus":raiseHTTPException(status_code=404,detail="Item not found, there's only a plumbus here")returnitem_id
Tip
Prefer to use the Annotated version if possible.
fromfastapiimportDepends,FastAPI,HTTPExceptionapp=FastAPI()classInternalError(Exception):passdefget_username():try:yield"Rick"exceptInternalError:print("We don't swallow the internal error here, we raise again 😎")raise@app.get("/items/{item_id}")defget_item(item_id:str,username:str=Depends(get_username)):ifitem_id=="portal-gun":raiseInternalError(f"The portal gun is too dangerous to be owned by {username}")ifitem_id!="plumbus":raiseHTTPException(status_code=404,detail="Item not found, there's only a plumbus here")returnitem_id
现在客户端同样会得到 HTTP 500 Internal Server Error 响应,但是服务器日志会记录下我们自定义的 InternalError。