SlideShare una empresa de Scribd logo
1 de 80
Beautiful REST + JSON APIs
Les Hazlewood @lhazlewood
CTO, Stormpath
stormpath.com
.com
• Identity Management and
Access Control API
• Security for your applications
• User security workflows
• Security best practices
• Developer tools, SDKs, libraries
Outline
• APIs, REST & JSON
• REST Fundamentals
• Design
Base URL
Versioning
Resource Format
Return Values
Content Negotiation
References (Linking)
Pagination
Query Parameters
Associations
Errors
IDs
Method Overloading
Resource Expansion
Partial Responses
Caching & Etags
Security
Multi Tenancy
Maintenance
APIs
• Applications
• Developers
• Pragmatism over Ideology
• Adoption
• Scale
Why REST?
• Scalability
• Generality
• Independence
• Latency (Caching)
• Security
• Encapsulation
Why JSON?
• Ubiquity
• Simplicity
• Readability
• Scalability
• Flexibility
HATEOAS
• Hypermedia
• As
• The
• Engine
• Of
• Application
• State
Further restriction on REST architectures.
REST Is Easy
REST Is *&@#$! Hard
(for providers)
REST can be easy
(if you follow some guidelines)
Example Domain: Stormpath
• Applications
• Directories
• Accounts
• Groups
• Associations
• Workflows
Fundamentals
Resources
Nouns, not Verbs
Coarse Grained, not Fine Grained
Architectural style for use-case scalability
What If?
/getAccount
/createDirectory
/updateGroup
/verifyAccountEmailAddress
What If?
/getAccount
/getAllAccounts
/searchAccounts
/createDirectory
/createLdapDirectory
/updateGroup
/updateGroupName
/findGroupsByDirectory
/searchGroupsByName
/verifyAccountEmailAddress
/verifyAccountEmailAddressByToken
…
Smells like bad RPC. DON‟T DO THIS.
Keep It Simple
The Answer
Fundamentally two types of resources:
Collection Resource
Instance Resource
Collection Resource
/applications
Instance Resource
/applications/a1b2c3
Behavior
• GET
• PUT
• POST
• DELETE
• HEAD
Behavior
POST, GET, PUT, DELETE
≠ 1:1
Create, Read, Update, Delete
Behavior
As you would expect:
GET = Read
DELETE = Delete
HEAD = Headers, no Body
Behavior
Not so obvious:
PUT and POST can both be used for
Create and Update
PUT for Create
Identifier is known by the client:
PUT /applications/clientSpecifiedId
{
…
}
PUT for Update
Full Replacement
PUT /applications/existingId
{
“name”: “Best App Ever”,
“description”: “Awesomeness”
}
PUT
Idempotent
POST as Create
On a parent resource
POST /applications
{
“name”: “Best App Ever”
}
Response:
201 Created
Location: https://api.stormpath.com/applications/a1b2c3
POST as Update
On instance resource
POST /applications/a1b2c3
{
“name”: “Best App Ever. Srsly.”
}
Response:
200 OK
POST
NOT Idempotent
Media Types
• Format Specification + Parsing Rules
• Request: Accept header
• Response: Content-Type header
• application/json
• application/foo+json
• application/foo+json;application
• …
Design Time!
Base URL
http(s)://api.foo.com
vs
http://www.foo.com/dev/service/api/rest
http(s)://api.foo.com
Rest Client
vs
Browser
Versioning
URL
https://api.stormpath.com/v1
vs.
Media-Type
application/json+foo;application&v=1
Resource Format
Media Type
Content-Type: application/json
When time allows:
application/foo+json
application/foo+json;bar=baz&v=1
…
camelCase
„JS‟ in „JSON‟ = JavaScript
myArray.forEach
Not myArray.for_each
account.givenName
Not account.given_name
Underscores for property/function names are
unconventional for JS. Stay consistent.
Date/Time/Timestamp
There‟s already a standard. Use it: ISO 8601
Example:
{
…,
“createdTimestamp”: “2012-07-10T18:02:24.343Z”
}
Use UTC!
HREF
• Distributed Hypermedia is paramount!
• Every accessible Resource has a unique
URL.
• Replaces IDs (IDs exist, but are opaque).
{
“href”: https://api.stormpath.com/v1/accounts/x7y8z9”,
…
}
Critical for linking, as we‟ll soon see
Response Body
GET obvious
What about POST?
Return the representation in the response
when feasible.
Add override (?_body=false) for control
Content Negotiation
Header
• Accept header
• Header values comma delimited in order
of preference
GET /applications/a1b2c3
Accept: application/json, text/plain
Resource Extension
/applications/a1b2c3.json
/applications/a1b2c3.csv
…
Conventionally overrides Accept header
Resource References
aka „Linking‟
• Hypermedia is paramount.
• Linking is fundamental to scalability.
• Tricky in JSON
• XML has it (XLink), JSON doesn‟t
• How do we do it?
Instance Reference
GET /accounts/x7y8z9
200 OK
{
“href”: “https://api.stormpath.com/v1/accounts/x7y8z9”,
“givenName”: “Tony”,
“surname”: “Stark”,
…,
“directory”: ????
}
Instance Reference
GET /accounts/x7y8z9
200 OK
{
“href”: “https://api.stormpath.com/v1/accounts/x7y8z9”,
“givenName”: “Tony”,
“surname”: “Stark”,
…,
“directory”: {
“href”: “https://api.stormpath.com/v1/directories/g4h5i6”
}
}
Collection Reference
GET /accounts/x7y8z9
200 OK
{
“href”: “https://api.stormpath.com/v1/accounts/x7y8z9”,
“givenName”: “Tony”,
“surname”: “Stark”,
…,
“groups”: {
“href”: “https://api.stormpath.com/v1/accounts/x7y8z9/groups”
}
}
Reference Expansion
(aka Entity Expansion, Link Expansion)
Account and its Directory?
GET /accounts/x7y8z9?expand=directory
200 OK
{
“href”: “https://api.stormpath.com/v1/accounts/x7y8z9”,
“givenName”: “Tony”,
“surname”: “Stark”,
…,
“directory”: {
“href”: “https://api.stormpath.com/v1/directories/g4h5i6”,
“name”: “Avengers”,
“creationDate”: “2012-07-01T14:22:18.029Z”,
…
}
}
Partial Representations
GET
/accounts/x7y8z9?fields=givenName,surname,
directory(name)
Pagination
Collection Resource supports query params:
• Offset
• Limit
…/applications?offset=50&limit=25
GET /accounts/x7y8z9/groups
200 OK
{
“href”: “…/accounts/x7y8z9/groups”,
“offset”: 0,
“limit”: 25,
“first”: { “href”: “…/accounts/x7y8z9/groups?offset=0” },
“previous”: null,
“next”: { “href”: “…/accounts/x7y8z9/groups?offset=25” },
“last”: { “href”: “…”},
“items”: [
{
“href”: “…”
},
{
“href”: “…”
},
…
]
}
Many To Many
Group to Account
• A group can have many accounts
• An account can be in many groups
• Each mapping is a resource:
GroupMembership
GET /groupMemberships/23lk3j2j3
200 OK
{
“href”: “…/groupMemberships/23lk3j2j3”,
“account”: {
“href”: “…”
},
“group”: {
“href”: “…”
},
…
}
GET /accounts/x7y8z9
200 OK
{
“href”: “…/accounts/x7y8z9”,
“givenName”: “Tony”,
“surname”: “Stark”,
…,
“groups”: {
“href”: “…/accounts/x7y8z9/groups”
},
“groupMemberships”: {
“href”: “…/groupMemberships?accountId=x7y8z9”
}
}
Errors
• As descriptive as possible
• As much information as possible
• Developers are your customers
POST /directories
409 Conflict
{
“status”: 409,
“code”: 40924,
“property”: “name”,
“message”: “A Directory named „Avengers‟
already exists.”,
“developerMessage”: “A directory named
„Avengers‟ already exists. If you have a stale
local cache, please expire it now.”,
“moreInfo”:
“https://www.stormpath.com/docs/api/errors/4092
4”
}
Security
Avoid sessions when possible
Authenticate every request if necessary
Stateless
Authorize based on resource content, NOT URL!
Use Existing Protocol:
Oauth 1.0a, Oauth2, Basic over SSL only
Custom Authentication Scheme:
Only if you provide client code / SDK
Only if you really, really know what you‟re doing
Use API Keys instead of Username/Passwords
401 vs 403
• 401 “Unauthorized” really means
Unauthenticated
“You need valid credentials for me to respond to
this request”
• 403 “Forbidden” really means Unauthorized
“I understood your credentials, but so sorry, you‟re
not allowed!”
HTTP Authentication Schemes
• Server response to issue challenge:
WWW-Authenticate: <scheme name>
realm=“Application Name”
• Client request to submit credentials:
Authorization: <scheme name> <data>
API Keys
• Entropy
• Password Reset
• Independence
• Speed
• Limited Exposure
• Traceability
IDs
• IDs should be opaque
• Should be globally unique
• Avoid sequential numbers
(contention, fusking)
• Good candidates: UUIDs, „Url64‟
HTTP Method Overrides
POST /accounts/x7y8z9?_method=DELETE
Caching &
Concurrency Control
Server (initial response):
ETag: "686897696a7c876b7e”
Client (later request):
If-None-Match: "686897696a7c876b7e”
Server (later response):
304 Not Modified
Maintenance
Use HTTP Redirects
Create abstraction layer / endpoints when
migrating
Use well defined custom Media Types
.com
• Free for any application
• Eliminate months of development
• Automatic security best practices
Sign Up Now: Stormpath.com

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

