Search code examples
pythonpython-requestsf-string

f string backslash escape


I have a request payload where i need to use a variable to get details from different products

payload = f"{\"filter\":\"1202-1795\",\"bpId\":\"\",\"hashedAgentId\":\"\",\"defaultCurrencyISO\":\"pt-PT\",\"regionId\":2001,\"tenantId\":1,\"homeRegionCurrencyUID\":48}"

i need to change the \"filter\":\"1202-1795\" to \"filter\":\"{variable}\" to populate the requests and get the info, but i'm struggling hard with the backslash in the f string

I tried to change for double to single quotes both inside the string and the opening and closing quotes, tried double {} and nothing works

this is my variable to populate the request

variable = ['1214-2291','1202-1823','1202-1795','1202-1742','1202-1719','1214-2000','1202-1198','1202-1090']

Solution

  • Create a dict, loop over items in the list, set filter key, make the request.

    import requests
    payload = {"bpId":"",
               "hashedAgentId":"",
               "defaultCurrencyISO":"pt-PT",
               "regionId":2001,
               "tenantId":1,
               "homeRegionCurrencyUID":48}
    
    items = ['1214-2291','1202-1823','1202-1795','1202-1742','1202-1719','1214-2000','1202-1198','1202-1090']
    for item  in items:
        payload['filter'] = item
        response = requests.get(url, json=payload)
    

    You can check the difference between data and json parameters in python requests package