Home > OS >  how to requests.get() a variable within a variable
how to requests.get() a variable within a variable

Time:09-28

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?@asset={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?

CodePudding user response:

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))

CodePudding user response:

I think if api_url is f-string this might recognize asset as a variable.

asset = 'BuildingA'
api_url = f'https://system.company.com/API?@asset={asset}'
  • Related