Home > other >  Add a variable to a link to make an Api call Python
Add a variable to a link to make an Api call Python

Time:11-10

I want to put the id in the link because I want to make an api call

id= 156
url1 = 'https://comtrade.un.org/api/get?r='<id>'&px=HS&ps=2020&p=0&rg=1&cc=total'

response1 = requests.get(url1)


print(response1.url)

CodePudding user response:

You have a lot of options here, if you want to add a lot of variables to the url or want your code to look clean, I suggest using an f-string as shown below:

url1 = f'https://comtrade.un.org/api/get?r={id}&px=HS&ps=2020&p=0&rg=1&cc=total'

This way you can put any variable in your string with just saying {variable}.

Don't forget to put the f before the quotes.

CodePudding user response:

Python 3 I would suggest the f"string" method as people wrote above me.

I personally like the format as it works for both 3 and 2

url1 = 'https://comtrade.un.org/api/get?r={0}&px=HS&ps=2020&p=0&rg=1&cc=total'.format(id)
  • Related