简体   繁体   中英

How to get the updated file back that posted to an api in python

I need to send a.xml file to an API and in return the API will return the same file with some updations. How to get the file from the API in python?

I can able to send the file but stuck at getting the updated file back.

import requests
import json
CLIENT_ID = "abcd"
CLIENT_SECRET = "ab342d"

grant_type = 'client_credentials'
body_params = {'grant_type' : grant_type}
# Getting the auth token
url='https://www.example.com/token'
response = requests.post(url, data=body_params, auth = (CLIENT_ID, CLIENT_SECRET)) 
token_raw = json.loads(response.text)
token = token_raw["access_token"]

headers = {"Authorization": "Bearer {}".format(token)}
url="https://some.api.abc.com"

# Posting the file 

req = {'file': open('report.xml', 'rb')}
res = requests.post(url, files=req, headers=headers)

# How to get the updated file from API

Any hints is highly appreciated, many thanks!

You can do something like this:

test.py:

from requests import Session

URL = "https://httpbin.org/xml"


def main():
    with Session() as s, open("test.xml", "w") as f:
        r = s.get(URL)
        f.write(r.text)


if __name__ == "__main__":
    main()

Test:

$ python test.py
$ file test.xml 
test.xml: XML 1.0 document text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM