Slide 1

Slide 1 text

BUILDING AMBITIOUS APIS WITH RUBY Dan Gebhardt @dgeb Burlington Ruby 2013

Slide 2

Slide 2 text

DO YOU NEED AN API?

Slide 3

Slide 3 text

CLIENT-SIDE JS APPLICATION?

Slide 4

Slide 4 text

CLIENT-SIDE JS APPLICATION? YOU NEED AN API

Slide 5

Slide 5 text

NATIVE APPLICATION?

Slide 6

Slide 6 text

NATIVE APPLICATION? YOU NEED AN API

Slide 7

Slide 7 text

3RD PARTY INTEGRATION? Creative Commons image courtesy of Kamil Porembiński

Slide 8

Slide 8 text

3RD PARTY INTEGRATION? YOU NEED AN API Image credit: http://up1ter.deviantart.com/art/Twilight-Sparkle-is-flying-286029311

Slide 9

Slide 9 text

SCRIPTABLE?

Slide 10

Slide 10 text

SCRIPTABLE? YOU NEED AN API @devops_borat @hipsterhacker @neckbeardhacker

Slide 11

Slide 11 text

SO DO YOU NEED AN API?

Slide 12

Slide 12 text

SO DO YOU NEED AN API? *PROBABLY*

Slide 13

Slide 13 text

LET'S BUILD SOMETHING THAT DOES

Slide 14

Slide 14 text

RubyPets!

Slide 15

Slide 15 text

RubyPets!

Slide 16

Slide 16 text

EMBER UI

Slide 17

Slide 17 text

ANDROID & IOS APPS EMBER UI

Slide 18

Slide 18 text

ANDROID & IOS APPS EMBER UI LOLCATS INTEGRATION

Slide 19

Slide 19 text

ANDROID & IOS APPS LOLCATS INTEGRATION EMBER UI NEEDS AN API

Slide 20

Slide 20 text

"WE NEED A RESTFUL API"

Slide 21

Slide 21 text

"...AFTER YOU FEED ME!"

Slide 22

Slide 22 text

RESTFUL API BASICS

Slide 23

Slide 23 text

Your application's NOUNS are modeled as RESOURCES

Slide 24

Slide 24 text

OUR RESOURCES Pets

Slide 25

Slide 25 text

OUR RESOURCES People

Slide 26

Slide 26 text

Every RESOURCE has a URI

Slide 27

Slide 27 text

OUR RESOURCES # all pets /pets # each pet /pets/123

Slide 28

Slide 28 text

OUR RESOURCES # all people /people # each person /people/123

Slide 29

Slide 29 text

Resources are acted upon with HTTP METHODS

Slide 30

Slide 30 text

POST GET UPDATE PATCH DELETE /pets/123 /pets/ /pets/123 /pets/123 /pets/123

Slide 31

Slide 31 text

POST GET UPDATE PATCH DELETE /pets/123 /pets/ /pets/123 /pets/123 /pets/123

Slide 32

Slide 32 text

POST GET UPDATE PATCH DELETE /pets/123 /pets/ /pets/123 /pets/123 /pets/123

Slide 33

Slide 33 text

POST GET UPDATE PATCH DELETE /pets/123 /pets/ /pets/123 /pets/123 /pets/123

Slide 34

Slide 34 text

POST GET UPDATE PATCH DELETE /pets/123 /pets/ /pets/123 /pets/123 /pets/123

Slide 35

Slide 35 text

POST GET UPDATE PATCH DELETE /pets/123 /pets/ /pets/123 /pets/123 /pets/123 + MORE

Slide 36

Slide 36 text

"WE NEED AN AMBITIOUS RESTFUL API!"

Slide 37

Slide 37 text

DEFINE AMBITIOUS

Slide 38

Slide 38 text

DEFINE AMBITIOUS •Flexible

Slide 39

Slide 39 text

DEFINE AMBITIOUS •Flexible •Consistent

