'How can I POST data in real time using FastAPI?

I built a simple demo project using FastAPI. I would like to POST data to the server in real time (maybe 30fps).

# in client
while True:
    ....
    res = requests.post(URL, files={'input_data' : input_data})
    ....

But, I get the following error:

(MaxRetryError: HTTPConnectionPool(host='~~', port=8000): Max retries exceeded with url)

I think it is caused due to the multiple requests, but I would like to perform requests in real time. How can I do? Thanks in advance.



Solution 1:[1]

As noted by @MatsLindh in the comments, you should rather use a more suitable protocol - such as WebSockets - than HTTP for such a task. FastAPI/Starlette supports sending and receiving data on a websocket (see the documentation here and here). Below is an example of using websockets to send video frames from a client to a server (assuming this is your task from your comment on 30fps - however, the same appproach could be applied to sending other types of data). OpenCV is used to capture the frames and websockets library is used to connect to the WebSocket server.

server.py

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
import cv2
import numpy as np

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    # listen for connections
    await websocket.accept()
    #count = 1
    try:
        while True:
            contents = await websocket.receive_bytes()
            arr = np.frombuffer(contents, np.uint8)
            frame = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED)
            cv2.imshow('frame', frame)
            cv2.waitKey(1)
            #cv2.imwrite("frame%d.png" % count, frame)
            #count += 1
    except WebSocketDisconnect:
        cv2.destroyWindow("frame")
        print("Client disconnected") 

client.py

import websockets
import asyncio
import cv2

camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)

async def main():
    # Connect to the server
    async with websockets.connect('ws://localhost:8000/ws') as ws:
         while True:
            success, frame = camera.read()
            if not success:
                break
            else:
                ret, buffer = cv2.imencode('.png', frame)
                await ws.send(buffer.tobytes())

# Start the connection
asyncio.run(main())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1