SlideShare a Scribd company logo
1 of 106
Download to read offline
RESTful API Design
Second Edition



Brian Mulloy
@landlessness

                 11.03.11 @ 11:03:11 PST
Apigee           Dial-in or VoIP
@apigee          See Details in Chat Window
groups.google.com/group/api-craft
youtube.com/apigee
To be a RESTafarian or a Pragmatist?
App    App             App       World of          API   Internal
               App                          API
User   Store         Developer    APIs            Team   Systems
Application developers are raison d'être for APIs.
Be pragmatic.

For the benefit of application developers.
Pragmatic RESTful APIs are a design problem.
baddesigns.com
Paul Mijksenaar Design for Function Award 2011
Let’s look at puppies.
hackett   hackett




hackett   hackett
...
/getAllDogs
/locationVerify
/foodNeeded
/createRecurringDogWalk
/giveDirectOrder
/healthCheck
/getRecurringDogWalkSchedule
/getLocation
/getDog
/massDogParty
/getNewDogsSince
/getRedDogs
/getSittingDogs
/dogStateChangesSearch
/replaceSittingDogsWithRunningDogs
/saveDog
...
A puppy’s world is big.
JnL               law_keven




Smithsonian's National Zoo    hackett
...                                  ...

/getAllDogs                          /getAllLeashedDogs

/verifyLocation                      /verifyVeterinarianLocation

/feedNeeded                          /feedNeededFood

/createRecurringWakeUp               /createRecurringMedication

/giveDirectOrder                     /doDirectOwnerDiscipline

/checkHealth                         /doExpressCheckupWithVeterinarian

/getRecurringWakeUpSchedule          /getRecurringFeedingSchedule

/getLocation                         /getHungerLevel

/getDog                              /getSquirrelsChasingPuppies

/newDog                              /newDogForOwner

/getNewDogsSince                     /getNewDogsAtKennelSince

/getRedDogs                          /getRedDogsWithoutSiblings

/getSittingDogs                      /getSittingDogsAtPark

/setDogStateTo                       /setLeashedDogStateTo

/replaceSittingDogsWithRunningDogs   /replaceParkSittingDogsWithRunningDogs

/saveDog                             /saveMommaDogsPuppies

...                                  ...
We are on a slippery slope.
Keep the simple things simple.
Hopkinsii
We only need two base URLs per resource.
The first is for a collection.
/dogs
The second is for an element.
/dogs/1234
POST
GET
PUT
DELETE
CREATE
READ
UPDATE
DELETE
Resource      POST            GET        PUT        DELETE
               create          read      update      delete




                                       replace
             create a                              delete all
  /dogs                    list dogs   dogs with
             new dog                               dogs
                                       new dogs


                                       if exists
             treat as a
                                       update Bo
             collection
/dogs/1234              show Bo                    delete Bo
             create new
                                       if not
             dog in it
                                       create Bo



                   Wikipedia
Resource      POST            GET        PUT       DELETE
               create          read      update      delete




                                       replace
             create a                            delete all
  /dogs                    list dogs   dogs with
             new dog                             dogs
                                       new dogs


             treat as a                if exists
             collection                update Bo
/dogs/1234   create     show Bo                    delete Bo
             new dog                   if not
             in it                     create Bo



                   Wikipedia
Resource      POST              GET        PUT        DELETE
               create            read      update      delete




                                         bulk
             create a                                delete all
  /dogs                      list dogs   update
             new dog                                 dogs
                                         dogs


                                         if exists
                                         update Bo
/dogs/1234   error           show Bo                 delete Bo
                                         if not
                                         error



                     Wikipedia
Verbs are bad.
Nouns are good.
Plurals or singulars?
Foursquare
/checkins



GroupOn
/deals



Zappos
/Product
Plurals are better.

/dogs
Abstract or concrete naming?
Super High
/things


High
/animals


Medium
/dogs


Low
/beagles
Concrete is better than abstract.
/dogs
What about associations?
GET /owners/5678/dogs