Slide 40

Slide 40 text

DEFINE AMBITIOUS •Flexible •Consistent •Efficient

Slide 41

Slide 41 text

DEFINE AMBITIOUS •Flexible •Consistent •Efficient •Secure

Slide 42

Slide 42 text

DEFINE AMBITIOUS •Flexible •Consistent •Efficient •Secure •Discoverable

Slide 43

Slide 43 text

IS THERE ANYTHING WE WON'T DO?

Slide 44

Slide 44 text

LET'S STICK WITH JSON ... AND SKIP XML

Slide 45

Slide 45 text

OK, LET'S GET STARTED!

Slide 46

Slide 46 text

OK, LET'S GET STARTED!

Slide 47

Slide 47 text

LET'S START SIMPLE $ rails new rubypets $ cd rubypets $ rails g scaffold pet name:string $ rails g scaffold toy name:string pet:references $ rake db:migrate # set a default route, define relationships, etc ...

Slide 48

Slide 48 text

LET'S START SIMPLE $ rails new rubypets $ cd rubypets $ rails g scaffold pet name:string $ rails g scaffold toy name:string pet:references $ rake db:migrate # set a default route, define relationships, etc ...

Slide 49

Slide 49 text

LET'S START SIMPLE $ rails new rubypets $ cd rubypets $ rails g scaffold pet name:string $ rails g scaffold toy name:string pet:references $ rake db:migrate # set a default route, define relationships, etc ...

Slide 50

Slide 50 text

LET'S START SIMPLE $ rails new rubypets $ cd rubypets $ rails g scaffold pet name:string $ rails g scaffold toy name:string pet:references $ rake db:migrate # set a default route, define relationships, etc ...

Slide 51

Slide 51 text

LET'S START SIMPLE $ rails new rubypets $ cd rubypets $ rails g scaffold pet name:string $ rails g scaffold toy name:string pet:references $ rake db:migrate # set a default route, define relationships, etc ...

Slide 52

Slide 52 text

LET'S START SIMPLE $ rails new rubypets $ cd rubypets $ rails g scaffold pet name:string $ rails g scaffold toy name:string pet:references $ rake db:migrate # set a default route, define relationships, etc ...

Slide 53

Slide 53 text

MODELS # /app/models/pet.rb class Pet < ActiveRecord::Base has_many :toys end # /app/models/toy.rb class Toy < ActiveRecord::Base belongs_to :pet end

Slide 54

Slide 54 text

CONTROLLERS class PetsController < ApplicationController before_action :set_pet, only: [:show, :edit, :update, :destroy] # GET /pets # GET /pets.json def index @pets = Pet.all end # GET /pets/1 # GET /pets/1.json def show end ..... end

Slide 55

Slide 55 text

JBUILDER VIEWS # pets/index.json.jbuilder json.array!(@pets) do |pet| json.extract! pet, :name json.url pet_url(pet, format: :json) end # pets/show.json.jbuilder json.extract! @pet, :name, :created_at, :updated_at

Slide 56

Slide 56 text

OUTPUT # /pets.json [ {"name":"Cashew", "url":"http://localhost:3000/pets/1.json"}, {"name":"Ginkgo", "url":"http://localhost:3000/pets/2.json"} ] # /pets/2.json {"name":"Ginkgo", "created_at":"2013-08-02T04:03:06.958Z", "updated_at":"2013-08-02T04:03:06.958Z"} JSON

Slide 57

Slide 57 text

OUTPUT # /pets.json [ {"name":"Cashew", "url":"http://localhost:3000/pets/1.json"}, {"name":"Ginkgo", "url":"http://localhost:3000/pets/2.json"} ] # /pets/2.json {"name":"Ginkgo", "created_at":"2013-08-02T04:03:06.958Z", "updated_at":"2013-08-02T04:03:06.958Z"} JSON

Slide 58

Slide 58 text

