You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3.0 KiB

You can use WebSockets with FastAPI.

WebSockets client

In production

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:

{!./src/websockets/tutorial001.py!}

Create a websocket_route

In your FastAPI application, create a websocket_route:

{!./src/websockets/tutorial001.py!}

!!! tip In this example we are importing WebSocket from starlette.websockets to use it in the type declaration in the WebSocket route function.

That is not required, but it's recommended as it will provide you completion and checks inside the function.

!!! info This websocket_route we are using comes directly from Starlette.

That's why the naming convention is not the same as with other API path operations (`get`, `post`, etc).

Await for messages and send messages

In your WebSocket route you can await for messages and send messages.

{!./src/websockets/tutorial001.py!}

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

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

Test it

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

uvicorn main:app --reload

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:

And your FastAPI application with WebSockets will respond back:

You can send (and receive) many messages:

And all of them will use the same WebSocket connection.