How do I download a file using 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 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 use the "shutil" module to save the content of a GET request to a file in binary format, but you can use any other module to work with files (the "shutil" module makes it easier to work with files). Click Execute to run Python Download File Example online and see the result.
How do I download a file using 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: 2728 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