OUTPUT # /pets.json [ {"name":"Cashew", "url":"http://localhost:3000/pets/1.json"}, {"name":"Ginkgo", "url":"http://localhost:3000/pets/2.json"} ] # /pets/2.json {"name":"Ginkgo", "created_at":"2013-08-02T04:03:06.958Z", "updated_at":"2013-08-02T04:03:06.958Z"} "WE NEED CONSISTENCY !!!" JSON

Slide 59

Slide 59 text

JBUILDER VIEWS # pets/index.json.jbuilder json.array!(@pets) do |pet| json.extract! pet, :name json.url pet_url(pet, format: :json) end # pets/show.json.jbuilder json.extract! @pet, :name, :created_at, :updated_at

Slide 60

Slide 60 text

"CUSTOM" ISN'T ALWAYS A GOOD THING

Slide 61

Slide 61 text

WE NEED MORE CONVENTION AND LESS CONFIGURATION

Slide 62

Slide 62 text

No content

Slide 63

Slide 63 text

No content

Slide 64

Slide 64 text

No content

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

No content

Slide 68

Slide 68 text

No content

Slide 69

Slide 69 text

No content

Slide 70

Slide 70 text

No content

Slide 71

Slide 71 text

No content

Slide 72

Slide 72 text

No content

Slide 73

Slide 73 text

LET'S TRY IT OUT # Gemfile # gem 'jbuilder', '~> 1.2' gem 'active_model_serializers'

Slide 74

Slide 74 text

LET'S TRY IT OUT # Gemfile # gem 'jbuilder', '~> 1.2' gem 'active_model_serializers' $ bundle install $ rails g serializer pet $ rails g serializer toy

Slide 75

Slide 75 text

LET'S TRY IT OUT # Gemfile # gem 'jbuilder', '~> 1.2' gem 'active_model_serializers' $ bundle install $ rails g serializer pet $ rails g serializer toy

Slide 76

Slide 76 text

LET'S TRY IT OUT # Gemfile # gem 'jbuilder', '~> 1.2' gem 'active_model_serializers' $ bundle install $ rails g serializer pet $ rails g serializer toy

Slide 77

Slide 77 text

SERIALIZERS # app/serializers/pet_serializer.rb class PetSerializer < ActiveModel::Serializer attributes :id, :name, :created_at, :updated_at end # app/serializers/toy_serializer.rb class ToySerializer < ActiveModel::Serializer attributes :id, :name, :created_at, :updated_at end

Slide 78

Slide 78 text

CONTROLLERS class PetsController < ApplicationController before_action :set_pet, only: [:show, :edit, :update, :destroy] # GET /pets # GET /pets.json def index render json: Pet.all end # GET /pets/1 # GET /pets/1.json def show render json: @pet end ..... end

Slide 79

Slide 79 text

OUTPUT # /pets.json {"pets": [{"id":1, "name":"Cashew", "created_at":"2013-08-02T04:02:58.467Z", "updated_at":"2013-08-02T04:02:58.467Z"}, {"id":2, "name":"Ginkgo", "created_at":"2013-08-02T04:03:06.958Z", "updated_at":"2013-08-02T04:03:06.958Z"}]} # /pets/2.json {"pet": {"id":2, "name":"Ginkgo", "created_at":"2013-08-02T04:03:06.958Z", "updated_at":"2013-08-02T04:03:06.958Z"}} JSON

Slide 80

Slide 80 text

OUTPUT # /pets.json {"pets": [{"id":1, "name":"Cashew", "created_at":"2013-08-02T04:02:58.467Z", "updated_at":"2013-08-02T04:02:58.467Z"}, {"id":2, "name":"Ginkgo", "created_at":"2013-08-02T04:03:06.958Z", "updated_at":"2013-08-02T04:03:06.958Z"}]} # /pets/2.json {"pet": {"id":2, "name":"Ginkgo", "created_at":"2013-08-02T04:03:06.958Z", "updated_at":"2013-08-02T04:03:06.958Z"}} JSON

