Erich Purpur
Erich Purpur

Reputation: 1509

Insert values into API request dynamically?

I have an API request I'm writing to query OpenWeatherMap's API to get weather data. I am using a city_id number to submit a request for a unique place in the world. A successful API query looks like this:

    r = requests.get('http://api.openweathermap.org/data/2.5/group?APPID=333de4e909a5ffe9bfa46f0f89cad105&id=4456703&units=imperial')

The key part of this is 4456703, which is a unique city_ID

I want the user to choose a few cities, which then I'll look through a JSON file for the city_ID, then supply the city_ID to the API request.

I can add multiple city_ID's by hard coding. I can also add city_IDs as variables. But what I can't figure out is if users choose a random number of cities (could be up to 20), how can I insert this into the API request. I've tried adding lists and tuples via several iterations of something like...

#assume the user already chose 3 cities, city_ids are below
city_ids = [763942, 539671, 334596]

r = requests.get(f'http://api.openweathermap.org/data/2.5/groupAPPID=333de4e909a5ffe9bfa46f0f89cad105&id={city_ids}&units=imperial')

Maybe a list is not the right data type to use?

Successful code would look something like...

r = requests.get(f'http://api.openweathermap.org/data/2.5/group?APPID=333de4e909a5ffe9bfa46f0f89cad105&id={city_id1},{city_id2},{city_id3}&units=imperial')

Except, as I stated previously, the user could choose 3 cities or 10 so that part would have to be updated dynamically.

Upvotes: 1

Views: 570

Answers (1)

gstbeing
gstbeing

Reputation: 51

you can use some string methods and list comprehensions to append all the variables of a list to single string and format that to the API string as following:

city_ids_list = [763942, 539671, 334596]
city_ids_string = ','.join([str(city) for city in city_ids_list]) # Would output "763942,539671,334596"
r = requests.get('http://api.openweathermap.org/data/2.5/group?APPID=333de4e909a5ffe9bfa46f0f89cad105&id={city_ids}&units=imperial'.format(city_ids=city_ids_string))

hope it helps, good luck

Upvotes: 2

Related Questions