Search code examples
pythonhttphyperlinkstring-formatting

Add a variable to a link to make an Api call Python


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)

Solution

  • 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.