psf / requests

A simple, yet elegant, HTTP library.

Home Page:https://requests.readthedocs.io/en/latest/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to download multiple files in local system using POST API request in python rather than in ascii or binary form data ?

dhingrachirag opened this issue · comments

I struck in one scenario in which i need to download multiple files in local repository using POST API request in python 3.9.12.

I tried below code but not able to resolve the issue.

def download(url: str, dest_folder: str):
    if not os.path.exists(dest_folder):
        os.makedirs(dest_folder)

    filename = url.split('/')[-1].replace(" ", "_")
    file_path = os.path.join(dest_folder, filename)

    payload = {'testcaseId': '305432601'}

    r = requests.post(url, data=json.dumps(payload), stream=False)
    if r.ok:
        print("saving to", os.path.abspath(file_path))
        with open(file_path, 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024 * 8):
                if chunk:
                    f.write(chunk)
                    f.flush()
                    os.fsync(f.fileno())
    else:  # HTTP status code 4XX/5XX
        print("Download failed: status code {}\n{}".format(r.status_code, r.text))


download("https://api.demo.com/siteapi/resultfiles/", dest_folder="//PycharmProjects//Testing_Local//Logs")

When I used above code it gives me below error:

Download failed: status code 500
{"timestamp":"2024-03-14T11:45:42.109+00:00","status":500,"error":"Internal Server Error","path":"/siteapi/resultfiles/"}

In postman we have that option to SEND and DOWNLOAD files and through that i am able to download multiple files in zip folder in my local system.

Screenshot 2024-03-05 at 11 51 16 AM

My questions are :

  1. How to download multiple files in local system or directory using python through POST API request rather than binary stream ?
  2. How to achieve task through python code which postman UI is providing through SEND and DOWNLOAD option ?

Below scenario is expected :

  1. Fire POST API request
  2. DOWNLOAD Files through response of POST API
  3. STORE files in local directory.

As described in the template, we won't be able to answer questions on this issue tracker. Please use Stack Overflow