Introduction to Facebook JavaScript & Python SDK

Post on 12-Sep-2014

1.490 views 1 download

Tags:

description

This is a workshop for teaching people building Facebook app with its JavaScript & Python SDK, and also included a code lab to let people do it in real

Transcript of Introduction to Facebook JavaScript & Python SDK

facebook JavaScript SDK

Introduction to

facebook JavaScript SDK!

Tutorials & Code Lab, 2013 Winter Colin Su Social Network Application

facebook JavaScript SDKhttp://goo.gl/MwcsRA

facebook JavaScript SDK

Colin Su

> littleq0903+sna@gmail.com

> Software Engineer @ Tagtoo

> National Chengchi University

http://about.me/littleq

facebook JavaScript SDK

Before We Start…> Google Moderator: http://goo.gl/OVNszf

Ask question here!

> Code Lab Repo: https://github.com/littleq0903/fb-js-codelab The code you will need it in the practice, check out the Wiki!

> Turn your smartphone to the vibrating mode

facebook JavaScript SDK

Outline> Facebook Developers Website

> Facebook App

> Facebook Components

> Facebook JavaScript SDK (Software Development Kit)

> Code Lab for Facebook JavaScript SDK

facebook JavaScript SDK

Basic KnowledgesChapter. 0

facebook JavaScript SDK

Facebook Developer Site

> developers.facebook.com

> Documentation & Tutorials

> Facebook Developer Apps Dashboard

> Download SDK

> Online Tools

Developer Portal for Facebook App Developers

facebook JavaScript SDKFacebook Developer DashboardYou can see all your apps information here

facebook JavaScript SDK

Facebook App

DeveloperFacebook

App

Permissions

Insights

Developer Alert

Settings

> Access Token > App ID > API Keys > Request Permissions > Developer Roles

> Daily Report > Active User Statistic > Sharing Report

> Breaking Changes > New Updates > Review Status

> Domain Settings > Testing > Go to Production

The most basic unit for a developer on Facebook

facebook JavaScript SDK

Facebook Component> Graph API - get data in and out of Facebook’s Social Graph

> Login - authenticate Facebook users on your website

> Social Plugins - don’t rebuild the wheel, take the power from Facebook

What can you do with Facebook JavaScript SDK?

facebook JavaScript SDK

Social Plugins> Like Button

> Share/Send Button

> Embedded Posts

> Follow Button

> Comments

> Activity Feed

> Recommendations Box/Bar

> Like Box

> Registration

> Facepile

You know, that like button

facebook JavaScript SDK

facebook JavaScript SDK

Authentication> Facebook - username and password

> Facebook API - access token

> Preventing server gets your credentials directly

The Key to The Facebook World

facebook JavaScript SDK

AuthenticationIn The Real World Example…

Username/Password Access Token

Not easy to destroy when stolen Easy to destroy when stolen

facebook JavaScript SDK

Graph API> Everything on Facebook forms a

graph

> Your profile is an object, and has a bunch of properties

> Every object will have an ID as the identity

Me

Name

Birthday

Work

E-mailGender

Data Form of Facebook, with RESTful API 

facebook JavaScript SDK

Graph API

> Some objects will be connected with Relations

> You could fetch more data on Facebook through the relations

Data Form of Facebook, with RESTful API 

Me

Friends

Alice

Bob

Posts

“Today I go to…

“Damn, I hate school…

Photos

facebook JavaScript SDK

Facebook Dialog> Pop-up style Facebook widget

> Examples - Friend Request Dialog

- Login Dialog

- Friends Dialog

- Send Dialog

Redirect some actions, let Facebook do it!

facebook JavaScript SDK

Technical DetailsChapter. 1

facebook JavaScript SDK

What Can JavaScript SDK Do

> AuthenticationServer side cannot achieve this, the most important part of building Facebook apps

> Interact with your website usersthe thing could be done by ONLY JavaScript

