Facebook & Twitter API

  • View

  • Download

Embed Size (px)


This is my initial release of a slide deck used to support a quick training to students on Facebook and Twitter API. A lot of stuff would need to be fixed (my english first as a non-native writer :-). It also does not (yet?) cover all APIs. This support is better with associated resources such as the underlying Postman request collections. Please feel free to give feedback if any.

Text of Facebook & Twitter API

  • Application Programming InterfaceFacebookhttp://www.slideshare.net/fabricedelhosteTwitter fabrice@delhoste.comFacebook: http://www.facebook.com/fabricedelhosteTwitter: @spifdDc. 2013

Content APISocial NetworksFacebookTwitter2 WarningThese slides are for training or educational purposes. They do not replace reference documentation. ! This is my rst version, december 2013. If you read this in 2013+, check for deprecation. Feel free to give me your feedback.!Pictures and clip arts are free for use. Credits coming on next release.3 APIApplication Programming Interface API? Application Programming InterfaceSoftware-to-software contractDenes the interactions between components5 API A good API can provide FlexibilitySecurityEase of useSimplicity Modern software are made of APIsScalabilityPortabilityOtherwise, it would serve a limited purpose6 API Design Patterns Separating interface from implementation !Faade design pattern A simplied interface to a larger body of codeMake software easier and convenient to useReduce dependenciesWrap a poorly designed APIs with a single well-designed API 7 API Platform Developers can be: customers channels to customersOffering them friendly helpful API is business-oriented cost-reductiontime-to-marketknow-how and expertise 8 API Cloud Computing Infrastructure-as-a-Service (IaaS) - infra level Platform-as-a-Service (PaaS) - service level API provides messaging system, databases, execution environmentSoftware-as-a-Service (SaaS) - application level API provides control, distribution, network, and workload.API mediates between apps and underlying IT infrastructureBackend-as-a-Service (BaaS) - application dev level API provides unied way to connect apps to cloud services 9 API General Recommendations Try test-driven design Think about what client really needs, not what your server can offer !Choose vocabulary wiselyUse standard when possibleCopy & enhance popular existing APIsBe self-descriptive, developer-friendlyTry dening highest level of API 10 API Practical Work Real world use case analysis What would you have done?11 HTTPQuick Overview HTTP Application protocol for distributed hypermedia systems. Request / responseStatelessMedia independentFoundation of the WWWCurrent version: 1.113 HTTP Request Format Request lineRequest headersEmpty line.Optional message body.POST /1.1/lists/create.json?name=My%20new%20list&mode=private HTTP/1.1 X-HostCommonName: api.twitter.com Authorization: OAuth oauth_consumer_key= Host: api.twitter.com Content-Length: 0 X-Target-URI: https://api.twitter.com Content-Type:application/x-www-form-urlencoded; charset=UTF-8 Connection: Keep-Alive! ! ! !14 HTTP Response Format Status lineResponse headersEmpty lineOptional message bodyHTTP/1.1 200 OK content-type: application/json; charset=utf-8 last-modified: Sun, 08 Dec 2013 20:41:48 GMT status: 200 OK date: Sun, 08 Dec 2013 20:41:48 GMT Connection: close content-length: 1879!{ "id_str": "101144843", "full_name": "@spifd/lists/my-new-list", "user": { "id_str": "18229030", 15 HTTP URL - Unied Resource Locator Not sent to server.Only browser.HTTP: clear HTTPS: encryptedURL (or Percent) encoding ! # $ & ( ) * + , / : ; = ? @ [ ] converted to %21 %23 %24 16 HTTP Verbs (methods) GET: retrieve a resourceOthersHEAD: GET without bodysafe: it must not modify resources idempotent: 1 call, same as multiple callsTRACE: echo request back to the senderOPTIONS: supported HTTP verbsCONNECT: connects to proxyPATCH: partial updatePUT: create/update a resource idempotentPOST: add a subordinate resource! not safe, not idempotentSafe/idempotent: DELETE: delete a resource Only semantic, no constraint in protocolidempotent 17 HTTP Headers General header: for both request and response messages. Request header: only for request messages. Ex: Authorization, Accept, Cookie, Host, User-AgentResponse header: only for response messages. Ex: Cache-Control, ConnectionEx: Server, Set-CookieEntity header: metadata about the entity body Ex: Content-Encoding, Content-Length, Content-Type, Last-Modied 18 HTTP Request Parameters For GET, part of the URL query string as eld / value pairs eld1=value1&eld2=value2&eld3=value3For POST, request parameters are sent using: Using "Content-type: application/x-www-form-urlencoded" (header) The content body contains "eld1=value1&eld2=value2&eld3=value3"Using "Content-type: "multipart/form-data" (header) for binary data Special format using several parts separated with a particular string boundary (content-disposition header), each part having its own contenttype header. 19 HTTP Status Codes 1xx: Informational2xx: Successful4xx: Client Error 400: Bad Request401: Unauthorized3xx: Redirection403: Forbidden302: Found404: Not Found304: Not modied (f-Modied-Since header)405: Method Not Allowed ! ! !201: Created (PUT & POST)5xx: Server Error 500: Internal Server Error503: Service Unavailable20 HTTP Security Authorization Header Allows different kind of authentication : basic, digest, oauthAuthorization: {Type} {Data}Ex: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== RFC2045-MIME variant of Base64 encoding of login:passwordEncryption with HTTPS = HTTP over SSL/TLS Assymetric key derived into a short-term session keyUsed to encrypt the whole HTTP data ow 21 HTTP DisclaimerHTTP Requests are NOT purely written to ease readability. !In particular: - they do NOT strictly respect HTTP format - they do NOT follow correctly URL-encoding when needed - they do NOT contain all HTTP headers and body !We are humans, not machines. 22 PostmanChrome App - Handy HTTP Client Postman24 API Practical Work Download and install Google ChromeDownload and install Postman (Packaged app) http://www.getpostman.com/ If you want to inspect requests in Google Chrome network console, browse chrome://ags and "Enable debugging for packed apps"Take time to play and be familiar with Postman features Well use it all along the training.See how to create collections, to save them, Ill collect your backup. 25 RESTDesigning Lightweight APIs REST REpresentational State TransferDened by HTTP 1.0 & 1.1 author (Roy Fielding)Architectural styleREST = Transfer of representations of resources !A simple way to handle interactions between systems 27 REST Main Principles Identify everything with an identierLink things togetherUse standardsResources with multiple representationsStateless28 REST Characteristics LightweightScalableSimpleFlexibleReadableReliableEfcientPortable! !29 REST HTTP-based Easy SOA (Service-Oriented Architecture) SOAP is another way often cumbersomePragmatic approach, mostly based on HTTP protocol Well known, widely deployed, and avoid new layersUse HTTP verbsUse URI as a global identier for resources30 REST RESTful Constraints Client-server: separation of concerns, separate interface from implementationStateless server: requests contains all necessary informationCache: responses can be cached or notUniform interface: Identication of resources: each resource is uniquely identiedManipulation of resources through representations: each resource has one or more representationsSelf-descriptive message: message is not only data but everything necessary for the message to be processedHypermedia as the engine for application state (HATEOAS): the server must give the client the needed information to navigate the serviceLayered system: client has no idea about the end server or intermediates processing the requestsCode-on-demand (optional): client are extendable by downloading code 31 REST CRUD POST = CREATEGET = READPUT = UPDATEDELETE = DELETEAlternative: POST /dogs?method=delete Filtering proxies, 32 REST Resources Use nouns, no verbPlural: /dogsConcrete: /dogs instead of /animalsUse Javascript naming convention33 REST Collections 2 base URLs per resourceCollection /dogsElement /dogs/123434 REST Requests for resources GET /owners/5678/dogsPOST /owners/5678/dogsGET /dogs?color=red&state=running&location=parkGET /dogs?elds=name,color,location.cityGET /dogs.xml?limit=25&offset=50GET /owners/5678/dogs?q=Bobby (search) 35 REST Requests for non-resources Use verbs for non-resources: compute, search, GET /convert?from=EUR&t=CNY&amount=100GET /search?q=toto (global search)GET /owners/5678/dogs/search?q=totoGET /dogs/count36 REST Handling errors Use HTTP status codes. Those are enough for most usages: 304: Not modied400: Bad Request, 401: Unauthorized, 403: Forbidden, 404: Not Found200: OK, 201: Created500: Internal Server ErrorBe verbose and self-descriptive in response body. Example:{"developerMessage" : "Verbose, plain language description of the problem for the app developer with hints about how to fix it.", "userMessage":"Pass this message on to the app user if needed.", "errorCode" : 12345, "more info": "http:// dev.teachdogrest.com/errors/12345"} 37 REST Versioning Make version mandatory.Use v prex to avoid confusionUse one number. API is not implementation.Ex: /v1/dogsRecommendations: Ascending compatibility with 1 versionCommunicate very soon on (breaking) changes. 38 REST REST API Design State of the art !You want to become a REST ninja?Read everything from: https://apigee.com/about/api-best-practices39 JSONOverview JSON http://www.json.org/JavaScript Object NotationLightweight standard for data-interchange formatDeveloper-friendly Easy for humans to read/write Efcient to parse/generateOpen, not only Javascript 41 JSON Types NumberArray: ordered values12[ 1, "apple", true, { } ] 2.45 324.0594 String "hello"Object: unordered key/value pairs. hello { "title": "Games of Thrones", "season": 1 }Boolean truefalse Empty value null 42 JSON Example { "id": "4", "favorite_teams": [ { "id": "116174408393207", "name": "Yankees" } ], "name": "Mark Zuckerberg", "hometown": { "id": "105506396148790", "name": "Dobbs Ferry, New York" } }43 API Practical Work In Postman, create a "API Todo" HTTP request collectionThink about a REST AP