0

I'm trying to iterate over a list of emails when calling an API endpoint using the requests library but when iterating over and trying to use an f-string I cannot escape backslash. Here's my code:

import requests
import json

file = '/usr/datas.json'
with open(file, 'r') as f:
    emails = json.load(f)

for email in emails:
    resp = requests.post(f'https://api.com/public/generic/v3/Load?readData={\"lib\":\"200\",\"debug\":\"false\",\"develfield\":{\"field\":[\"id\",\"suffix\",\"m\"]},\"primaryKey\":{\"mail\":\"{email}\"},\"fieldList\":{\"field\":[\"uid\",\"mail\",\"postalCode\",\"location\",\"phone\",\"fax\",\"l\",\"m\"]}}&responsetype=json', headers=custom_header, verify=False)
    resp.raise_for_status()
    account_data = resp.json()

I've tried to reference the {email} variable in my string but getting the f-string expression part cannot include a backslash error message.

I've tried escaping my backslash multiple ways like creating a backslash variable and reference that in my f-string but no luck. Is there any way to reference a variable when doing a loop without the use of an f-string?

Thanks!

vboxer00
  • 125
  • 2
  • 11
  • 2
    It's because you can't use escaping in f-literals: [here](https://mail.python.org/pipermail/python-ideas/2016-August/041727.html) and [here](https://mail.python.org/pipermail/python-dev/2016-August/145979.html) – S.B Jan 29 '22 at 18:50

1 Answers1

1

You actually need to escape the curly braces in f-strings, not quotes

You need to double the {{ and }} [to escape them]

import requests
import json

file = '/usr/datas.json'
with open(file, 'r') as f:
    emails = json.load(f)

for email in emails:
    resp = requests.post(f'https://api.com/public/generic/v3/Load?readData={{"lib":"200","debug":"false","develfield":{{"field":["id","suffix","m"]}},"primaryKey":{{"mail":"{email}"}},"fieldList":{{"field":["uid","mail","postalCode","location","phone","fax","l","m"]}}}}&responsetype=json', headers=custom_header, verify=False)
    resp.raise_for_status()
    account_data = resp.json()

Also, consider to build the readData param with dict and json.dumps for better readability

import requests
import json

file = '/usr/datas.json'
with open(file, 'r') as f:
    emails = json.load(f)

for email in emails:
    data = {
        "lib": "200",
        "debug": "false",
        "develfield": {
            "field": ["id", "suffix", "m"]
        },
        "primaryKey": {"mail": email},
        "fieldList": {
            "field": ["uid", "mail", "postalCode", "location", "phone", "fax", "l", "m"]
        }
    }
    str_data = json.dumps(data)
    resp = requests.post(
        f'https://api.com/public/generic/v3/Load?readData={str_data}&responsetype=json',
        headers=custom_header, verify=False)
    resp.raise_for_status()
    account_data = resp.json()
Yevhen Bondar
  • 4,357
  • 1
  • 11
  • 31