Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Creating a RESTful API for mobile applications

Creating a RESTful API for mobile applications

Paul McMahon

March 25, 2013
Tweet

More Decks by Paul McMahon

Other Decks in Technology

Transcript

  1. 5 standard actions in APIs GET /communities List communities POST

    /communities Create a community GET /communities/1 Get a community PUT /communities/1 Update a community DELETE /communities/1 Delete a community
  2. So the body of a request / response could be

    html, json, xml, image, etc
  3. Example { “community”: { “name”: “Tokyo iOS Meetup”, “post_count”: 5,

    “members”: [ { “name”: “Paul” }, { “name”: “Matt” } ], “public”: true, }
  4. Important status codes 200 OK 201 Created 401 Not Authorized

    404 Not Found 406 Not Acceptable 422 Unprocessable Entity
  5. Anatomy of an API Controller class Api::V1::CommunitiesController respond_to :json def

    index @communities = Community.all respond_with @communities end end
  6. RABL # app/views/posts/index.rabl collection @posts attributes :id, :title, :subject child(:user)

    { attributes :full_name } node(:read) { |post| post.read_by?(@user) } [{ "post" : { "id" : 5, title: "...", subject: "...", "user" : { full_name : "..." }, "read" : true } }]
  7. ActiveModel Serializers class PostSerializer < ActiveModel::Serializer attributes :id, :title, :body

    has_many :comments end class CommentSerializer < ActiveModel::Serializer attributes :id, :text end # /posts/1 { “post” : { “id”: 1, “title”: “Sample”, “body”: “Sample Body”, “comments”: [ {“id”: 1, “text”: “comment 1”}}, {“id”: 2, “text”: “comment 2”}] }
  8. OAuth2 with Doorkeeper class Api::V1::CommunitiesController respond_to :json doorkeeper_for :index def

    index @communities = Community.all respond_with @communities end end