> Load Facebook pre-defined components like buttons, comments, registration form in a second

> Pre-defined functions from Facebook out-of-box APIs and don’t rebuild the wheel

facebook JavaScript SDK

Authentication

Redirect user to FB for authorizing your

app

Facebook response user’s access token to your

function

Rock it up!

user type username & password to login and

authorize

JS SDK gets authorized and feedback on the interface or program

Workflow of Authentication

facebook JavaScript SDK

Authentication> FB.login()

tell Facebook it’s about time to start the authentication flow

> FB.Event.subscribe(event, callback)tell Facebook what to do when user got logged in

facebook JavaScript SDK

Graph API> Callback model applied

> RESTful knowledge

facebook JavaScript SDK

Callback Model> one of JavaScript patterns

> make sure action has been done

The most important part while using other’s JS library

function callback

Job

Okay! I will tell callback when I finished

I’ve done, here you go!

Could you plz do this for

me?

Data

Arguments

facebook JavaScript SDK

RESTful API Model

> HTTP Method: GET, POST, DELETE, PUT…

> GET /user/{id} Fetch the information of the user with id {id}

> POST /user Create a user

> DELETE /user/{id}Delete the user with id {id}

facebook JavaScript SDK

Graph API> FB.api( graph_path , callback )

{ "id": "1681390745", "name": "Colin Su", "first_name": "Colin", "last_name": "Su", "link": "https://www.facebook.com/littleq0903", "username": "littleq0903", "work": [ ... ], "gender": "male", "timezone": 8, "locale": "en_US", "verified": true, "updated_time": "2013-12-02T17:44:06+0000"}

FB.api(“/me”, function(response){ console.log(response); });

JavaScript Result

A Simple GET Example

facebook JavaScript SDK

Graph API> FB.api( graph_path , callback )

{ "data": [ {post}, {post}, {post}, {post}, {post} ]}

