Python (Scripting) - Download File using requests

by
Jeremy Canfield |
Updated: April 01 2024
| Python (Scripting) articles
There are a couple ways to go about downloading a file.
- using requests (this article)
- using paramiko Secure Copy Protocol (SCP)
- using urllib
requests can be used to download a file. Use the pip list command to determine if the requests package is installed.
~]$ pip list
Package Version
------------------- ---------
requests 2.31.0
If the requests package is not listed, use the pip install command to install the requests package.
pip install requests
Here is the minimal boilterplate code without error handling to download a file using requests using requests.
#!/usr/bin/python3
import requests
requests.get(
"https://api.example.com/api/v1/example.txt",
headers={ "Authorization": "Token abc123" }
)
Here is a more practical example, with try/except/else error handling. This basically uses requests to return the content of the file and then creates a file with the same content.
#!/usr/bin/python3
import requests
try:
response = requests.get(
"https://api.example.com/api/v1/example.txt",
headers={ "Authorization": "Token abc123" }
)
except Exception as exception:
print(f"got the following exception: {exception}")
else:
with open("/tmp/example.txt", "w") as file:
file.write(response.text)
Did you find this article helpful?
If so, consider buying me a coffee over at