Slide 81

Slide 81 text

OUTPUT # /pets.json {"pets": [{"id":1, "name":"Cashew", "created_at":"2013-08-02T04:02:58.467Z", "updated_at":"2013-08-02T04:02:58.467Z"}, {"id":2, "name":"Ginkgo", "created_at":"2013-08-02T04:03:06.958Z", "updated_at":"2013-08-02T04:03:06.958Z"}]} # /pets/2.json {"pet": {"id":2, "name":"Ginkgo", "created_at":"2013-08-02T04:03:06.958Z", "updated_at":"2013-08-02T04:03:06.958Z"}} "THAT'S BETTER, BUT..." JSON

Slide 82

Slide 82 text

CUSTOM FIELDS # app/serializers/base_serializer.rb class PetSerializer < ActiveModel::Serializer attributes :id, :created_at, :updated_at # allow custom inclusion of a single field def include_created_at? if @options.key?(:fields) return @options[:fields][:created_at] end true end end

Slide 83

Slide 83 text

CUSTOM FIELDS # app/serializers/base_serializer.rb class PetSerializer < ActiveModel::Serializer attributes :id, :created_at, :updated_at # allow custom inclusion of a single field def include_created_at? if @options.key?(:fields) return @options[:fields][:created_at] end true end end "THAT'S BETTER, BUT..."

Slide 84

Slide 84 text

BASE SERIALIZER # app/serializers/base_serializer.rb class BaseSerializer < ActiveModel::Serializer attributes :id, :created_at, :updated_at end # app/serializers/pet_serializer.rb class PetSerializer < BaseSerializer attributes :name end # app/serializers/toy_serializer.rb class ToySerializer < BaseSerializer attributes :name end

Slide 85

Slide 85 text

CUSTOM FIELDS + # app/serializers/base_serializer.rb class BaseSerializer < ActiveModel::Serializer attributes :id, :created_at, :updated_at # allow custom inclusion of ANY field # via options passed in from the controller def include?(field) if @options.key?(:fields) return @options[:fields][field] end super(field) end end

Slide 86

Slide 86 text

ONE-TO-MANY # /app/models/pet.rb class Pet < ActiveRecord::Base has_many :toys end # app/serializers/pet_serializer.rb class PetSerializer < BaseSerializer attributes :name has_many :toys end

Slide 87

Slide 87 text

OUTPUT JSON # /pets/2.json {"pet": {"id":2, "name":"Ginkgo", "toys":[ {"id":3, "name":"Busy Bee"}, {"id":4, "name":"Dan's sock"}]}}

Slide 88

Slide 88 text

ONE-TO-ONE # /app/models/pet.rb class Pet < ActiveRecord::Base has_many :toys belongs_to :person end # app/serializers/pet_serializer.rb class PetSerializer < BaseSerializer attributes :name has_many :toys has_one :person end

Slide 89

Slide 89 text

OUTPUT JSON # /pets/2.json {"pet": {"id":2, "name":"Ginkgo", "toys":[ {"id":3, "name":"Busy Bee"}, {"id":4, "name":"Dan's sock"}] "person": {"id":1,"name":"Dan"}}}

Slide 90

Slide 90 text

OUTPUT JSON # /pets.json {"pets": [{"id":1, "name":"Cashew", "toys":[...], "person":{"id":1,"name":"Dan"}}, {"id":2, "name":"Ginkgo", "toys":[...], "person":{"id":1,"name":"Dan"}}]}

Slide 91

Slide 91 text

OUTPUT JSON # /pets.json {"pets": [{"id":1, "name":"Cashew", "toys":[...], "person":{"id":1,"name":"Dan"}}, {"id":2, "name":"Ginkgo", "toys":[...], "person":{"id":1,"name":"Dan"}}]} "DUPLICATION!"

Slide 92

Slide 92 text