RESTful API Design Best Practices Using ASP.NET Web API
RESTful API Design Best Practices Using ASP.NET Web APIRESTful API Design Best Practices Using ASP.NET Web API
RESTful API Design Best Practices Using ASP.NET Web API
 
Having fun with code igniter
Having fun with code igniterHaving fun with code igniter
Having fun with code igniter
 
Introduction To CodeIgniter
Introduction To CodeIgniterIntroduction To CodeIgniter
Introduction To CodeIgniter
 
Building Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET CoreBuilding Beautiful REST APIs with ASP.NET Core
Building Beautiful REST APIs with ASP.NET Core
 
Prairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API ResponsesPrairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API Responses
 
ACL in CodeIgniter
ACL in CodeIgniterACL in CodeIgniter
ACL in CodeIgniter
 
CodeIgniter 101 Tutorial
CodeIgniter 101 TutorialCodeIgniter 101 Tutorial
CodeIgniter 101 Tutorial
 
Publishing strategies for API documentation
Publishing strategies for API documentationPublishing strategies for API documentation
Publishing strategies for API documentation
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaUsing the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
 
Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1Your First Scala Web Application using Play 2.1
Your First Scala Web Application using Play 2.1
 
Metaprogramming JavaScript
Metaprogramming  JavaScriptMetaprogramming  JavaScript
Metaprogramming JavaScript
 
