DEV Community

Free Python Code
Free Python Code

Posted on

How to use WebSocket in FastAPI and Python

Hi πŸ™‚πŸ–

Welcome to a new post, Today I will share with you how to use WebSocket in FastAPI and Python in an easy way.

Step 1

Import modules

from fastapi import FastAPI
from fastapi import WebSocket
from fastapi.responses import HTMLResponse
Enter fullscreen mode Exit fullscreen mode

Step 2

Create a route for the Send Messages web page.

app = FastAPI()

@app.get('/test', response_class = HTMLResponse)
def test():
    return HTMLResponse(""" 
        <!DOCTYPE html>
        <html>
            <head>
                <title>Test</title>
            </head>
            <body>
                <input type="text" placeholder="write any text" id="msg">
                <button id="btn">send</button>
                <script>

                    let ws = new WebSocket('ws://localhost:8000/ws')

                    ws.onmessage = function (event) {
                        console.log(event.data)
                    }

                    document.getElementById('btn').onclick = function () {
                        let msg = document.getElementById('msg').value
                        ws.send(msg)
                        msg = ''
                    }
                </script>
            </body>
        </html>
        """)
Enter fullscreen mode Exit fullscreen mode

Step 3

Create web socket route

@app.websocket('/ws')
async def websocket_endpoint(websocket : WebSocket):
    await websocket.accept()
    while True:
        text = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {text}")
Enter fullscreen mode Exit fullscreen mode

result

Image description

full code


from fastapi import FastAPI
from fastapi import WebSocket
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get('/test', response_class = HTMLResponse)
def test():
    return HTMLResponse(""" 
        <!DOCTYPE html>
        <html>
            <head>
                <title>Test</title>
            </head>
            <body>
                <input type="text" placeholder="write any text" id="msg">
                <button id="btn">send</button>
                <script>

                    let ws = new WebSocket('ws://localhost:8000/ws')

                    ws.onmessage = function (event) {
                        console.log(event.data)
                    }

                    document.getElementById('btn').onclick = function () {
                        let msg = document.getElementById('msg').value
                        ws.send(msg)
                        msg = ''
                    }
                </script>
            </body>
        </html>
        """)

@app.websocket('/ws')
async def websocket_endpoint(websocket : WebSocket):
    await websocket.accept()
    while True:
        text = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {text}")
Enter fullscreen mode Exit fullscreen mode

Now we're done πŸ€—

Don't forget to like and follow πŸ™‚

Support me on PayPal πŸ€—
https://www.paypal.com/paypalme/amr396

Top comments (0)