Better Programming

Advice for programmers.

Follow publication

Member-only story

How To Download Streaming Responses as a File in Python

Ng Wai Foong
Better Programming
Published in
3 min readJun 11, 2021

--

App icons
Photo by Alexander Shatov on Unsplash.

Most of the time, a streaming response is the preferred choice when returning audio or video files from a server. This is mainly because streaming responses work really well for large files — especially those that exceed 1GB in file size.

In this tutorial, you will learn to:

  • Create a simple FastAPI server that returns an audio file via StreamingResponse.
  • Create a simple Python script to call the FastAPI server and save the response as a file directly to disk.

Let’s proceed to the next section and start installing the necessary modules.

Setup

It is highly recommended to create a virtual environment before you continue with the setup.

FastAPI

Activate the virtual environment and run the following command to install FastAPI:

pip install fastapi

Uvicorn

You will need an ASGI server in order to serve FastAPI. The recommended choice is Uvicorn. You can choose to install the standard version via:

pip install uvicorn[standard]

Or the minimal version as follows:

pip install uvicorn

Requests

To keep it simple and short, the requests package will be used to call the FastAPI server. Please note that requests is based on blocking I/O. Hence, it will block the content property until the entire response has been downloaded. If you are looking for non-blocking-I/O packages, consider using asyncio instead. Run the following command to install it:

pip install requests

Implementation

In this section, you will implement:

  • A FastAPI server.
  • A Python script.

FastAPI server

Create a new Python file called server.py and append the following code inside it:

--

--

Ng Wai Foong
Ng Wai Foong

Written by Ng Wai Foong

Senior AI Engineer@Yoozoo | Content Writer #NLP #datascience #programming #machinelearning | Linkedin: https://www.linkedin.com/in/wai-foong-ng-694619185/

Responses (1)

Write a response