Building Beautiful REST APIs in ASP.NET Core
Building Beautiful REST APIs in ASP.NET CoreBuilding Beautiful REST APIs in ASP.NET Core
Building Beautiful REST APIs in ASP.NET Core
 
Test in Rest. API testing with the help of Rest Assured.
Test in Rest. API testing with the help of  Rest Assured.Test in Rest. API testing with the help of  Rest Assured.
Test in Rest. API testing with the help of Rest Assured.
 
REST full API Design
REST full API DesignREST full API Design
REST full API Design
 
The REST And Then Some
The REST And Then SomeThe REST And Then Some
The REST And Then Some
 
Spring REST Docs: Documenting RESTful APIs using your tests - Devoxx
Spring REST Docs: Documenting RESTful APIs using your tests - DevoxxSpring REST Docs: Documenting RESTful APIs using your tests - Devoxx
Spring REST Docs: Documenting RESTful APIs using your tests - Devoxx
 
A Conversation About REST
A Conversation About RESTA Conversation About REST
A Conversation About REST
 
Web Development with Smalltalk
Web Development with SmalltalkWeb Development with Smalltalk
Web Development with Smalltalk
 
Web API Test Automation using Frisby & Node.js
Web API Test Automation using Frisby  & Node.jsWeb API Test Automation using Frisby  & Node.js
Web API Test Automation using Frisby & Node.js
 
Declarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHPDeclarative Development Using Annotations In PHP
Declarative Development Using Annotations In PHP
 

Similar a Beautiful REST and JSON APIs - Les Hazlewood

JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
Shreedhar Ganapathy
 

Similar a Beautiful REST and JSON APIs - Les Hazlewood (20)

Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
 
REST API Design for JAX-RS And Jersey
REST API Design for JAX-RS And JerseyREST API Design for JAX-RS And Jersey
REST API Design for JAX-RS And Jersey
 
Designing a beautiful REST json api
Designing a beautiful REST json apiDesigning a beautiful REST json api
Designing a beautiful REST json api
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API Platform
 
REST easy with API Platform
REST easy with API PlatformREST easy with API Platform
REST easy with API Platform
 
Elegant Rest Design Webinar
Elegant Rest Design WebinarElegant Rest Design Webinar
Elegant Rest Design Webinar
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API Platform
 
Build AWS CloudFormation Custom Resources (DEV417-R2) - AWS re:Invent 2018
Build AWS CloudFormation Custom Resources (DEV417-R2) - AWS re:Invent 2018Build AWS CloudFormation Custom Resources (DEV417-R2) - AWS re:Invent 2018
Build AWS CloudFormation Custom Resources (DEV417-R2) - AWS re:Invent 2018
 
2.28.17 Introducing DSpace 7 Webinar Slides
2.28.17 Introducing DSpace 7 Webinar Slides2.28.17 Introducing DSpace 7 Webinar Slides
2.28.17 Introducing DSpace 7 Webinar Slides
 
Spring 3 - An Introduction
Spring 3 - An IntroductionSpring 3 - An Introduction
Spring 3 - An Introduction
 
JSON REST API for WordPress
JSON REST API for WordPressJSON REST API for WordPress
JSON REST API for WordPress
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
 
Build a Node.js Client for Your REST+JSON API
Build a Node.js Client for Your REST+JSON APIBuild a Node.js Client for Your REST+JSON API
Build a Node.js Client for Your REST+JSON API
 
Avro
AvroAvro
Avro
 
Build A Killer Client For Your REST+JSON API
Build A Killer Client For Your REST+JSON APIBuild A Killer Client For Your REST+JSON API
Build A Killer Client For Your REST+JSON API
 
Shooting rabbits with sling
Shooting rabbits with slingShooting rabbits with sling
Shooting rabbits with sling
 
Scaling with swagger
Scaling with swaggerScaling with swagger
Scaling with swagger
 
Andrei shakirin rest_cxf
Andrei shakirin rest_cxfAndrei shakirin rest_cxf
Andrei shakirin rest_cxf
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responses
 
From System Engineer to Gopher
From System Engineer to GopherFrom System Engineer to Gopher
From System Engineer to Gopher
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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
 
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
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Beautiful REST and JSON APIs - Les Hazlewood