POST /owners/5678/dogs
What about complex variations?
Cody Simms
Sweep variations under the ‘?’
/dogs?color=red&state=running&location=park
Hopkinsii
/dogs
What about errors?
meredithfarmer
Facebook            HTTP Status Code: 200

{"type":"OAuthException","message":"(#803) Some
of the aliases you requested do not exist:
foo.bar"}




Twilio              HTTP Status Code: 401

{"status":401,"message":"Authenticate","code":
20003,"more_info":"http://www.twilio.com/docs/
errors/20003"}




SimpleGeo           HTTP Status Code: 401

{"code":401,"message":"Authentication
Required"}
Code for code
200 - OK

401 - Unauthorized
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes




Message for people
{“message” : “Verbose, plain language
description of the problem with hints about
how to fix it.”
“more_info” : “http://dev.teachdogrest.com/
errors/12345”}
What about versioning?
Twilio
/2010-04-01/Accounts/



salesforce.com
/services/data/v20.0/sobjects/Account



Facebook
?v=1.0
/v1/dogs
Please give me exactly what I need.
LinkedIn
/people:(id,first-name,last-name,industry)




Facebook
/joe.smith/friends?fields=id,name,picture




Google (partial response)
?fields=title,media:group(media:thumbnail)
/dogs?fields=name,color,location
What about pagination?
Facebook
offset
limit


Twitter
page
rpp


LinkedIn
start
count
/dogs?limit=25&offset=50
What about formats?
Google Data
?alt=json



Foursquare
/venue.json



Digg*
Accept: application/json
?type=json
* The type argument, if present, overrides the Accept header.
/dogs.json


/dogs/1234.json
What about defaults?
Format
json



Pagination (depends on data size)
limit=10&offset=0
What about attribute names?
Twitter
"created_at": "Thu Nov 03 05:19:38 +0000 2011"




Bing
"DateTime": "2011-10-29T09:35:00Z"




Foursquare
"createdAt": 1320296464
JSON is for JavaScript Objects
var myObject = JSON.parse(response);



These looks funny in JavaScript

timing = myObject.created_at;

timing = myObject.DateTime;
JavaScript Convention
"createdAt": 1320296464


timing = myObject.createdAt;

Medial Capitalization aka CamelCase
What about non-resource-y stuff?
Calculate

Translate

Convert
Use verbs not nouns
/convert?from=EUR&to=CNY&amount=100
What about searching?
Global
/search?q=fluffy+fur



Scoped
/owners/5678/dogs/search?q=fluffy+fur



Formatted
/search.xml?q=fluffy+fur
What about counts?
/dogs/count
What about the rest of the URL?
Facebook    graph.facebook.com

             api.facebook.com

             developers.facebook.com



Foursquare   api.foursquare.com
             developers.foursquare.com



   Twitter   api.twitter.com

             search.twitter.com

             stream.twitter.com

             dev.twitter.com
API gateway
api.teachdogrest.com



Developer connection
developers.teachdogrest.com



Do web redirects
api ! developers (if from browser)

dev ! developers
developer ! developers
What about exceptional stuff?
Client intercepts HTTP error codes
Twitter

/public_timelines.json?
suppress_response_codes=true


HTTP Status Code: 200


{"error" : "Could not authenticate
you." }
Always returns OK
/dogs?suppress_response_codes=true


Code for code ignoring
200 - OK


Message for people & code
{“response_code” : “401”, “message” :
“Verbose, plain language description of the
problem with hints about how to fix it.”
“more_info” : “http://dev.teachdogrest.com/
errors/12345”, “code” : 12345}
Client supports limited HTTP methods
Method Parameter
create

/dogs?method=post
read

/dogs
update

/dogs/1234?method=put&location=park
delete

/dogs/1234?method=delete
What about authentication?
PayPal
Permissions Service API



Facebook
OAuth 2.0



Twitter
OAuth 1.0a
Use latest and greatest OAuth
OAuth 2.0
Don’t do something close, but different.
How do application developers use the API?
What about chatty applications?
First be complete & RESTful.


Then provide shortcuts.
Partial response syntax can help.

/owners/5678?fields=name,dogs(name)
What about when building an UI
requires a lot of domain knowledge?
Complement your API with code
libraries and SDK.
Really? All of this? And iterate it?
Application




      API Virtualization Layer




API             API              API
Be RESTful
Only 2 URLs
No verbs
Use nouns as plurals
Concrete over abstract
For JSON follow JavaScript conventions
Sweep complexity behind the ‘?’
Borrow from leading APIs
Account for exceptional clients
Add virtualization layer
Questions?
THANK YOU
Subscribe to API webinars at:
youtube.com/apigee
THANK YOU
Questions and ideas to:
groups.google.com/group/api-craft
THANK YOU
Contact me at:
@landlessness
brian@apigee.com

More Related Content

What's hot

What's hot (20)

10 Tips for Configuring Your Builds with Bamboo Specs
10 Tips for Configuring Your Builds with Bamboo Specs10 Tips for Configuring Your Builds with Bamboo Specs
10 Tips for Configuring Your Builds with Bamboo Specs
 
Arrow Functions in JavaScript
Arrow Functions in JavaScriptArrow Functions in JavaScript
Arrow Functions in JavaScript
 
Rest API
Rest APIRest API
Rest API
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMSM.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS
 
Spring Boot Observability
Spring Boot ObservabilitySpring Boot Observability
Spring Boot Observability
 
Deploying Elasticsearch and Kibana on Kubernetes with the Elastic Operator / ECK
Deploying Elasticsearch and Kibana on Kubernetes with the Elastic Operator / ECKDeploying Elasticsearch and Kibana on Kubernetes with the Elastic Operator / ECK
Deploying Elasticsearch and Kibana on Kubernetes with the Elastic Operator / ECK
 
API Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid Rahimian
API Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid RahimianAPI Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid Rahimian
API Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid Rahimian
 
RESTFul API Design and Documentation - an Introduction
RESTFul API Design and Documentation - an IntroductionRESTFul API Design and Documentation - an Introduction
RESTFul API Design and Documentation - an Introduction
 
REST-API overview / concepts
REST-API overview / conceptsREST-API overview / concepts
REST-API overview / concepts
 
아파치 카프카 입문과 활용 강의자료
아파치 카프카 입문과 활용 강의자료아파치 카프카 입문과 활용 강의자료
아파치 카프카 입문과 활용 강의자료
 
REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & Development
 
RESTful API - Best Practices
RESTful API - Best PracticesRESTful API - Best Practices
RESTful API - Best Practices
 
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
 
Elk stack
Elk stackElk stack
Elk stack
 
Practical Celery
Practical CeleryPractical Celery
Practical Celery
 
Introdução APIs RESTful
Introdução APIs RESTfulIntrodução APIs RESTful
Introdução APIs RESTful
 
Pydata-Python tools for webscraping
Pydata-Python tools for webscrapingPydata-Python tools for webscraping
Pydata-Python tools for webscraping
 
Improving the performance of Odoo deployments
Improving the performance of Odoo deploymentsImproving the performance of Odoo deployments
Improving the performance of Odoo deployments
 
Data discovery & metadata management (amundsen installation)
Data discovery & metadata management (amundsen installation)Data discovery & metadata management (amundsen installation)
Data discovery & metadata management (amundsen installation)
 

Viewers also liked (6)

대용량 분산 아키텍쳐 설계 #5. rest
대용량 분산 아키텍쳐 설계 #5. rest대용량 분산 아키텍쳐 설계 #5. rest
대용량 분산 아키텍쳐 설계 #5. rest
 
대용량 분산 아키텍쳐 설계 #2 대용량 분산 시스템 아키텍쳐 디자인 패턴
대용량 분산 아키텍쳐 설계 #2 대용량 분산 시스템 아키텍쳐 디자인 패턴대용량 분산 아키텍쳐 설계 #2 대용량 분산 시스템 아키텍쳐 디자인 패턴
대용량 분산 아키텍쳐 설계 #2 대용량 분산 시스템 아키텍쳐 디자인 패턴
 
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
 
대용량 분산 아키텍쳐 설계 #4. soa 아키텍쳐
대용량 분산 아키텍쳐 설계 #4. soa 아키텍쳐대용량 분산 아키텍쳐 설계 #4. soa 아키텍쳐
대용량 분산 아키텍쳐 설계 #4. soa 아키텍쳐
 
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
 
Global platform
Global platformGlobal platform
Global platform
 

More from Apigee | Google Cloud

More from Apigee | Google Cloud (20)

How Secure Are Your APIs?
How Secure Are Your APIs?How Secure Are Your APIs?
How Secure Are Your APIs?
 
Magazine Luiza at a glance (1)
Magazine Luiza at a glance (1)Magazine Luiza at a glance (1)
Magazine Luiza at a glance (1)
 
Monetization: Unlock More Value from Your APIs
Monetization: Unlock More Value from Your APIs Monetization: Unlock More Value from Your APIs
Monetization: Unlock More Value from Your APIs
 
Apigee Demo: API Platform Overview
Apigee Demo: API Platform OverviewApigee Demo: API Platform Overview
Apigee Demo: API Platform Overview
 
Ticketmaster at a glance
Ticketmaster at a glanceTicketmaster at a glance
Ticketmaster at a glance
 
AccuWeather: Recasting API Experiences in a Developer-First World
AccuWeather: Recasting API Experiences in a Developer-First WorldAccuWeather: Recasting API Experiences in a Developer-First World
AccuWeather: Recasting API Experiences in a Developer-First World
 
Which Application Modernization Pattern Is Right For You?
Which Application Modernization Pattern Is Right For You?Which Application Modernization Pattern Is Right For You?
Which Application Modernization Pattern Is Right For You?
 
Apigee Product Roadmap Part 2
Apigee Product Roadmap Part 2Apigee Product Roadmap Part 2
Apigee Product Roadmap Part 2
 
The Four Transformative Forces of the API Management Market
The Four Transformative Forces of the API Management MarketThe Four Transformative Forces of the API Management Market
The Four Transformative Forces of the API Management Market
 
Walgreens at a glance
Walgreens at a glanceWalgreens at a glance
Walgreens at a glance
 
Apigee Edge: Intro to Microgateway
Apigee Edge: Intro to MicrogatewayApigee Edge: Intro to Microgateway
Apigee Edge: Intro to Microgateway
 
Managing the Complexity of Microservices Deployments
Managing the Complexity of Microservices DeploymentsManaging the Complexity of Microservices Deployments
Managing the Complexity of Microservices Deployments
 
Pitney Bowes at a glance
Pitney Bowes at a glancePitney Bowes at a glance
Pitney Bowes at a glance
 
Microservices Done Right: Key Ingredients for Microservices Success
Microservices Done Right: Key Ingredients for Microservices SuccessMicroservices Done Right: Key Ingredients for Microservices Success
Microservices Done Right: Key Ingredients for Microservices Success
 
Adapt or Die: Opening Keynote with Chet Kapoor
Adapt or Die: Opening Keynote with Chet KapoorAdapt or Die: Opening Keynote with Chet Kapoor
Adapt or Die: Opening Keynote with Chet Kapoor
 
Adapt or Die: Keynote with Greg Brail
Adapt or Die: Keynote with Greg BrailAdapt or Die: Keynote with Greg Brail
Adapt or Die: Keynote with Greg Brail
 
Adapt or Die: Keynote with Anant Jhingran
Adapt or Die: Keynote with Anant JhingranAdapt or Die: Keynote with Anant Jhingran
Adapt or Die: Keynote with Anant Jhingran
 
London Adapt or Die: Opening Keynot
London Adapt or Die: Opening KeynotLondon Adapt or Die: Opening Keynot
London Adapt or Die: Opening Keynot
 
London Adapt or Die: Lunch keynote
London Adapt or Die: Lunch keynoteLondon Adapt or Die: Lunch keynote
London Adapt or Die: Lunch keynote
 
London Adapt or Die: Closing Keynote — Adapt Now!
London Adapt or Die: Closing Keynote — Adapt Now!London Adapt or Die: Closing Keynote — Adapt Now!
London Adapt or Die: Closing Keynote — Adapt Now!
 

Recently uploaded

Recently uploaded (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

RESTful API Design, Second Edition