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

Designing & Building RESTful JSON APIs

Designing & Building RESTful JSON APIs

This is a talk I gave at Ruby Tuesday (Ottawa's Ruby meetup) on August 26 2014.

To see a recording please go to: http://youtu.be/36M2BSA2LYk
For the code go to: https://github.com/aomra015/api-presentation

Ahmed Omran

August 27, 2014
Tweet

More Decks by Ahmed Omran

Other Decks in Programming

Transcript

  1. 1.What is an API and why build one? 2.How to

    design & build an API 3.Misc things to consider
  2. ! Contact data in database Client ! ! API Contact

    Data ! JSON over HTTP for our example…
  3. Building the API $ gem install rails-api $ rails-api new

    easycontacts It’s rails without the stuff you don’t need…
  4. Rails.application.routes.draw do namespace :api, :defaults => {:format => :json} do

    get "/contacts" post "/contacts" get "/contacts/:id" put "/contacts/:id" delete "/contacts/:id" end end
  5. Rails.application.routes.draw do namespace :api, :defaults => {:format => :json} do

    get "/contacts" post "/contacts" get "/contacts/:id" put "/contacts/:id" delete "/contacts/:id" end end /api/URI
  6. Rails.application.routes.draw do namespace :api, :defaults => {:format => :json} do

    get "/contacts", to: "contacts#index" post "/contacts", to: "contacts#create" get "/contacts/:id", to: "contacts#show" put "/contacts/:id", to: "contacts#update" delete "/contacts/:id", to: "contacts#destroy" end end
  7. Status Codes • 200, Ok => Successful GET • 204,

    No Content => Successful DELETE or PUT • 201, Created => Successful POST • 422, Unprocessable Entity => Well formed request but there’s a semantic error. i.e. problem creating or updating a resource. • 401, Unauthorized => Authentication credentials missing or incorrect
  8. Respond with JSON & Status Code class ContactsController < ApplicationController

    def index @contacts = Contact.all render json: @contacts, status: :ok end end 200
  9. class ContactsController < ApplicationController def update if @contact.update(contact_params) head :no_content

    else render json: @contact.errors, status: :unprocessable_entity end end end 204 422
  10. def create @contact = Contact.new(params[:contact]) ! if @contact.save render json:

    @contact, status: :created else render json: @contact.errors, status: :unprocessable_entity end end 201 422
  11. def create @contact = Contact.new(params[:contact]) ! if @contact.save render json:

    @contact, status: :created else render json: @contact.errors, status: :unprocessable_entity end end Verbose errors Tell client what went wrong
  12. Non-resource responses • /calculate, /translate, /convert ?? • use verbs

    & make it clear in API docs • or POST /calculations, /translations, /conversions
  13. Test your APIs … • Command line: cURL or httpie

    • Browser: Postman, JSON-formatter • RSpec: Request Specs • Rails Minitest: Integration tests