I'm using Python 3.8
I have a variable api_url
that represents an API URL I extracted from a database. The URL can change depending on how I query the database.
api_url = https://system.company.com/API?%40asset={asset}
I now want to make an API get request using the api_url
which contains an {asset}
variable.
import requests
asset = "BuildingA"
requests.get(f"{api_url}", headers=headers)
But I'm pretty sure it's not working because the API call is returning a blank response. I'm assuming that the f string is not seeing {asset}
as a variable.
Hence, my question is how do I use a variable {asset}
within a variable {api_url}
in a requests.get() function?
You cannot chain f-strings.
So either:
api_url = 'https://system.company.com/API'
requests.get(f"{api_url}?asset={asset}")
or
api_url = 'https://system.company.com/API'
requests.get(api_url, params={'asset': asset})
If you really want to have a predefined string that has variables, you can use format:
asset_url = 'https://system.company.com/API?asset={asset}'
requests.get(asset_url.format(asset=asset))