1

I need to design an API in FastAPI and I am struggling to find the best way to do it.

What I need is to record a video streaming. Here is the workflow:

  1. User send signal to start video recording (/{camera}/start) on camera XYZ. API returns message "video recording started for camera YXZ"
  2. do whatever
  3. User send signal to stop video recording (/{camera}/stop) on camera XYZ. API returns the mp4 file of the recording.

Right now, I am using a background task to perform the video capture and a flag in the database to check if the video recording for device XYZ should continue or not. If not, the video recording is stopped, the mp4 file is saved and returned as a response for (/{camera}/stop)

Is there a more elegant way to do it? For example: avoiding using a database to store the should_continue flag, status and filename?

Chris
  • 18,724
  • 6
  • 46
  • 80
guilhermecgs
  • 2,913
  • 11
  • 39
  • 69
  • You could use `websockets` instead. See relevant posts [here](https://stackoverflow.com/a/71738644/17865804), [here](https://stackoverflow.com/a/70996841/17865804) and [here](https://stackoverflow.com/a/72070914/17865804). You may also want to have a look at [this](https://stackoverflow.com/a/70626324/17865804), as well as [this](https://stackoverflow.com/a/71871482/17865804) and [this](https://stackoverflow.com/a/71545097/17865804). – Chris Nov 08 '22 at 19:40

1 Answers1

1

If your case is as simple you described there is no need to overengineer. But I personally like the apscheduler, it has simple setup with FastAPI asyncio loop and allow you to control runned job.

from apscheduler.schedulers.asyncio import AsyncIOScheduler

sched = AsyncIOScheduler()
sched.start()

And then in endpoint

def start():
    sched.add_job(start_recording, "date", run_date=datetime.now(), args=[], id=<unique_id>)
    # to stop: sched.remove_job(<unique_id>)
kosciej16
  • 6,294
  • 1
  • 18
  • 29
  • this solution looks really interesting... From what I understood, it is a "background task" from FastAPI with steroids -> a job store and the hability to pause. Thanks – guilhermecgs Nov 09 '22 at 00:24