FB.api(“/me/posts”, function(response){ // will response an array in “data” console.log(response); });

JavaScript Result

A Simple GET Example

facebook JavaScript SDK

Graph API> FB.api( graph_path , type , options , callback )

Post ID: 6892345var body = 'Reading JS SDK documentation';FB.api('/me/feed', 'post', { message: body }, function(response) { if (!response || response.error) { console.log(‘Error occured'); } else { console.log(‘Post ID: ' + response.id); }});

JavaScript Result

A Simple POST Example

facebook JavaScript SDK

Social Plugins> out-of-box Facebook plugins

> no programmatic stuffsit’s just a piece of HTML snippet

> configure it by adjusting DOM attributes

Facebook’s Native Component on Your Website

facebook JavaScript SDK

Social Plugins> Insert a snippet into your HTML code

<div class="fb-like" data-href="https://www.facebook.com"></div>

HTML Result

Code Example

facebook JavaScript SDK

Dialogs> FB.ui(parameters , callback)

FB.ui({ method: 'friends', id: 'brent'}, function(response){});

JavaScript Result

Code Example

facebook JavaScript SDK

Dialogs> FB.ui(parameters , callback)

Code Example

Add Brent as Friend<a href=“https://www.facebook.com/dialog/friends/? id=brent &app_id=458358780877780 &redirect_uri=https://mighty-lowlands-6381.herokuapp.com/“>Add Brent as Friend</a>

HTML Result

facebook JavaScript SDK

Developer ToolsChapter. 2

facebook JavaScript SDK

Facebook Developer Tools> Graph API Explorer

Examine the result of Graph API queries

> JavaScript Test ConsoleVerify your JavaScript code’s validation and examine the result

> Access Token ToolFor generating access tokens, for streamline your testing

There are some tools to help out your development of Facebook app

facebook JavaScript SDK

Graph API Explorer> simulate querying/FQL

> simulate GET/POST/DELETE request

> filter fields

> generate/use access token easily

facebook JavaScript SDK

facebook JavaScript SDK

JavaScript Test Console

facebook JavaScript SDK

facebook JavaScript SDK

Access Token Tool> generate tokens easily

> user/app tokens in one place

> test various tokens for you app

facebook JavaScript SDK

facebook JavaScript SDK

Code LabChapter. 3

facebook JavaScript SDK

In This Code Lab

> how to integrate Facebook JavaScript SDK into your project

> how to authenticate user’s Facebook account

> how to access Graph API with users’ credentials

> how to place a Facebook cool widget on your page

> how to use Facebook dialog to save your time

You will learn…

facebook JavaScript SDK

Before We Start…

> Google Moderator: http://goo.gl/OVNszf Ask question here!

> Code Lab Repo: https://github.com/littleq0903/fb-js-codelab The code you will need it in the practice, check out the Wiki!

> Download the CodeLab packhttps://github.com/littleq0903/fb-js-codelab/releases/download/v1.0/fb-js-codelab.tgz

> Ready your editor, web browser, and passion!

Get prepared

facebook JavaScript SDK

Introduction to

facebook Python SDK!

Tutorials & Code Lab, 2013 Winter Colin Su Social Network Application

facebook JavaScript SDKhttp://goo.gl/MwcsRA

facebook JavaScript SDK

Before We Start…

> Code Lab Repo: https://github.com/littleq0903/fb-python-codelab The code you will need it in the practice, check out the Wiki!

> Turn your smartphone to the vibrating mode

facebook JavaScript SDK

Outline

> Web Application

> Heroku

> Facebook Python SDK

facebook JavaScript SDK

Web ApplicationChapter. 4

facebook JavaScript SDK

Website v.s. Web Application

> Website: display information to visitors

> Web Application: interact with users, response users’ various request

facebook JavaScript SDK

Web Application

> Front End: interact with users ( JavaScript)You’ve learned.

> Back End: deal with data (Python)The part related to this presentation

facebook JavaScript SDK

StacksWeb Framework Web Server Web Interface

User

User

User

facebook JavaScript SDK

Heroku

> Platform as a Service (PaaS)

> Easy to setup

> Your code is everything

http://heroku.com

facebook JavaScript SDK

WorkflowThe Story of a Heroku Application

Write Your Code

Deploy to Heroku

TestCreate a Heroku

Application

facebook JavaScript SDK

Technical DetailChapter. 5

facebook JavaScript SDK

JSON Serialization

> JSON to Python Object mapping

> json module

> json.loads(str) json string -> python object

> json.dumps(obj) python object -> json string

facebook JavaScript SDK

LoadExample of JSON Serialization

{u'a': [1, 2, 3, 4, 5], u'b': 2} import json !# is a string text = '{"a": [1,2,3,4,5], "b": 2}' !result = json.loads(text) !print result

Python Console

facebook JavaScript SDK

DumpExample of JSON Serialization

{"a": [1,2,3,4,5], "b": 2} import json !# is a dictionary data = {u'a': [1, 2, 3, 4, 5], u'b': 2} !result = json.dumps(data) !print result

Python Console

facebook JavaScript SDK

Bottle.py> Web Framework

WSGI-Compatible

> Writing functions as Request Handler

> Only one file as library

> http://bottlepy.org Documentation

facebook JavaScript SDK

Request Handler ExampleExample of Bottle’s Request Handler

hello worldfrom bottle import Bottle !#create your web application app = Bottle() !#define a function and point to /index @app.route('/index') def index(): return 'hello world'

Python /index

facebook JavaScript SDK

URL ArgumentExample of Bottle’s Request Handler

hello world from bottle import Bottle !#create your web application app = Bottle() !# <name> will be the 'name' argument in the function @app.route('/index/<name>') def index(name='default'): return "hello " + name

Python /index/world

facebook JavaScript SDK

Access RequestExample of Bottle’s Request Handler

<LocalRequest: GET http://localhost:8080/index> from bottle import Bottle #import request function from bottle import request !#create your web application app = Bottle() !#define a function and point to /index @app.route('/index') def index(): return request

Python /index

facebook JavaScript SDK

Heroku Deployment> First time, run heroku login to authenticate

> Must be a Git repository: git init

> heroku createCreate a Heroku app and add it to git remotes

> heroku config:set var1=val1 var2=val2Set Environment Variables on Heroku

> git push heroku masterDeploy

facebook JavaScript SDK

Git Remotes

> Git's remote branch

> Github, Heroku or your own Git server

> git push <remote> <branch>

Your Repo

Github Heroku

facebook JavaScript SDK

Installing Python Libraries

> requirement.txt Create this file and put it under the root folder

> one package per line

> <package name>

> <package name>==<version>

> (local) pip install -r ./requirements.txt

How to made Heroku server install Python packages for you

facebook JavaScript SDK

Facebook Python SDK> access Facebook Graph

> query with FQL

> Operating Data with Python is easier than JavaScript

facebook x

facebook JavaScript SDK

Documentation?

> In Python, sometimes source code is the best documentation

> Doc string

> So does bottle.py

https://github.com/pythonforfacebook/facebook-sdk/blob/master/facebook.py

facebook JavaScript SDK

Graph API

> facebook.GraphAPI( [access_token] )

> access token is not necessary

facebook JavaScript SDK

Graph API Methods> get_object

> get_connections

> fql

> put_object

> put_like

> delete_object

> put_photo

facebook JavaScript SDK

Get ObjectExample of Facebook Python SDK

{u'first_name': u'Colin', u'gender': u'male', u'id': u'1681390745', u'last_name': u'Su', u'link': u'https://www.facebook.com/littleq0903', u'locale': u'en_US', u'name': u'Colin Su', u'timezone': 8, u'updated_time': u'2013-12-05T15:31:10+0000', u'username': u'littleq0903', u'verified': True, u'work': [{u'employer': {u'id': u'240616999424812', u'name': u'Tagtoo \u5854\u5716\u79d1\u6280'}, u'location': {u'id': u'110765362279102', u'name': u'Taipei, Taiwan'}, u'position': {u'id': u'109542932398298', u'name': u'Software Engineer'}, u'start_date': u'2013-09-30'}, {u'employer': {u'id': u'454607821247176', u'name': u'g0v.tw \u53f0\u7063\u96f6\u6642\u653f\u5e9c'}}]}

import facebook !token = "..." !graph = Facebook.GraphAPI(token) !me = graph.get_object('me') !print me

Python Console

facebook JavaScript SDK

Put ObjectExample of Facebook Python SDK

Colin Su 3 seconds ago from Graph API --------------------------- !I'm testing api !--------------------------- Like . Comment . Promote . Share --------------------------- Obama and Mark Zurgerburg like this. --------------------------- Someone lalalalala 5 seconds ago . Like !Somebody ? 10 seconds ago . Like !!

import facebook !token = "..." !msg = "I'm testing api" !graph = Facebook.GraphAPI(token) !graph.put_object('me', 'feed', message=msg)

Python Facebook

facebook JavaScript SDK

FQL> Facebook Query Language

> SQL-like query for Facebook data

> support nested querying, batch querying

facebook JavaScript SDK

FQL QueryExample of Facebook Python SDK

[{u'url': u'http://www.facebook.com/littleq0903', u'username': u'littleq0903', u'name': u'Colin Su'}] import facebook

!token = "..." !graph = Facebook.GraphAPI(token) !# me() is the built-in function for returning your id query = "SELECT name,url,username FROM profile WHERE id = me()" !print graph.fql(query)

Python Console

facebook JavaScript SDK

Python SDK Code LabChapter. 6

facebook JavaScript SDK

Code Lab Repository

> littleq0903/fb-python-codelab @ Github

> Wiki -> Code Lab Checkpoints

> Download the sample package

facebook JavaScript SDK

EOF