Aaron Nelson
Aaron Nelson

Reputation: 191

How to make multiple API calls from multiple pages in single URL

So the title is a little confusing I guess..

I have a script that I've been writing that will display some random data and other non-essentials when I open my shell. I'm using grequests to make my API calls since I'm using more than one URL. For my weather data, I use WeatherUnderground's API since it will offer active alerts. The alerts and conditions data are on separate pages. What I can't figure out is how to insert the appropriate name in the grequests object when it is making requests. Here is the code that I have:

URLS = ['http://api.wunderground.com/api/'+api_id+'/conditions/q/autoip.json',
        'http://www.ourmanna.com/verses/api/get/?format=json',
        'http://quotes.rest/qod.json',
        'http://httpbin.org/ip']

requests = (grequests.get(url) for url in URLS)
responses = grequests.map(requests)
data = [response.json() for response in responses]

#json parsing from here

In the URL 'http://api.wunderground.com/api/'+api_id+'/conditions/q/autoip.json' I need to make an API request to conditions and alerts to retrieve the data I need. How do I do this without rewriting a fourth URLS string?

I've tried

pages = ['conditions', 'alerts']
URL = ['http://api.wunderground.com/api/'+api_id+([p for p in pages])/q/autoip.json']

but, as I'm sure some of you more seasoned programmers know, threw and exception. So how can I iterate through these pages, or will I have to write out both complete URLS?

Thanks!

Upvotes: 0

Views: 2606

Answers (1)

Aaron Nelson
Aaron Nelson

Reputation: 191

Ok I was actually able to figure out how to call each individual page within the grequests object by using a simple for loop. Here is the the code that I used to produced the expected results:

import grequests

pages = ['conditions', 'alerts']
api_id = 'myapikeyhere' 

for p in pages:
    URLS = ['http://api.wunderground.com/api/'+api_id+'/'+p+'/q/autoip.json',
            'http://www.ourmanna.com/verses/api/get/?format=json',
            'http://quotes.rest/qod.json',
            'http://httpbin.org/ip']

    #create grequest object and retrieve results
    requests = (grequests.get(url) for url in URLS)
    responses = grequests.map(requests)
    data = [response.json() for response in responses]

    #json parsing from here

I'm still not sure why I couldn't figure this out before.

Documentation for the grequests library here

Upvotes: 1

Related Questions