Exceptions - HTTPException and WebSocketException

These are the exceptions that you can raise to show errors to the client.

When you raise an exception, as would happen with normal Python, the rest of the excecution is aborted. This way you can raise these exceptions from anywhere in the code to abort a request and show the error to the client.

You can use:

  • HTTPException
  • WebSocketException

These exceptions can be imported directly from fastapi:

  1. from fastapi import HTTPException, WebSocketException

fastapi.HTTPException

  1. HTTPException(status_code, detail=None, headers=None)

Bases: HTTPException

An HTTP exception you can raise in your own code to show errors to the client.

This is for client errors, invalid authentication, invalid data, etc. Not for server errors in your code.

Read more about it in the FastAPI docs for Handling Errors.

Example

  1. from fastapi import FastAPI, HTTPException
  2. app = FastAPI()
  3. items = {"foo": "The Foo Wrestlers"}
  4. @app.get("/items/{item_id}")
  5. async def read_item(item_id: str):
  6. if item_id not in items:
  7. raise HTTPException(status_code=404, detail="Item not found")
  8. return {"item": items[item_id]}
PARAMETERDESCRIPTION
status_code

HTTP status code to send to the client.

TYPE: int

detail

Any data to be sent to the client in the detail key of the JSON response.

TYPE: Any DEFAULT: None

headers

Any headers to send to the client in the response.

TYPE: Optional[Dict[str, str]] DEFAULT: None

Source code in fastapi/exceptions.py

  1. 37
  2. 38
  3. 39
  4. 40
  5. 41
  6. 42
  7. 43
  8. 44
  9. 45
  10. 46
  11. 47
  12. 48
  13. 49
  14. 50
  15. 51
  16. 52
  17. 53
  18. 54
  19. 55
  20. 56
  21. 57
  22. 58
  23. 59
  24. 60
  25. 61
  26. 62
  27. 63
  28. 64
  29. 65
  1. def init(
  2. self,
  3. statuscode: Annotated[
  4. int,
  5. Doc(
  6. “””
  7. HTTP status code to send to the client.
  8. “””
  9. ),
  10. ],
  11. detail: Annotated[
  12. Any,
  13. Doc(
  14. “””
  15. Any data to be sent to the client in the detail key of the JSON
  16. response.
  17. “””
  18. ),
  19. ] = None,
  20. headers: Annotated[
  21. Optional[Dict[str, str]],
  22. Doc(
  23. “””
  24. Any headers to send to the client in the response.
  25. “””
  26. ),
  27. ] = None,
  28. ) -> None:
  29. super()._init(status_code=status_code, detail=detail, headers=headers)

status_code instance-attribute

  1. status_code = status_code

detail instance-attribute

  1. detail = detail

headers instance-attribute

  1. headers = headers

fastapi.WebSocketException

  1. WebSocketException(code, reason=None)

Bases: WebSocketException

A WebSocket exception you can raise in your own code to show errors to the client.

This is for client errors, invalid authentication, invalid data, etc. Not for server errors in your code.

Read more about it in the FastAPI docs for WebSockets.

Example

  1. from typing import Annotated
  2. from fastapi import (
  3. Cookie,
  4. FastAPI,
  5. WebSocket,
  6. WebSocketException,
  7. status,
  8. )
  9. app = FastAPI()
  10. @app.websocket("/items/{item_id}/ws")
  11. async def websocket_endpoint(
  12. *,
  13. websocket: WebSocket,
  14. session: Annotated[str | None, Cookie()] = None,
  15. item_id: str,
  16. ):
  17. if session is None:
  18. raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
  19. await websocket.accept()
  20. while True:
  21. data = await websocket.receive_text()
  22. await websocket.send_text(f"Session cookie is: {session}")
  23. await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
PARAMETERDESCRIPTION
code

TYPE: int

reason

The reason to close the WebSocket connection.

It is UTF-8-encoded data. The interpretation of the reason is up to the application, it is not specified by the WebSocket specification.

It could contain text that could be human-readable or interpretable by the client code, etc.

TYPE: Union[str, None] DEFAULT: None

Source code in fastapi/exceptions.py

  1. 110
  2. 111
  3. 112
  4. 113
  5. 114
  6. 115
  7. 116
  8. 117
  9. 118
  10. 119
  11. 120
  12. 121
  13. 122
  14. 123
  15. 124
  16. 125
  17. 126
  18. 127
  19. 128
  20. 129
  21. 130
  22. 131
  23. 132
  24. 133
  25. 134
  26. 135
  27. 136
  1. def init(
  2. self,
  3. code: Annotated[
  4. int,
  5. Doc(
  6. “””
  7. A closing code from the
  8. valid codes defined in the specification.
  9. “””
  10. ),
  11. ],
  12. reason: Annotated[
  13. Union[str, None],
  14. Doc(
  15. “””
  16. The reason to close the WebSocket connection.
  17. It is UTF-8-encoded data. The interpretation of the reason is up to the
  18. application, it is not specified by the WebSocket specification.
  19. It could contain text that could be human-readable or interpretable
  20. by the client code, etc.
  21. “””
  22. ),
  23. ] = None,
  24. ) -> None:
  25. super().init(code=code, reason=reason)

code instance-attribute

  1. code = code

reason instance-attribute

  1. reason = reason or ''