Using download_file_from_server_endpoint to download a file from a HTTP server endpoint via HTTP GETĪfter we had defined the download_file_from_server_endpoint function, we can then use it to download a file from a HTTP server endpoint via HTTP GET. Inside the with statement, data is read from the HTTP response in 128-byte chunks and written to local_file.
When the status code in the HTTP response is a 200 OK, a file handler is created to write binary data to the path specified by local_file_path. After the function is called, it first uses requests.get to get a Response object.
With open(local_file_path, 'wb') as local_file:įor chunk in er_content(chunk_size=128):Īs shown above, the download_file_from_server_endpoint function expects a server endpoint and a local file path as input.
# Write the file contents in the response to a file specified by local_file_path # Send HTTP GET request to server and attempt to receive a response Given these points, we can create a Python 3 function that downloads a file from a HTTP server endpoint via HTTP GET:ĭef download_file_from_server_endpoint(server_endpoint, local_file_path): Python 3 function that downloads a file from a HTTP server endpoint via HTTP GET
Previously, we discussed how to upload a file and some data through HTTP multipart in Python 3 using the requests library. When you are building a HTTP client with Python 3, you could be coding it to upload a file to a HTTP server or download a file from a HTTP server. How to download a file via HTTP POST and HTTP GET with Python 3 requests library