BASE SERIALIZER # app/serializers/base_serializer.rb class BaseSerializer < ActiveModel::Serializer # sideload related data by default embed :ids, include: true attributes :id, :created_at, :updated_at end

Slide 93

Slide 93 text

OUTPUT JSON # /pets.json {"toys":[ {"id":1, "name":"BTVRuby catnip"}, {"id":2, "name":"Mr Smoochums"}, {"id":3, "name":"Busy Bee"}, {"id":4, "name":"Dan's sock"}], "people":[ {"id":1, "name":"Dan"}], "pets":[ {"id":1, "name":"Cashew", "toy_ids":[1,2], "person_id":1}, {"id":2, "name":"Ginkgo", "toy_ids":[3,4], "person_id":1}]}

Slide 94

Slide 94 text

OUTPUT JSON # /pets.json {"toys":[ {"id":1, "name":"BTVRuby catnip"}, {"id":2, "name":"Mr Smoochums"}, {"id":3, "name":"Busy Bee"}, {"id":4, "name":"Dan's sock"}], "people":[ {"id":1, "name":"Dan"}], "pets":[ {"id":1, "name":"Cashew", "toy_ids":[1,2], "person_id":1}, {"id":2, "name":"Ginkgo", "toy_ids":[3,4], "person_id":1}]}

Slide 95

Slide 95 text

OUTPUT JSON # /pets.json {"toys":[ {"id":1, "name":"BTVRuby catnip"}, {"id":2, "name":"Mr Smoochums"}, {"id":3, "name":"Busy Bee"}, {"id":4, "name":"Dan's sock"}], "people":[ {"id":1, "name":"Dan"}], "pets":[ {"id":1, "name":"Cashew", "toy_ids":[1,2], "person_id":1}, {"id":2, "name":"Ginkgo", "toy_ids":[3,4], "person_id":1}]}

Slide 96

Slide 96 text

OUTPUT JSON # /pets.json {"toys":[ {"id":1, "name":"BTVRuby catnip"}, {"id":2, "name":"Mr Smoochums"}, {"id":3, "name":"Busy Bee"}, {"id":4, "name":"Dan's sock"}], "people":[ {"id":1, "name":"Dan"}], "pets":[ {"id":1, "name":"Cashew", "toy_ids":[1,2], "person_id":1}, {"id":2, "name":"Ginkgo", "toy_ids":[3,4], "person_id":1}]} "NO DUPLICATION... I APPROVE."

Slide 97

Slide 97 text

API DESIGN

Slide 98

Slide 98 text

FILTERING DATA /pets/cats /pets/dogs

Slide 99

Slide 99 text

FILTERING DATA /pets/cats /pets/dogs ~ VS. ~ /pets?type=cats /pets?type=dogs

Slide 100

Slide 100 text

FILTERING DATA /pets/cats /pets/dogs ~ VS. ~ /pets?type=cats /pets?type=dogs /pets?type=cats,dogs

Slide 101

Slide 101 text

FILTERING DATA /pets/cats /pets/dogs ~ VS. ~ /pets?type=cats /pets?type=dogs /pets?type=cats,dogs /pets?type=cats,dogs&color=red

Slide 102

Slide 102 text

INCLUDING RELATIONSHIPS Best guess inclusions (e.g. always include toys with pets)

Slide 103

Slide 103 text

INCLUDING RELATIONSHIPS /pets?include=toys,people Best guess inclusions (e.g. always include toys with pets) ~ VS. ~ No inclusions by default. Custom inclusions as requested.

Slide 104

Slide 104 text

EMBEDDING RELATIONSHIPS Always embed any related data (i.e. JBuilder approach)

Slide 105

Slide 105 text

