🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 46 (from laksa123)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

📄
INDEXABLE
CRAWLED
2 days ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0.1 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://fastapi.tiangolo.com/tutorial/handling-errors/
Last Crawled2026-04-10 22:26:39 (2 days ago)
First Indexed2019-02-16 16:40:47 (7 years ago)
HTTP Status Code200
Meta TitleHandling Errors - FastAPI
Meta DescriptionFastAPI framework, high performance, easy to learn, fast to code, ready for production
Meta Canonicalnull
Boilerpipe Text
There are many situations in which you need to notify an error to a client that is using your API. This client could be a browser with a frontend, a code from someone else, an IoT device, etc. You could need to tell the client that: The client doesn't have enough privileges for that operation. The client doesn't have access to that resource. The item the client was trying to access doesn't exist. etc. In these cases, you would normally return an HTTP status code in the range of 400 (from 400 to 499). This is similar to the 200 HTTP status codes (from 200 to 299). Those "200" status codes mean that somehow there was a "success" in the request. The status codes in the 400 range mean that there was an error from the client. Remember all those "404 Not Found" errors (and jokes)? Use HTTPException ¶ To return HTTP responses with errors to the client you use HTTPException . Import HTTPException ¶ from fastapi import FastAPI , HTTPException app = FastAPI () items = { "foo" : "The Foo Wrestlers" } @app . get ( "/items/ {item_id} " ) async def read_item ( item_id : str ): if item_id not in items : raise HTTPException ( status_code = 404 , detail = "Item not found" ) return { "item" : items [ item_id ]} Raise an HTTPException in your code ¶ HTTPException is a normal Python exception with additional data relevant for APIs. Because it's a Python exception, you don't return it, you raise it. This also means that if you are inside a utility function that you are calling inside of your path operation function , and you raise the HTTPException from inside of that utility function, it won't run the rest of the code in the path operation function , it will terminate that request right away and send the HTTP error from the HTTPException to the client. The benefit of raising an exception over returning a value will be more evident in the section about Dependencies and Security. In this example, when the client requests an item by an ID that doesn't exist, raise an exception with a status code of 404 : from fastapi import FastAPI , HTTPException app = FastAPI () items = { "foo" : "The Foo Wrestlers" } @app . get ( "/items/ {item_id} " ) async def read_item ( item_id : str ): if item_id not in items : raise HTTPException ( status_code = 404 , detail = "Item not found" ) return { "item" : items [ item_id ]} The resulting response ¶ If the client requests http://example.com/items/foo (an item_id "foo" ), that client will receive an HTTP status code of 200, and a JSON response of: { "item" : "The Foo Wrestlers" } But if the client requests http://example.com/items/bar (a non-existent item_id "bar" ), that client will receive an HTTP status code of 404 (the "not found" error), and a JSON response of: { "detail" : "Item not found" } Tip When raising an HTTPException , you can pass any value that can be converted to JSON as the parameter detail , not only str . You could pass a dict , a list , etc. They are handled automatically by FastAPI and converted to JSON. There are some situations in where it's useful to be able to add custom headers to the HTTP error. For example, for some types of security. You probably won't need to use it directly in your code. But in case you needed it for an advanced scenario, you can add custom headers: from fastapi import FastAPI , HTTPException app = FastAPI () items = { "foo" : "The Foo Wrestlers" } @app . get ( "/items-header/ {item_id} " ) async def read_item_header ( item_id : str ): if item_id not in items : raise HTTPException ( status_code = 404 , detail = "Item not found" , headers = { "X-Error" : "There goes my error" }, ) return { "item" : items [ item_id ]} Install custom exception handlers ¶ You can add custom exception handlers with the same exception utilities from Starlette . Let's say you have a custom exception UnicornException that you (or a library you use) might raise . And you want to handle this exception globally with FastAPI. You could add a custom exception handler with @app.exception_handler() : from fastapi import FastAPI , Request from fastapi.responses import JSONResponse class UnicornException ( Exception ): def __init__ ( self , name : str ): self . name = name app = FastAPI () @app . exception_handler ( UnicornException ) async def unicorn_exception_handler ( request : Request , exc : UnicornException ): return JSONResponse ( status_code = 418 , content = { "message" : f "Oops! { exc . name } did something. There goes a rainbow..." }, ) @app . get ( "/unicorns/ {name} " ) async def read_unicorn ( name : str ): if name == "yolo" : raise UnicornException ( name = name ) return { "unicorn_name" : name } Here, if you request /unicorns/yolo , the path operation will raise a UnicornException . But it will be handled by the unicorn_exception_handler . So, you will receive a clean error, with an HTTP status code of 418 and a JSON content of: { "message" : "Oops! yolo did something. There goes a rainbow..." } Technical Details You could also use from starlette.requests import Request and from starlette.responses import JSONResponse . FastAPI provides the same starlette.responses as fastapi.responses just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with Request . Override the default exception handlers ¶ FastAPI has some default exception handlers. These handlers are in charge of returning the default JSON responses when you raise an HTTPException and when the request has invalid data. You can override these exception handlers with your own. Override request validation exceptions ¶ When a request contains invalid data, FastAPI internally raises a RequestValidationError . And it also includes a default exception handler for it. To override it, import the RequestValidationError and use it with @app.exception_handler(RequestValidationError) to decorate the exception handler. The exception handler will receive a Request and the exception. from fastapi import FastAPI , HTTPException from fastapi.exceptions import RequestValidationError from fastapi.responses import PlainTextResponse from starlette.exceptions import HTTPException as StarletteHTTPException app = FastAPI () @app . exception_handler ( StarletteHTTPException ) async def http_exception_handler ( request , exc ): return PlainTextResponse ( str ( exc . detail ), status_code = exc . status_code ) @app . exception_handler ( RequestValidationError ) async def validation_exception_handler ( request , exc : RequestValidationError ): message = "Validation errors:" for error in exc . errors (): message += f " \n Field: { error [ 'loc' ] } , Error: { error [ 'msg' ] } " return PlainTextResponse ( message , status_code = 400 ) @app . get ( "/items/ {item_id} " ) async def read_item ( item_id : int ): if item_id == 3 : raise HTTPException ( status_code = 418 , detail = "Nope! I don't like 3." ) return { "item_id" : item_id } Now, if you go to /items/foo , instead of getting the default JSON error with: { "detail" : [ { "loc" : [ "path" , "item_id" ], "msg" : "value is not a valid integer" , "type" : "type_error.integer" } ] } you will get a text version, with: Validation errors: Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer Override the HTTPException error handler ¶ The same way, you can override the HTTPException handler. For example, you could want to return a plain text response instead of JSON for these errors: from fastapi import FastAPI , HTTPException from fastapi.exceptions import RequestValidationError from fastapi.responses import PlainTextResponse from starlette.exceptions import HTTPException as StarletteHTTPException app = FastAPI () @app . exception_handler ( StarletteHTTPException ) async def http_exception_handler ( request , exc ): return PlainTextResponse ( str ( exc . detail ), status_code = exc . status_code ) @app . exception_handler ( RequestValidationError ) async def validation_exception_handler ( request , exc : RequestValidationError ): message = "Validation errors:" for error in exc . errors (): message += f " \n Field: { error [ 'loc' ] } , Error: { error [ 'msg' ] } " return PlainTextResponse ( message , status_code = 400 ) @app . get ( "/items/ {item_id} " ) async def read_item ( item_id : int ): if item_id == 3 : raise HTTPException ( status_code = 418 , detail = "Nope! I don't like 3." ) return { "item_id" : item_id } Technical Details You could also use from starlette.responses import PlainTextResponse . FastAPI provides the same starlette.responses as fastapi.responses just as a convenience for you, the developer. But most of the available responses come directly from Starlette. Warning Have in mind that the RequestValidationError contains the information of the file name and line where the validation error happens so that you can show it in your logs with the relevant information if you want to. But that means that if you just convert it to a string and return that information directly, you could be leaking a bit of information about your system, that's why here the code extracts and shows each error independently. Use the RequestValidationError body ¶ The RequestValidationError contains the body it received with invalid data. You could use it while developing your app to log the body and debug it, return it to the user, etc. from fastapi import FastAPI , Request from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from pydantic import BaseModel app = FastAPI () @app . exception_handler ( RequestValidationError ) async def validation_exception_handler ( request : Request , exc : RequestValidationError ): return JSONResponse ( status_code = 422 , content = jsonable_encoder ({ "detail" : exc . errors (), "body" : exc . body }), ) class Item ( BaseModel ): title : str size : int @app . post ( "/items/" ) async def create_item ( item : Item ): return item Now try sending an invalid item like: { "title" : "towel" , "size" : "XL" } You will receive a response telling you that the data is invalid containing the received body: { "detail" : [ { "loc" : [ "body" , "size" ], "msg" : "value is not a valid integer" , "type" : "type_error.integer" } ], "body" : { "title" : "towel" , "size" : "XL" } } FastAPI's HTTPException vs Starlette's HTTPException ¶ FastAPI has its own HTTPException . And FastAPI 's HTTPException error class inherits from Starlette's HTTPException error class. The only difference is that FastAPI 's HTTPException accepts any JSON-able data for the detail field, while Starlette's HTTPException only accepts strings for it. So, you can keep raising FastAPI 's HTTPException as normally in your code. But when you register an exception handler, you should register it for Starlette's HTTPException . This way, if any part of Starlette's internal code, or a Starlette extension or plug-in, raises a Starlette HTTPException , your handler will be able to catch and handle it. In this example, to be able to have both HTTPException s in the same code, Starlette's exceptions is renamed to StarletteHTTPException : from starlette.exceptions import HTTPException as StarletteHTTPException Reuse FastAPI 's exception handlers ¶ If you want to use the exception along with the same default exception handlers from FastAPI , you can import and reuse the default exception handlers from fastapi.exception_handlers : from fastapi import FastAPI , HTTPException from fastapi.exception_handlers import ( http_exception_handler , request_validation_exception_handler , ) from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException as StarletteHTTPException app = FastAPI () @app . exception_handler ( StarletteHTTPException ) async def custom_http_exception_handler ( request , exc ): print ( f "OMG! An HTTP error!: { repr ( exc ) } " ) return await http_exception_handler ( request , exc ) @app . exception_handler ( RequestValidationError ) async def validation_exception_handler ( request , exc ): print ( f "OMG! The client sent invalid data!: { exc } " ) return await request_validation_exception_handler ( request , exc ) @app . get ( "/items/ {item_id} " ) async def read_item ( item_id : int ): if item_id == 3 : raise HTTPException ( status_code = 418 , detail = "Nope! I don't like 3." ) return { "item_id" : item_id } In this example you are just printing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers.
Markdown
[Skip to content](https://fastapi.tiangolo.com/tutorial/handling-errors/#handling-errors) [Join the **FastAPI Cloud** waiting list 🚀](https://fastapicloud.com/) [Follow **@fastapi** on **X (Twitter)** to stay updated](https://x.com/fastapi) [Follow **FastAPI** on **LinkedIn** to stay updated](https://www.linkedin.com/company/fastapi) [Subscribe to the **FastAPI and friends** newsletter 🎉](https://fastapi.tiangolo.com/newsletter/) [sponsor ![](https://fastapi.tiangolo.com/img/sponsors/blockbee-banner.png)](https://blockbee.io/?ref=fastapi "BlockBee Cryptocurrency Payment Gateway") [sponsor ![](https://fastapi.tiangolo.com/img/sponsors/scalar-banner.svg)](https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=top-banner "Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files") [sponsor ![](https://fastapi.tiangolo.com/img/sponsors/propelauth-banner.png)](https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=topbanner "Auth, user management and more for your B2B product") [sponsor ![](https://fastapi.tiangolo.com/img/sponsors/zuplo-banner.png)](https://zuplo.link/fastapi-web "Zuplo: Scale, Protect, Document, and Monetize your FastAPI") [sponsor ![](https://fastapi.tiangolo.com/img/sponsors/liblab-banner.png)](https://liblab.com/?utm_source=fastapi "liblab - Generate SDKs from FastAPI") [sponsor ![](https://fastapi.tiangolo.com/img/sponsors/render-banner.svg)](https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi "Deploy & scale any full-stack web app on Render. Focus on building apps, not infra.") [sponsor ![](https://fastapi.tiangolo.com/img/sponsors/coderabbit-banner.png)](https://www.coderabbit.ai/?utm_source=fastapi&utm_medium=banner&utm_campaign=fastapi "Cut Code Review Time & Bugs in Half with CodeRabbit") [sponsor ![](https://fastapi.tiangolo.com/img/sponsors/subtotal-banner.svg)](https://subtotal.com/?utm_source=fastapi&utm_medium=sponsorship&utm_campaign=open-source "Making Retail Purchases Actionable for Brands and Developers") [sponsor ![](https://fastapi.tiangolo.com/img/sponsors/railway-banner.png)](https://docs.railway.com/guides/fastapi?utm_medium=integration&utm_source=docs&utm_campaign=fastapi "Deploy enterprise applications at startup speed") [sponsor ![](https://fastapi.tiangolo.com/img/sponsors/serpapi-banner.png)](https://serpapi.com/?utm_source=fastapi_website "SerpApi: Web Search API") [sponsor ![](https://fastapi.tiangolo.com/img/sponsors/greptile-banner.png)](https://www.greptile.com/?utm_source=fastapi&utm_medium=sponsorship&utm_campaign=fastapi_sponsor_page "Greptile: The AI Code Reviewer") [![logo](https://fastapi.tiangolo.com/img/icon-white.svg)](https://fastapi.tiangolo.com/ "FastAPI") FastAPI Handling Errors - [en - English](https://fastapi.tiangolo.com/) - [de - Deutsch](https://fastapi.tiangolo.com/de/) - [es - español](https://fastapi.tiangolo.com/es/) - [fr - français](https://fastapi.tiangolo.com/fr/) - [ja - 日本語](https://fastapi.tiangolo.com/ja/) - [ko - 한국어](https://fastapi.tiangolo.com/ko/) - [pt - português](https://fastapi.tiangolo.com/pt/) - [ru - русский язык](https://fastapi.tiangolo.com/ru/) - [tr - Türkçe](https://fastapi.tiangolo.com/tr/) - [uk - українська мова](https://fastapi.tiangolo.com/uk/) - [zh - 简体中文](https://fastapi.tiangolo.com/zh/) - [zh-hant - 繁體中文](https://fastapi.tiangolo.com/zh-hant/) Type to start searching [fastapi/fastapi 0.135.3 96.8k 9k](https://github.com/fastapi/fastapi "Go to repository") - [FastAPI](https://fastapi.tiangolo.com/) - [Features](https://fastapi.tiangolo.com/features/) - [Learn](https://fastapi.tiangolo.com/learn/) - [Reference](https://fastapi.tiangolo.com/reference/) - [FastAPI People](https://fastapi.tiangolo.com/fastapi-people/) - [Resources](https://fastapi.tiangolo.com/resources/) - [About](https://fastapi.tiangolo.com/about/) - [Release Notes](https://fastapi.tiangolo.com/release-notes/) [![logo](https://fastapi.tiangolo.com/img/icon-white.svg)](https://fastapi.tiangolo.com/ "FastAPI") FastAPI [fastapi/fastapi 0.135.3 96.8k 9k](https://github.com/fastapi/fastapi "Go to repository") - [FastAPI](https://fastapi.tiangolo.com/) - [Features](https://fastapi.tiangolo.com/features/) - [Learn](https://fastapi.tiangolo.com/learn/) Learn - [Python Types Intro](https://fastapi.tiangolo.com/python-types/) - [Concurrency and async / await](https://fastapi.tiangolo.com/async/) - [Environment Variables](https://fastapi.tiangolo.com/environment-variables/) - [Virtual Environments](https://fastapi.tiangolo.com/virtual-environments/) - [Tutorial - User Guide](https://fastapi.tiangolo.com/tutorial/) Tutorial - User Guide - [First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/) - [Path Parameters](https://fastapi.tiangolo.com/tutorial/path-params/) - [Query Parameters](https://fastapi.tiangolo.com/tutorial/query-params/) - [Request Body](https://fastapi.tiangolo.com/tutorial/body/) - [Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/) - [Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/) - [Query Parameter Models](https://fastapi.tiangolo.com/tutorial/query-param-models/) - [Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/) - [Body - Fields](https://fastapi.tiangolo.com/tutorial/body-fields/) - [Body - Nested Models](https://fastapi.tiangolo.com/tutorial/body-nested-models/) - [Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) - [Extra Data Types](https://fastapi.tiangolo.com/tutorial/extra-data-types/) - [Cookie Parameters](https://fastapi.tiangolo.com/tutorial/cookie-params/) - [Header Parameters](https://fastapi.tiangolo.com/tutorial/header-params/) - [Cookie Parameter Models](https://fastapi.tiangolo.com/tutorial/cookie-param-models/) - [Header Parameter Models](https://fastapi.tiangolo.com/tutorial/header-param-models/) - [Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/) - [Extra Models](https://fastapi.tiangolo.com/tutorial/extra-models/) - [Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/) - [Form Data](https://fastapi.tiangolo.com/tutorial/request-forms/) - [Form Models](https://fastapi.tiangolo.com/tutorial/request-form-models/) - [Request Files](https://fastapi.tiangolo.com/tutorial/request-files/) - [Request Forms and Files](https://fastapi.tiangolo.com/tutorial/request-forms-and-files/) - Handling Errors [Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/) Table of contents - [Use `HTTPException`](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception) - [Import `HTTPException`](https://fastapi.tiangolo.com/tutorial/handling-errors/#import-httpexception) - [Raise an `HTTPException` in your code](https://fastapi.tiangolo.com/tutorial/handling-errors/#raise-an-httpexception-in-your-code) - [The resulting response](https://fastapi.tiangolo.com/tutorial/handling-errors/#the-resulting-response) - [Add custom headers](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers) - [Install custom exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers) - [Override the default exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-default-exception-handlers) - [Override request validation exceptions](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-request-validation-exceptions) - [Override the `HTTPException` error handler](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-httpexception-error-handler) - [Use the `RequestValidationError` body](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-the-requestvalidationerror-body) - [FastAPI's `HTTPException` vs Starlette's `HTTPException`](https://fastapi.tiangolo.com/tutorial/handling-errors/#fastapis-httpexception-vs-starlettes-httpexception) - [Reuse **FastAPI**'s exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#reuse-fastapis-exception-handlers) - [Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/) - [JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/) - [Body - Updates](https://fastapi.tiangolo.com/tutorial/body-updates/) - [Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/) Dependencies - [Classes as Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies/) - [Sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/) - [Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/) - [Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/) - [Dependencies with yield](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/) - [Security](https://fastapi.tiangolo.com/tutorial/security/) Security - [Security - First Steps](https://fastapi.tiangolo.com/tutorial/security/first-steps/) - [Get Current User](https://fastapi.tiangolo.com/tutorial/security/get-current-user/) - [Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/) - [OAuth2 with Password (and hashing), Bearer with JWT tokens](https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/) - [Middleware](https://fastapi.tiangolo.com/tutorial/middleware/) - [CORS (Cross-Origin Resource Sharing)](https://fastapi.tiangolo.com/tutorial/cors/) - [SQL (Relational) Databases](https://fastapi.tiangolo.com/tutorial/sql-databases/) - [Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/) - [Stream JSON Lines](https://fastapi.tiangolo.com/tutorial/stream-json-lines/) - [Server-Sent Events (SSE)](https://fastapi.tiangolo.com/tutorial/server-sent-events/) - [Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/) - [Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/) - [Static Files](https://fastapi.tiangolo.com/tutorial/static-files/) - [Testing](https://fastapi.tiangolo.com/tutorial/testing/) - [Debugging](https://fastapi.tiangolo.com/tutorial/debugging/) - [Advanced User Guide](https://fastapi.tiangolo.com/advanced/) Advanced User Guide - [Stream Data](https://fastapi.tiangolo.com/advanced/stream-data/) - [Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/) - [Additional Status Codes](https://fastapi.tiangolo.com/advanced/additional-status-codes/) - [Return a Response Directly](https://fastapi.tiangolo.com/advanced/response-directly/) - [Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/) - [Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/) - [Response Cookies](https://fastapi.tiangolo.com/advanced/response-cookies/) - [Response Headers](https://fastapi.tiangolo.com/advanced/response-headers/) - [Response - Change Status Code](https://fastapi.tiangolo.com/advanced/response-change-status-code/) - [Advanced Dependencies](https://fastapi.tiangolo.com/advanced/advanced-dependencies/) - [Advanced Security](https://fastapi.tiangolo.com/advanced/security/) Advanced Security - [OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/) - [HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/) - [Using the Request Directly](https://fastapi.tiangolo.com/advanced/using-request-directly/) - [Using Dataclasses](https://fastapi.tiangolo.com/advanced/dataclasses/) - [Advanced Middleware](https://fastapi.tiangolo.com/advanced/middleware/) - [Sub Applications - Mounts](https://fastapi.tiangolo.com/advanced/sub-applications/) - [Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/) - [Templates](https://fastapi.tiangolo.com/advanced/templates/) - [WebSockets](https://fastapi.tiangolo.com/advanced/websockets/) - [Lifespan Events](https://fastapi.tiangolo.com/advanced/events/) - [Testing WebSockets](https://fastapi.tiangolo.com/advanced/testing-websockets/) - [Testing Events: lifespan and startup - shutdown](https://fastapi.tiangolo.com/advanced/testing-events/) - [Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/) - [Async Tests](https://fastapi.tiangolo.com/advanced/async-tests/) - [Settings and Environment Variables](https://fastapi.tiangolo.com/advanced/settings/) - [OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/) - [OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/) - [Including WSGI - Flask, Django, others](https://fastapi.tiangolo.com/advanced/wsgi/) - [Generating SDKs](https://fastapi.tiangolo.com/advanced/generate-clients/) - [Advanced Python Types](https://fastapi.tiangolo.com/advanced/advanced-python-types/) - [JSON with Bytes as Base64](https://fastapi.tiangolo.com/advanced/json-base64-bytes/) - [Strict Content-Type Checking](https://fastapi.tiangolo.com/advanced/strict-content-type/) - [Vibe Coding](https://fastapi.tiangolo.com/advanced/vibe/) - [FastAPI CLI](https://fastapi.tiangolo.com/fastapi-cli/) - [Editor Support](https://fastapi.tiangolo.com/editor-support/) - [Deployment](https://fastapi.tiangolo.com/deployment/) Deployment - [About FastAPI versions](https://fastapi.tiangolo.com/deployment/versions/) - [FastAPI Cloud](https://fastapi.tiangolo.com/deployment/fastapicloud/) - [About HTTPS](https://fastapi.tiangolo.com/deployment/https/) - [Run a Server Manually](https://fastapi.tiangolo.com/deployment/manually/) - [Deployments Concepts](https://fastapi.tiangolo.com/deployment/concepts/) - [Deploy FastAPI on Cloud Providers](https://fastapi.tiangolo.com/deployment/cloud/) - [Server Workers - Uvicorn with Workers](https://fastapi.tiangolo.com/deployment/server-workers/) - [FastAPI in Containers - Docker](https://fastapi.tiangolo.com/deployment/docker/) - [How To - Recipes](https://fastapi.tiangolo.com/how-to/) How To - Recipes - [General - How To - Recipes](https://fastapi.tiangolo.com/how-to/general/) - [Migrate from Pydantic v1 to Pydantic v2](https://fastapi.tiangolo.com/how-to/migrate-from-pydantic-v1-to-pydantic-v2/) - [GraphQL](https://fastapi.tiangolo.com/how-to/graphql/) - [Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/) - [Conditional OpenAPI](https://fastapi.tiangolo.com/how-to/conditional-openapi/) - [Extending OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/) - [Separate OpenAPI Schemas for Input and Output or Not](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas/) - [Custom Docs UI Static Assets (Self-Hosting)](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/) - [Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/) - [Testing a Database](https://fastapi.tiangolo.com/how-to/testing-database/) - [Use Old 403 Authentication Error Status Codes](https://fastapi.tiangolo.com/how-to/authentication-error-status-code/) - [Reference](https://fastapi.tiangolo.com/reference/) Reference - [`FastAPI` class](https://fastapi.tiangolo.com/reference/fastapi/) - [Request Parameters](https://fastapi.tiangolo.com/reference/parameters/) - [Status Codes](https://fastapi.tiangolo.com/reference/status/) - [`UploadFile` class](https://fastapi.tiangolo.com/reference/uploadfile/) - [Exceptions - `HTTPException` and `WebSocketException`](https://fastapi.tiangolo.com/reference/exceptions/) - [Dependencies - `Depends()` and `Security()`](https://fastapi.tiangolo.com/reference/dependencies/) - [`APIRouter` class](https://fastapi.tiangolo.com/reference/apirouter/) - [Background Tasks - `BackgroundTasks`](https://fastapi.tiangolo.com/reference/background/) - [`Request` class](https://fastapi.tiangolo.com/reference/request/) - [WebSockets](https://fastapi.tiangolo.com/reference/websockets/) - [`HTTPConnection` class](https://fastapi.tiangolo.com/reference/httpconnection/) - [`Response` class](https://fastapi.tiangolo.com/reference/response/) - [Custom Response Classes - File, HTML, Redirect, Streaming, etc.](https://fastapi.tiangolo.com/reference/responses/) - [Middleware](https://fastapi.tiangolo.com/reference/middleware/) - [OpenAPI](https://fastapi.tiangolo.com/reference/openapi/) OpenAPI - [OpenAPI `docs`](https://fastapi.tiangolo.com/reference/openapi/docs/) - [OpenAPI `models`](https://fastapi.tiangolo.com/reference/openapi/models/) - [Security Tools](https://fastapi.tiangolo.com/reference/security/) - [Encoders - `jsonable_encoder`](https://fastapi.tiangolo.com/reference/encoders/) - [Static Files - `StaticFiles`](https://fastapi.tiangolo.com/reference/staticfiles/) - [Templating - `Jinja2Templates`](https://fastapi.tiangolo.com/reference/templating/) - [Test Client - `TestClient`](https://fastapi.tiangolo.com/reference/testclient/) - [FastAPI People](https://fastapi.tiangolo.com/fastapi-people/) - [Resources](https://fastapi.tiangolo.com/resources/) Resources - [Help FastAPI - Get Help](https://fastapi.tiangolo.com/help-fastapi/) - [Development - Contributing](https://fastapi.tiangolo.com/contributing/) - [Full Stack FastAPI Template](https://fastapi.tiangolo.com/project-generation/) - [External Links](https://fastapi.tiangolo.com/external-links/) - [FastAPI and friends newsletter](https://fastapi.tiangolo.com/newsletter/) - [Repository Management Tasks](https://fastapi.tiangolo.com/management-tasks/) - [About](https://fastapi.tiangolo.com/about/) About - [Alternatives, Inspiration and Comparisons](https://fastapi.tiangolo.com/alternatives/) - [History, Design and Future](https://fastapi.tiangolo.com/history-design-future/) - [Benchmarks](https://fastapi.tiangolo.com/benchmarks/) - [Repository Management](https://fastapi.tiangolo.com/management/) - [Release Notes](https://fastapi.tiangolo.com/release-notes/) Table of contents - [Use `HTTPException`](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception) - [Import `HTTPException`](https://fastapi.tiangolo.com/tutorial/handling-errors/#import-httpexception) - [Raise an `HTTPException` in your code](https://fastapi.tiangolo.com/tutorial/handling-errors/#raise-an-httpexception-in-your-code) - [The resulting response](https://fastapi.tiangolo.com/tutorial/handling-errors/#the-resulting-response) - [Add custom headers](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers) - [Install custom exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers) - [Override the default exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-default-exception-handlers) - [Override request validation exceptions](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-request-validation-exceptions) - [Override the `HTTPException` error handler](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-httpexception-error-handler) - [Use the `RequestValidationError` body](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-the-requestvalidationerror-body) - [FastAPI's `HTTPException` vs Starlette's `HTTPException`](https://fastapi.tiangolo.com/tutorial/handling-errors/#fastapis-httpexception-vs-starlettes-httpexception) - [Reuse **FastAPI**'s exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#reuse-fastapis-exception-handlers) 1. [FastAPI](https://fastapi.tiangolo.com/) 2. [Learn](https://fastapi.tiangolo.com/learn/) 3. [Tutorial - User Guide](https://fastapi.tiangolo.com/tutorial/) # Handling Errors[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#handling-errors) There are many situations in which you need to notify an error to a client that is using your API. This client could be a browser with a frontend, a code from someone else, an IoT device, etc. You could need to tell the client that: - The client doesn't have enough privileges for that operation. - The client doesn't have access to that resource. - The item the client was trying to access doesn't exist. - etc. In these cases, you would normally return an **HTTP status code** in the range of **400** (from 400 to 499). This is similar to the 200 HTTP status codes (from 200 to 299). Those "200" status codes mean that somehow there was a "success" in the request. The status codes in the 400 range mean that there was an error from the client. Remember all those **"404 Not Found"** errors (and jokes)? ## Use `HTTPException`[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception) To return HTTP responses with errors to the client you use `HTTPException`. ### Import `HTTPException`[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#import-httpexception) [Python 3.10+](https://fastapi.tiangolo.com/tutorial/handling-errors/#__tabbed_1_1) ``` ``` ### Raise an `HTTPException` in your code[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#raise-an-httpexception-in-your-code) `HTTPException` is a normal Python exception with additional data relevant for APIs. Because it's a Python exception, you don't `return` it, you `raise` it. This also means that if you are inside a utility function that you are calling inside of your *path operation function*, and you raise the `HTTPException` from inside of that utility function, it won't run the rest of the code in the *path operation function*, it will terminate that request right away and send the HTTP error from the `HTTPException` to the client. The benefit of raising an exception over returning a value will be more evident in the section about Dependencies and Security. In this example, when the client requests an item by an ID that doesn't exist, raise an exception with a status code of `404`: [Python 3.10+](https://fastapi.tiangolo.com/tutorial/handling-errors/#__tabbed_2_1) ``` ``` ### The resulting response[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#the-resulting-response) If the client requests `http://example.com/items/foo` (an `item_id` `"foo"`), that client will receive an HTTP status code of 200, and a JSON response of: ``` ``` But if the client requests `http://example.com/items/bar` (a non-existent `item_id` `"bar"`), that client will receive an HTTP status code of 404 (the "not found" error), and a JSON response of: ``` ``` Tip When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`. You could pass a `dict`, a `list`, etc. They are handled automatically by **FastAPI** and converted to JSON. ## Add custom headers[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers) There are some situations in where it's useful to be able to add custom headers to the HTTP error. For example, for some types of security. You probably won't need to use it directly in your code. But in case you needed it for an advanced scenario, you can add custom headers: [Python 3.10+](https://fastapi.tiangolo.com/tutorial/handling-errors/#__tabbed_3_1) ``` ``` ## Install custom exception handlers[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers) You can add custom exception handlers with [the same exception utilities from Starlette](https://www.starlette.dev/exceptions/). Let's say you have a custom exception `UnicornException` that you (or a library you use) might `raise`. And you want to handle this exception globally with FastAPI. You could add a custom exception handler with `@app.exception_handler()`: [Python 3.10+](https://fastapi.tiangolo.com/tutorial/handling-errors/#__tabbed_4_1) ``` ``` Here, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`. But it will be handled by the `unicorn_exception_handler`. So, you will receive a clean error, with an HTTP status code of `418` and a JSON content of: ``` {"message": "Oops! yolo did something. There goes a rainbow..."} ``` Technical Details You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`. ## Override the default exception handlers[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-default-exception-handlers) **FastAPI** has some default exception handlers. These handlers are in charge of returning the default JSON responses when you `raise` an `HTTPException` and when the request has invalid data. You can override these exception handlers with your own. ### Override request validation exceptions[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-request-validation-exceptions) When a request contains invalid data, **FastAPI** internally raises a `RequestValidationError`. And it also includes a default exception handler for it. To override it, import the `RequestValidationError` and use it with `@app.exception_handler(RequestValidationError)` to decorate the exception handler. The exception handler will receive a `Request` and the exception. [Python 3.10+](https://fastapi.tiangolo.com/tutorial/handling-errors/#__tabbed_5_1) ``` ``` Now, if you go to `/items/foo`, instead of getting the default JSON error with: ``` ``` you will get a text version, with: ``` ``` ### Override the `HTTPException` error handler[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-httpexception-error-handler) The same way, you can override the `HTTPException` handler. For example, you could want to return a plain text response instead of JSON for these errors: [Python 3.10+](https://fastapi.tiangolo.com/tutorial/handling-errors/#__tabbed_6_1) ``` ``` Technical Details You could also use `from starlette.responses import PlainTextResponse`. **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. Warning Have in mind that the `RequestValidationError` contains the information of the file name and line where the validation error happens so that you can show it in your logs with the relevant information if you want to. But that means that if you just convert it to a string and return that information directly, you could be leaking a bit of information about your system, that's why here the code extracts and shows each error independently. ### Use the `RequestValidationError` body[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-the-requestvalidationerror-body) The `RequestValidationError` contains the `body` it received with invalid data. You could use it while developing your app to log the body and debug it, return it to the user, etc. [Python 3.10+](https://fastapi.tiangolo.com/tutorial/handling-errors/#__tabbed_7_1) ``` ``` Now try sending an invalid item like: ``` ``` You will receive a response telling you that the data is invalid containing the received body: ``` ``` #### FastAPI's `HTTPException` vs Starlette's `HTTPException`[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#fastapis-httpexception-vs-starlettes-httpexception) **FastAPI** has its own `HTTPException`. And **FastAPI**'s `HTTPException` error class inherits from Starlette's `HTTPException` error class. The only difference is that **FastAPI**'s `HTTPException` accepts any JSON-able data for the `detail` field, while Starlette's `HTTPException` only accepts strings for it. So, you can keep raising **FastAPI**'s `HTTPException` as normally in your code. But when you register an exception handler, you should register it for Starlette's `HTTPException`. This way, if any part of Starlette's internal code, or a Starlette extension or plug-in, raises a Starlette `HTTPException`, your handler will be able to catch and handle it. In this example, to be able to have both `HTTPException`s in the same code, Starlette's exceptions is renamed to `StarletteHTTPException`: ``` from starlette.exceptions import HTTPException as StarletteHTTPException ``` ### Reuse **FastAPI**'s exception handlers[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#reuse-fastapis-exception-handlers) If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`: [Python 3.10+](https://fastapi.tiangolo.com/tutorial/handling-errors/#__tabbed_8_1) ``` ``` In this example you are just printing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers. Back to top [Previous Request Forms and Files](https://fastapi.tiangolo.com/tutorial/request-forms-and-files/) [Next Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/) The FastAPI trademark is owned by [@tiangolo](https://tiangolo.com/) and is registered in the US and across other regions Made with [Material for MkDocs](https://squidfunk.github.io/mkdocs-material/)
Readable Markdown
There are many situations in which you need to notify an error to a client that is using your API. This client could be a browser with a frontend, a code from someone else, an IoT device, etc. You could need to tell the client that: - The client doesn't have enough privileges for that operation. - The client doesn't have access to that resource. - The item the client was trying to access doesn't exist. - etc. In these cases, you would normally return an **HTTP status code** in the range of **400** (from 400 to 499). This is similar to the 200 HTTP status codes (from 200 to 299). Those "200" status codes mean that somehow there was a "success" in the request. The status codes in the 400 range mean that there was an error from the client. Remember all those **"404 Not Found"** errors (and jokes)? ## Use `HTTPException`[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception) To return HTTP responses with errors to the client you use `HTTPException`. ### Import `HTTPException`[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#import-httpexception) ``` ``` ### Raise an `HTTPException` in your code[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#raise-an-httpexception-in-your-code) `HTTPException` is a normal Python exception with additional data relevant for APIs. Because it's a Python exception, you don't `return` it, you `raise` it. This also means that if you are inside a utility function that you are calling inside of your *path operation function*, and you raise the `HTTPException` from inside of that utility function, it won't run the rest of the code in the *path operation function*, it will terminate that request right away and send the HTTP error from the `HTTPException` to the client. The benefit of raising an exception over returning a value will be more evident in the section about Dependencies and Security. In this example, when the client requests an item by an ID that doesn't exist, raise an exception with a status code of `404`: ``` ``` ### The resulting response[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#the-resulting-response) If the client requests `http://example.com/items/foo` (an `item_id` `"foo"`), that client will receive an HTTP status code of 200, and a JSON response of: ``` ``` But if the client requests `http://example.com/items/bar` (a non-existent `item_id` `"bar"`), that client will receive an HTTP status code of 404 (the "not found" error), and a JSON response of: ``` ``` Tip When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`. You could pass a `dict`, a `list`, etc. They are handled automatically by **FastAPI** and converted to JSON. There are some situations in where it's useful to be able to add custom headers to the HTTP error. For example, for some types of security. You probably won't need to use it directly in your code. But in case you needed it for an advanced scenario, you can add custom headers: ``` ``` ## Install custom exception handlers[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers) You can add custom exception handlers with [the same exception utilities from Starlette](https://www.starlette.dev/exceptions/). Let's say you have a custom exception `UnicornException` that you (or a library you use) might `raise`. And you want to handle this exception globally with FastAPI. You could add a custom exception handler with `@app.exception_handler()`: ``` ``` Here, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`. But it will be handled by the `unicorn_exception_handler`. So, you will receive a clean error, with an HTTP status code of `418` and a JSON content of: ``` {"message": "Oops! yolo did something. There goes a rainbow..."} ``` Technical Details You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`. ## Override the default exception handlers[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-default-exception-handlers) **FastAPI** has some default exception handlers. These handlers are in charge of returning the default JSON responses when you `raise` an `HTTPException` and when the request has invalid data. You can override these exception handlers with your own. ### Override request validation exceptions[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-request-validation-exceptions) When a request contains invalid data, **FastAPI** internally raises a `RequestValidationError`. And it also includes a default exception handler for it. To override it, import the `RequestValidationError` and use it with `@app.exception_handler(RequestValidationError)` to decorate the exception handler. The exception handler will receive a `Request` and the exception. ``` ``` Now, if you go to `/items/foo`, instead of getting the default JSON error with: ``` ``` you will get a text version, with: ``` ``` ### Override the `HTTPException` error handler[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-httpexception-error-handler) The same way, you can override the `HTTPException` handler. For example, you could want to return a plain text response instead of JSON for these errors: ``` ``` Technical Details You could also use `from starlette.responses import PlainTextResponse`. **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. Warning Have in mind that the `RequestValidationError` contains the information of the file name and line where the validation error happens so that you can show it in your logs with the relevant information if you want to. But that means that if you just convert it to a string and return that information directly, you could be leaking a bit of information about your system, that's why here the code extracts and shows each error independently. ### Use the `RequestValidationError` body[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-the-requestvalidationerror-body) The `RequestValidationError` contains the `body` it received with invalid data. You could use it while developing your app to log the body and debug it, return it to the user, etc. ``` ``` Now try sending an invalid item like: ``` ``` You will receive a response telling you that the data is invalid containing the received body: ``` ``` #### FastAPI's `HTTPException` vs Starlette's `HTTPException`[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#fastapis-httpexception-vs-starlettes-httpexception) **FastAPI** has its own `HTTPException`. And **FastAPI**'s `HTTPException` error class inherits from Starlette's `HTTPException` error class. The only difference is that **FastAPI**'s `HTTPException` accepts any JSON-able data for the `detail` field, while Starlette's `HTTPException` only accepts strings for it. So, you can keep raising **FastAPI**'s `HTTPException` as normally in your code. But when you register an exception handler, you should register it for Starlette's `HTTPException`. This way, if any part of Starlette's internal code, or a Starlette extension or plug-in, raises a Starlette `HTTPException`, your handler will be able to catch and handle it. In this example, to be able to have both `HTTPException`s in the same code, Starlette's exceptions is renamed to `StarletteHTTPException`: ``` from starlette.exceptions import HTTPException as StarletteHTTPException ``` ### Reuse **FastAPI**'s exception handlers[¶](https://fastapi.tiangolo.com/tutorial/handling-errors/#reuse-fastapis-exception-handlers) If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`: ``` ``` In this example you are just printing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers.
Shard46 (laksa)
Root Hash14787387764798509246
Unparsed URLcom,tiangolo!fastapi,/tutorial/handling-errors/ s443