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
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>
""")
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}")
result
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}")
Now we're done 🤗
Don't forget to like and follow 🙂
Support me on PayPal 🤗
https://www.paypal.com/paypalme/amr396
Top comments (0)