简体   繁体   中英

How can I use list values to format an API payload request string?

I'm trying to make multiple look-ups using an API using a list in order to create a dictionary that I can then manipulate a dataframe with. I am currently using ({}.format(i)), which runs, however I receive a warning from the API that there is an invalid format for the required field.

When I test the code by hand typing one of the list values in place of ({}.format(i)), it works, so I 'm fairly sure it's related to using ({}.format(i)), however, not sure of another way to do this.

I've included an example of the code below. Is it the " being escaped by the backslash? Thanks for any help!

list_string = ['XXXXXX','YYYYYY','ZZZZZZ']

for i in list_string
    url = "https://fakeurl.api.co.uk/enquiry"
    payload = "{\n\t\"identification1\": \"({}.format(i))\"\n}" # Works when ({}.format(i)) replaced with XXXXXX
    headers = {
      'x-api-key': 'INSERT KEY HERE',
      'Content-Type': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data = payload)
    response = response.json()
    response

The format call needs to be added at the end of the string, like the following. Also, list is a reserved word in Python, please use a different one. And, you need to escape the outer curly braces.

EDIT: Removed brackets after adding additional curly braces.

list_string = ['XXXXXX','YYYYYY','ZZZZZZ']

for i in list_string:
    url = "https://fakeurl.api.co.uk/enquiry"
    payload = "{{\n\t\"identification1\": \"{}\"\n}}".format(i)
    headers = {
      'x-api-key': 'INSERT KEY HERE',
      'Content-Type': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data = payload)
    response = response.json()
    response

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