{"id":1372,"date":"2018-11-14T17:50:53","date_gmt":"2018-11-14T09:50:53","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=1372"},"modified":"2018-11-17T22:31:29","modified_gmt":"2018-11-17T14:31:29","slug":"how-to-download-a-file-via-http-post-and-http-get-with-python-3-requests-library","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-download-a-file-via-http-post-and-http-get-with-python-3-requests-library\/","title":{"rendered":"How to download a file via HTTP POST and HTTP GET with Python 3 requests library"},"content":{"rendered":"<p>When you are building a <a href=\"https:\/\/www.techcoil.com\/glossary\/http-client\/\" rel=\"noopener\" target=\"_blank\">HTTP client<\/a> with Python 3, you could be coding it to <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-upload-a-file-and-some-data-through-http-multipart-in-python-3-using-the-requests-library\/\" rel=\"noopener\" target=\"_blank\">upload a file to a HTTP server<\/a> or download a file from a HTTP server. <\/p>\n<p>Previously, we discussed <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-upload-a-file-and-some-data-through-http-multipart-in-python-3-using-the-requests-library\/\" rel=\"noopener\" target=\"_blank\">how to upload a file and some data through HTTP multipart in Python 3 using the requests library<\/a>. In this post, let's see how we can download a file via HTTP POST and HTTP GET.<\/p>\n<h2>Downloading a file from a HTTP server endpoint via HTTP GET<\/h2>\n<p>Generally, downloading a file from a <a href=\"https:\/\/www.techcoil.com\/glossary\/http-server\/\" rel=\"noopener\" target=\"_blank\">HTTP server<\/a> endpoint via HTTP GET consists of the following steps:<\/p>\n<ol>\n<li>Construct the HTTP GET request to send to the HTTP server.<\/li>\n<li>Send the <a href=\"https:\/\/www.techcoil.com\/glossary\/http-request\/\" rel=\"noopener\" target=\"_blank\">HTTP request<\/a> and receive the <a href=\"https:\/\/www.techcoil.com\/glossary\/http-response\/\" rel=\"noopener\" target=\"_blank\">HTTP Response<\/a> from the HTTP server.<\/li>\n<li>Save the contents of the file from HTTP Response to a local file.<\/li>\n<\/ol>\n<h3>Python 3 function that downloads a file from a HTTP server endpoint via HTTP GET<\/h3>\n<p>Given these points, we can create a Python 3 function that downloads a file from a HTTP server endpoint via HTTP GET:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport requests\r\n\r\ndef download_file_from_server_endpoint(server_endpoint, local_file_path):\r\n\r\n    # Send HTTP GET request to server and attempt to receive a response\r\n    response = requests.get(server_endpoint)\r\n    \r\n    # If the HTTP GET request can be served\r\n    if response.status_code == 200:\r\n        \r\n        # Write the file contents in the response to a file specified by local_file_path\r\n        with open(local_file_path, 'wb') as local_file:\r\n            for chunk in response.iter_content(chunk_size=128):\r\n                local_file.write(chunk)\r\n<\/pre>\n<p>As shown above, the <code>download_file_from_server_endpoint<\/code> function expects a server endpoint and a local file path as input. After the function is called, it first uses <a href=\"http:\/\/docs.python-requests.org\/en\/master\/api\/#requests.get\" rel=\"noopener\" target=\"_blank\">requests.get<\/a> to get a <a href=\"http:\/\/docs.python-requests.org\/en\/master\/api\/#requests.Response\" rel=\"noopener\" target=\"_blank\">Response<\/a> object. <\/p>\n<p>When the status code in the HTTP response is a <strong>200 OK<\/strong>, a file handler is created to write binary data to the path specified by <code>local_file_path<\/code>. <\/p>\n<p>Inside the <code>with<\/code> statement, data is read from the HTTP response in <strong>128-byte<\/strong> chunks and written to <code>local_file<\/code>.<\/p>\n<h3>Using <code>download_file_from_server_endpoint<\/code> to download a file from a HTTP server endpoint via HTTP GET<\/h3>\n<p>After we had defined the <code>download_file_from_server_endpoint<\/code> function, we can then use it to download a file from a HTTP server endpoint via HTTP GET. For example, if we want to download Techcoil's logo, we can call the <code>download_file_from_server_endpoint<\/code> function as follows:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndownload_file_from_server_endpoint('https:\/\/www.techcoil.com\/ph\/img\/logo.png', 'logo.png')\r\n<\/pre>\n<p>After the function call completes, you should find Techcoil's logo in the same directory as the Python script if your computer is connected to the Internet.<\/p>\n<h2>Downloading a file HTTP from a HTTP server endpoint via HTTP POST<\/h2>\n<p>There could be cases where the client need to supply some information to the HTTP server in order to download a file. In such a situation, HTTP POST is a more appropriate HTTP method to use for downloading the file. <\/p>\n<p>As with HTTP GET, downloading of a file from the HTTP server via HTTP POST consists of the following steps:<\/p>\n<ol>\n<li>Construct the HTTP POST request to send to the HTTP server.<\/li>\n<li>Send the HTTP request and receive the HTTP Response from the HTTP server.<\/li>\n<li>Save the contents of the file from HTTP Response to a local file.<\/li>\n<\/ol>\n<h3>Python 3 function that downloads a file from a HTTP server endpoint via HTTP POST<\/h3>\n<p>Given these points, we can create a Python 3 function that downloads a file from a HTTP server endpoint via HTTP POST:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef download_file_from_server_endpoint(server_endpoint, local_file_path, data_dict):\r\n\r\n    # Send HTTP GET request to server and attempt to receive a response\r\n    response = requests.post(url=server_endpoint, data=data_dict)\r\n\r\n    # If the HTTP GET request can be served\r\n    if response.status_code == 200:\r\n\r\n        # Write the file contents in the response to a file specified by local_file_path\r\n        with open(local_file_path, 'wb') as local_file:\r\n            for chunk in response.iter_content(chunk_size=128):\r\n                local_file.write(chunk)\r\n\r\n<\/pre>\n<p>As shown above, the <code>download_file_from_server_endpoint<\/code> function now accepts a server endpoint, a local file path, and a data dictionary.<\/p>\n<p>In this case, we had used <a href=\"http:\/\/docs.python-requests.org\/en\/master\/api\/#requests.post\" rel=\"noopener\" target=\"_blank\"><code>requests.post<\/code><\/a> instead of <a href=\"http:\/\/docs.python-requests.org\/en\/master\/api\/#requests.get\" rel=\"noopener\" target=\"_blank\"><code>requests.get<\/code><\/a> to get a <a href=\"http:\/\/docs.python-requests.org\/en\/master\/api\/#requests.Response\" rel=\"noopener\" target=\"_blank\">Response<\/a>  object. In addition, we had supplied server_endpoint as the url and data_dict as the POST variables for <code>requests.post<\/code> to construct and send the HTTP request to the server for a HTTP response.<\/p>\n<p>After we had gotten the <code>Response<\/code> object, we save the file contents in the response just like the function that downloads the file via HTTP GET.  <\/p>\n<h3>Using <code>download_file_from_server_endpoint<\/code> to download a file from a HTTP server endpoint via HTTP POST<\/h3>\n<p>In order to visualise how <code>download_file_from_server_endpoint<\/code> works, we can reuse the server backend from the <a href=\"https:\/\/techcoil.com\/proof-of-concepts\/using-jquery-to-push-a-dynamically-generated-file-to-web-browser\" rel=\"noopener\" target=\"_blank\">proof of concept that we can use jQuery to push a dynamically generated file to the web browser based on the user's input<\/a>.<\/p>\n<p>Given that, we can create the following Python 3 code to use <code>download_file_from_server_endpoint<\/code> to download a file from a HTTP server endpoint via HTTP POST:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndownload_file_from_server_endpoint('https:\/\/www.techcoil.com\/process\/proof-of-concepts\/userNameAndLuckyNumberTextFileGeneration'\r\n                                   , 'number.txt', {'visitorName': 'John Doe', 'luckyNumber': 1234})\r\n<\/pre>\n<p>After the function call completes, you should find <code>number.txt<\/code> in the same directory as the python script if your computer is connected to the Internet. In addition, number.txt should contain the following content:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nHi John Doe. \r\nYou have drawn the number 1234.\r\n<\/pre>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-m8\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-m8&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-m8&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F1372&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>When you are building a <a href=\"https:\/\/www.techcoil.com\/glossary\/http-client\/\" rel=\"noopener\" target=\"_blank\">HTTP client<\/a> with Python 3, you could be coding it to <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-upload-a-file-and-some-data-through-http-multipart-in-python-3-using-the-requests-library\/\" rel=\"noopener\" target=\"_blank\">upload a file to a HTTP server<\/a> or download a file from a HTTP server. <\/p>\n<p>Previously, we discussed <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-upload-a-file-and-some-data-through-http-multipart-in-python-3-using-the-requests-library\/\" rel=\"noopener\" target=\"_blank\">how to upload a file and some data through HTTP multipart in Python 3 using the requests library<\/a>. In this post, let&#8217;s see how we can download a file via HTTP POST and HTTP GET.<\/p>\n","protected":false},"author":1,"featured_media":1244,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[23,199,161,226,233,551],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Python-Logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-m8","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1372"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=1372"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1372\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1244"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=1372"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=1372"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=1372"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}