EMBEDDING RELATIONSHIPS Always embed any related data (i.e. JBuilder approach) ~ VS. ~ Favor "side-loading" and embed data very selectively (and only when it won't be shared)

Slide 106

Slide 106 text

VERSIONING One version that's never broken

Slide 107

Slide 107 text

VERSIONING One version that's never broken ~ VS. ~ Version by host or path api.rubypets.org v1.api.rubypets.org rubypets.org/api/v1

Slide 108

Slide 108 text

SPARSE FIELDSETS Include all fields

Slide 109

Slide 109 text

SPARSE FIELDSETS Include all fields ~ VS. ~ Allow for custom inclusion of fields: /pets?fields=id,name,age

Slide 110

Slide 110 text

SPARSE FIELDSETS Include all fields ~ VS. ~ Allow for custom inclusion of fields: /pets?fields=id,name,age /pets?include=toys,people& pet_fields=id,name,age& people_fields=id,name& toy_fields=name

Slide 111

Slide 111 text

SORTING Default sort order only

Slide 112

Slide 112 text

SORTING Default sort order only ~ VS. ~ Allow for custom sort order: /pets?sort=name # ascending /pets?sort=-name # descending

Slide 113

Slide 113 text

PAGINATION No limits on resources

Slide 114

Slide 114 text

PAGINATION No limits on resources ~ VS. ~ Provide a default page size, a max page size, and allow custom requests: /pets?page=2&per_page=100

Slide 115

Slide 115 text

PAGINATION No limits on resources ~ VS. ~ Provide a default page size, a max page size, and allow custom requests: /pets?page=2&per_page=100 Opinion! JSON API should separate the primary resource from its related resources when "side-loading" in order to clarify issues of primacy like pagination.

Slide 116

Slide 116 text

PAGINATION, CONT. As per RFC 5988, return a LINK header to allow for navigation: Link: ; rel="next", ; rel="last" Possible values for `rel`: first, last, next, prev

Slide 117

Slide 117 text

TL;DR A Hypermedia API makes full use of HTTP and a hypermedia content type to be as as navigable as the web itself. REST was a term originally invented by Roy Fielding, but since most "REST" APIs aren't in line with his definition, the term "Hypermedia API" was created. HYPERMEDIA APIS

Slide 118

Slide 118 text

HYPERMEDIA APIS Designing Hypermedia APIs by Steve Klabnik designinghypermediaapis.com Recommendation: It's not TL, so there's no reason for DR !

Slide 119

Slide 119 text

HYPERMEDIA APIS "Hypermedia designs promote scalability, allow resilience towards future changes, and promote decoupling and encapsulation, with all the benefits those things bring. On the downside, it is not necessarily the most latency-tolerant design, and caches can get stale if you’re not careful. It may not be as efficient on an individual request level as other designs." Steve Klabnik Designing Hypermedia APIs designinghypermediaapis.com

Slide 120

Slide 120 text

SECURITY

Slide 121

Slide 121 text

SECURITY A Brief History of OAuth

Slide 122

Slide 122 text

SECURITY A Brief History of OAuth

Slide 123

Slide 123 text

*BASIC* SECURITY RECOMMENDATIONS • Restrict access to particular users (e.g. non-admins) as needed in your controller and serializer layers

Slide 124

Slide 124 text

*BASIC* SECURITY RECOMMENDATIONS • Restrict access to particular users (e.g. non-admins) as needed in your controller and serializer layers • HTTPS for all the things

Slide 125

Slide 125 text

*BASIC* SECURITY RECOMMENDATIONS • Restrict access to particular users (e.g. non-admins) as needed in your controller and serializer layers • HTTPS for all the things • Use token-based security

Slide 126

Slide 126 text

*BASIC* SECURITY RECOMMENDATIONS • Restrict access to particular users (e.g. non-admins) as needed in your controller and serializer layers • HTTPS for all the things • Use token-based security • If you want to build an OAuth provider, don't go it alone. Use a gem like James Coglan's oauth2-provider: https://github.com/songkick/oauth2-provider

Slide 127

Slide 127 text

No content

Slide 128

Slide 128 text

THANKS! @dgeb Burlington Ruby 2013