WebSockets

    The current page still doesn’t have a translation for this language.

    But you can help translating it: Contributing.

    You can use with FastAPI.

    First you need to install WebSockets:

    WebSockets client

    In your production system, you probably have a frontend created with a modern framework like React, Vue.js or Angular.

    And to communicate using WebSockets with your backend you would probably use your frontend’s utilities.

    Or you might have a native mobile application that communicates with your WebSocket backend directly, in native code.

    Or you might have any other way to communicate with the WebSocket endpoint.


    But for this example, we’ll use a very simple HTML document with some JavaScript, all inside a long string.

    This, of course, is not optimal and you wouldn’t use it for production.

    In production you would have one of the options above.

    But it’s the simplest way to focus on the server-side of WebSockets and have a working example:

    In your FastAPI application, create a websocket:

    1. from fastapi import FastAPI, WebSocket
    2. from fastapi.responses import HTMLResponse
    3. app = FastAPI()
    4. html = """
    5. <!DOCTYPE html>
    6. <html>
    7. <head>
    8. <title>Chat</title>
    9. </head>
    10. <body>
    11. <h1>WebSocket Chat</h1>
    12. <form action="" onsubmit="sendMessage(event)">
    13. <input type="text" id="messageText" autocomplete="off"/>
    14. <button>Send</button>
    15. </form>
    16. <ul id='messages'>
    17. </ul>
    18. <script>
    19. var ws = new WebSocket("ws://localhost:8000/ws");
    20. ws.onmessage = function(event) {
    21. var messages = document.getElementById('messages')
    22. var message = document.createElement('li')
    23. var content = document.createTextNode(event.data)
    24. message.appendChild(content)
    25. messages.appendChild(message)
    26. };
    27. function sendMessage(event) {
    28. var input = document.getElementById("messageText")
    29. ws.send(input.value)
    30. input.value = ''
    31. event.preventDefault()
    32. }
    33. </script>
    34. </body>
    35. </html>
    36. """
    37. @app.get("/")
    38. async def get():
    39. @app.websocket("/ws")
    40. async def websocket_endpoint(websocket: WebSocket):
    41. while True:
    42. data = await websocket.receive_text()
    43. await websocket.send_text(f"Message text was: {data}")

    Technical Details

    You could also use from starlette.websockets import WebSocket.

    FastAPI provides the same WebSocket directly just as a convenience for you, the developer. But it comes directly from Starlette.

    Await for messages and send messages

    You can receive and send binary, text, and JSON data.

    If your file is named main.py, run your application with:

    WebSockets - 图2

    Open your browser at http://127.0.0.1:8000.

    You will see a simple page like:

    You can type messages in the input box, and send them:

    WebSockets - 图4

    And your FastAPI application with WebSockets will respond back:

    You can send (and receive) many messages:

    WebSockets - 图6

    And all of them will use the same WebSocket connection.

    Using Depends and others

    In WebSocket endpoints you can import from fastapi and use:

    • Depends
    • Security
    • Cookie
    • Header
    • Path
    • Query

    They work the same way as for other FastAPI endpoints/path operations:

    1. from typing import Union
    2. from fastapi import Cookie, Depends, FastAPI, Query, WebSocket, status
    3. from fastapi.responses import HTMLResponse
    4. app = FastAPI()
    5. html = """
    6. <!DOCTYPE html>
    7. <html>
    8. <head>
    9. <title>Chat</title>
    10. </head>
    11. <body>
    12. <h1>WebSocket Chat</h1>
    13. <form action="" onsubmit="sendMessage(event)">
    14. <label>Item ID: <input type="text" id="itemId" autocomplete="off" value="foo"/></label>
    15. <label>Token: <input type="text" id="token" autocomplete="off" value="some-key-token"/></label>
    16. <button onclick="connect(event)">Connect</button>
    17. <hr>
    18. <label>Message: <input type="text" id="messageText" autocomplete="off"/></label>
    19. <button>Send</button>
    20. </form>
    21. <ul id='messages'>
    22. </ul>
    23. <script>
    24. var ws = null;
    25. function connect(event) {
    26. var itemId = document.getElementById("itemId")
    27. var token = document.getElementById("token")
    28. ws = new WebSocket("ws://localhost:8000/items/" + itemId.value + "/ws?token=" + token.value);
    29. ws.onmessage = function(event) {
    30. var messages = document.getElementById('messages')
    31. var message = document.createElement('li')
    32. var content = document.createTextNode(event.data)
    33. message.appendChild(content)
    34. messages.appendChild(message)
    35. };
    36. }
    37. function sendMessage(event) {
    38. var input = document.getElementById("messageText")
    39. ws.send(input.value)
    40. input.value = ''
    41. event.preventDefault()
    42. }
    43. </script>
    44. </body>
    45. </html>
    46. """
    47. @app.get("/")
    48. async def get():
    49. return HTMLResponse(html)
    50. async def get_cookie_or_token(
    51. websocket: WebSocket,
    52. session: Union[str, None] = Cookie(default=None),
    53. token: Union[str, None] = Query(default=None),
    54. ):
    55. if session is None and token is None:
    56. await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
    57. return session or token
    58. @app.websocket("/items/{item_id}/ws")
    59. async def websocket_endpoint(
    60. websocket: WebSocket,
    61. item_id: str,
    62. q: Union[int, None] = None,
    63. cookie_or_token: str = Depends(get_cookie_or_token),
    64. ):
    65. await websocket.accept()
    66. while True:
    67. data = await websocket.receive_text()
    68. await websocket.send_text(
    69. f"Session cookie or query token value is: {cookie_or_token}"
    70. )
    71. if q is not None:
    72. await websocket.send_text(f"Query parameter q is: {q}")
    73. await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")

    Info

    In a WebSocket it doesn’t really make sense to raise an HTTPException. So it’s better to close the WebSocket connection directly.

    In the future, there will be a WebSocketException that you will be able to raise from anywhere, and add exception handlers for it. It depends on the PR #527 in Starlette.

    Try the WebSockets with dependencies

    If your file is named main.py, run your application with:

    Open your browser at http://127.0.0.1:8000.

    There you can set:

    • The “Item ID”, used in the path.
    • The “Token” used as a query parameter.

    Tip

    Notice that the query token will be handled by a dependency.

    With that you can connect the WebSocket and then send and receive messages:

    WebSockets - 图8

    When a WebSocket connection is closed, the await websocket.receive_text() will raise a WebSocketDisconnect exception, which you can then catch and handle like in this example.

    To try it out:

    • Open the app with several browser tabs.
    • Write messages from them.
    • Then close one of the tabs.

    That will raise the WebSocketDisconnect exception, and all the other clients will receive a message like:

    1. Client #1596980209979 left the chat

    Tip

    The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections.

    But have in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process.

    If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster.

    More info

    To learn more about the options, check Starlette’s documentation for: