Downloading a File with Python Requests

To download a file using the Python Request library, you need to make a GET, POST, or PUT request and read the server's response data using response.content, response.json, or response.raw objects, and then save it to disk using the Python file object methods. In this Python Requests Download File Example, we download a file from the ReqBin echo URL and save it to disk in binary format. Click Execute to run Python Download File example online and see the result.
Downloading a File with Python Requests Execute
import shutil
import requests

url = 'https://reqbin.com/echo/get/json'
response = requests.get(url, stream=True)

with open('sample.json', 'wb') as out_file:
  shutil.copyfileobj(response.raw, out_file)

print('The file was saved successfully')
Updated: Viewed: 16914 times

What is the Python Requests library?

The Requests Library is one of the most popular Library that makes it uncomplicated to send HTTP (POST, GET and DELETE) requests, post JSON and XML data, submit HTML forms, and upload files. The Requests Library automatically checks server SSL certificates, session cookies and supports International Domain Names. Requests Library is based on the urllib3 library and disguises the complexity of making HTTP requests behind a easy API. The Requests Library is not comprised in the Python distribution, but almost everyone uses Requests Library because the Python code for working with HTTP becomes straightforward and short.

How to use the Python Requests Library?

To install the Python Requests Library, run the following command:

Install Python Requests Library
pip install requests

After installing the Request Library, you can use it in your work:

import requests

See also