druuu
druuu

Reputation: 1716

Writing code using graph APIs

I am extremely new to python , scripting and APIs, well I am just learning. I came across a very cool code which uses facebook api to reply for birthday wishes.

I will add my questions, I will number it so that it will be easier for someone else later too. I hope this question will clear lots of newbies doubts.

1) Talking about APIs, in what format are the usually in? is it a library file which we need to dowload and later import? for instance, twitter API, we need to import twitter ?

Here is the code :

import requests
import json

AFTER = 1353233754
TOKEN = ' <insert token here> '

def get_posts():
    """Returns dictionary of id, first names of people who posted on my wall

    between start and end time"""

    query = ("SELECT post_id, actor_id, message FROM stream WHERE "
             "filter_key = 'others' AND source_id = me() AND "
             "created_time > 1353233754 LIMIT 200")

    payload = {'q': query, 'access_token': TOKEN}
    r = requests.get('https://graph.facebook.com/fql', params=payload)
    result = json.loads(r.text)
    return result['data']

def commentall(wallposts):
    """Comments thank you on all posts"""
    #TODO convert to batch request later

    for wallpost in wallposts:
        r = requests.get('https://graph.facebook.com/%s' %
                         wallpost['actor_id'])

        url = 'https://graph.facebook.com/%s/comments' % wallpost['post_id']
        user = json.loads(r.text)
        message = 'Thanks %s :)' % user['first_name']
        payload = {'access_token': TOKEN, 'message': message}

        s = requests.post(url, data=payload)
        print "Wall post %s done" % wallpost['post_id']

if __name__ == '__main__':
     commentall(get_posts())`

Questions:

  1. importing json--> why is json imported here? to give a structured reply?
  2. What is the 'AFTER' and the empty variable 'TOKEN' here?
  3. what is the variable 'query' and 'payload' inside get_post() function? Precisely explain almost what each methods and functions do.

I know I am extremely naive, but this could be a good start. A little hint, I can carry on. If not going to explain the code, which is pretty boring, I understand, please tell me how to link to APIs after a code is written, meaning how does a script written communicate with the desired API.

This is not my code, I copied it from a source.

Upvotes: 1

Views: 537

Answers (1)

Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26637

  1. json is needed to access the web service and interpret the data that is sent via HTTP.
  2. The 'AFTER' variable is supposed to get used to assume all posts after this certain timestamp are birthday wishes.
  3. To make the program work, you need a token which you can obtain from Graph API Explorer with the appropriate permissions.

Upvotes: 2

Related Questions