How to add values to url on python request

Viewed 163

I wanna get data from an api and I use this: requests.get("https://www.metaweather.com/api/location/woeid/2013/4/i/"). I want woeid to be a variable and i be an integer.

2 Answers

You can use Python's f-string syntax to substitute variable names for values in a string.

woeid = "2487956"
i = 12
url = f"https://www.metaweather.com/api/location/{woeid}/2013/4/{i}/"
print(url)
response = requests.get(url)

The url becomes: https://www.metaweather.com/api/location/2487956/2013/4/12/

The longer and more time consuming version of CodeMonkey's answer would be

woeid = "2487956"
i = 12
url = "https://www.metaweather.com/api/location/" + woeid + "/2013/4" + i "/"
print(url)
response = requests.get(url)

Reason why I added this is because, string interpolation isnt supported by all languages.

Related