Upload
indikamaligaspe
View
254
Download
4
Tags:
Embed Size (px)
DESCRIPTION
This presentation done on REST services explains the fundamentals of REST services as well as emphasizes on several best practices and standards that we have learnt over the years in building our REST API's.
Citation preview
Reservations Gateway Inc.Reservations Gateway Inc. YOUR LINK to e-TRAVEL SOLUTIONSYOUR LINK to e-TRAVEL SOLUTIONS
June 2014
REST Services – an Architects REST Services – an Architects GuideGuide
““The teacher gets to be a student The teacher gets to be a student
each time he teaches ”each time he teaches ”
- - Indika MaligaspeIndika Maligaspe
Indika Maligaspe
Intro...Intro...
October 2013
Indika Maligaspe
K. Indika Maligaspe
Chief Technology Officer – RezGateway Inc.
Developer, Designer, Architect , Trainer
Specialized in JEE, Web Services , Software Engineering etc...
Over 13 years if experience in IT / Web Technologies http://www.linkedin.com/profile/view?id=201732082&trk=nav_responsive_tab_profile
June 2014
What is HTTP – Intro to HTTP What is HTTP – Intro to HTTP
What is REST – Intro to REST ServicesWhat is REST – Intro to REST Services
BEST Practices for building REST services BEST Practices for building REST services
What we will coverWhat we will cover
Indika Maligaspe
June 2014
Stands for Hypertext Transfer ProtocolStands for Hypertext Transfer Protocol
Defines a set of rules for transferring Hypertext on WWWDefines a set of rules for transferring Hypertext on WWW
A request / response protocol for Client - ServerA request / response protocol for Client - Server
What is HTTPWhat is HTTP
Indika Maligaspe
Hypertext is structured text that uses logical links Hypertext is structured text that uses logical links (hyperlinks) between nodes containing text. HTTP (hyperlinks) between nodes containing text. HTTP is a set of rules to exchange or transfer hypertext is a set of rules to exchange or transfer hypertext (hypermedia) between a client and a server.(hypermedia) between a client and a server.
June 2014
What is HTTPWhat is HTTP
Indika Maligaspe
May 2014
Stands for Representational State TransferStands for Representational State Transfer
It is an Architectural StyleIt is an Architectural Style
Set of Constraints for distributed hypermedia Set of Constraints for distributed hypermedia systemssystems
Was used to design HTTP1.1Was used to design HTTP1.1
What is RESTWhat is REST
Indika Maligaspe
In Many ways, the World Wide Web itself, based on In Many ways, the World Wide Web itself, based on HTTP can be viewed as a REST-based architectureHTTP can be viewed as a REST-based architecture
June 2014
Resource Based – Resources are transferred to / from the origin Resource Based – Resources are transferred to / from the origin serverserver
Representation – Presents the state of the resources Representation – Presents the state of the resources (what lives (what lives in that resource like Hotel / City / User etc...)in that resource like Hotel / City / User etc...)
Identified by URI – All resources are identified by a unique URIIdentified by URI – All resources are identified by a unique URI
Has HTTP behaviors – GET / POST / PUT / DELETE /HEAD etc...Has HTTP behaviors – GET / POST / PUT / DELETE /HEAD etc...
Has MediaTypes – Format Specification + Parsing rules Has MediaTypes – Format Specification + Parsing rules
Features of RESTFeatures of REST
Indika Maligaspe
GETGETapi.rezgateway.com/hotel/ID/HiltonMarriottapi.rezgateway.com/hotel/ID/HiltonMarriott
Request – Accept HeaderRequest – Accept HeaderAccept:Accept: application/json, application/xml, */*; application/json, application/xml, */*;
q=0.01q=0.01
Response – Content TypeResponse – Content TypeContent-Type:Content-Type: application/jsonapplication/json
June 2014
Six ConstraintsSix Constraints
Uniform Interface - Uniform Interface - Defines a specific , uniformed way of Defines a specific , uniformed way of communicating between the User Agent and Origin Server (HTTP verbs, communicating between the User Agent and Origin Server (HTTP verbs, URI , HTTP Response)URI , HTTP Response)
Statelessness - Statelessness - Server contains no client state . Each message is Server contains no client state . Each message is self descriptive. ***There are some anti patterns (Oauth 2)self descriptive. ***There are some anti patterns (Oauth 2)
Client Server - Client Server - Assumes a disconnected systemAssumes a disconnected system
Cacheble - Cacheble - Server responses are cacheble (Explicit / Implicit)Server responses are cacheble (Explicit / Implicit)
Layered System - Layered System - Software or Hardware intermediaries between Software or Hardware intermediaries between client and server (Proxy / Gateway etc...)client and server (Proxy / Gateway etc...)
Source on Demand (Optional) - Source on Demand (Optional) - Server can temporarily extend Server can temporarily extend client (JavaScripts / Applets )client (JavaScripts / Applets )
Constraints in REST Constraints in REST
Indika Maligaspe
Above constraints give – Above constraints give – Scalability / Simplicity / Modifiability / Visibility / Portability / Scalability / Simplicity / Modifiability / Visibility / Portability /
ReliabilityReliability
June 2014
Resource Resource
Nouns not verbs (hotel / book / user etc... and not Nouns not verbs (hotel / book / user etc... and not GetHotel / getBooks etc...)GetHotel / getBooks etc...)
Coarse GrainedCoarse Grained
Two TypesTwo Types
Collections – Books / UsersCollections – Books / Users
Instance – Book/a1b1c1Instance – Book/a1b1c1
Some Best Practices Some Best Practices
Indika Maligaspe
June 2014
URI'sURI's
Should be Should be Global – Global – globally accessible (scope)globally accessible (scope)
Disambiguable – Disambiguable – not ambiguousnot ambiguous Resolvable – Resolvable – Name of the thing is how we relate to it Name of the thing is how we relate to it
Some Best Practices Some Best Practices
Indika Maligaspe
http://api.rezgateway.com/hotel/1234567 Vs Vshttp://api.rezgateway.com/hotel/id/1234567http://api.rezgateway.com/hotel/id/1234567
June 2014
URI'sURI's
http://api.rezgateway.com Vs Vs http://www.rezgateway.com/services/rest/v1/hotels
http://api.rezgateway.com/hotels Vs http://api.rezgateway.com/hotels Vs http://api.rezgateway.com/hotels/hotel.cgi or http://api.rezgateway.com/hotels/hotel.cgi or http://api.rezgateway.com/hotels/hotel.do
http://api.rezgateway.com/getHotels?goups=Marriot Vs Vs http://api.rezgatewway.com/hotels/groups/Marriotthttp://api.rezgatewway.com/hotels/groups/Marriott
Some Best Practices Some Best Practices
Indika Maligaspe
Make each URI meaningful,expandable, long lasting and Make each URI meaningful,expandable, long lasting and decouple them from the underlying technology / framework decouple them from the underlying technology / framework used to build the service.used to build the service.
June 2014
Verbs / Behaviors Verbs / Behaviors
GET – Safe / Idempotent / Cacheable GET – Safe / Idempotent / Cacheable
POST – None of the abovePOST – None of the above
PUT – IdempotentPUT – Idempotent
DELETE – IdempotentDELETE – Idempotent
Some Best Practices Some Best Practices
Indika Maligaspe
Use each verb to do what they are suppose to do, do not use Use each verb to do what they are suppose to do, do not use POST to get content or GET to change resource statePOST to get content or GET to change resource state
June 2014
Content NegotiationContent Negotiation
Header values comma delimited in order of preference (accept header , Header values comma delimited in order of preference (accept header , type, language, encoding)type, language, encoding)
Use Vary Response HeaderUse Vary Response Header
No sufix based resource URI'sNo sufix based resource URI's
Some Best Practices Some Best Practices
Indika Maligaspe
Vary:Accept-LangugeVary:Accept-Languge Vary:Accept-Encoding Vary:Accept-Encoding
Accept:application/json,application/xml;q=1.0Accept:application/json,application/xml;q=1.0 Accept-language: en;q-1.0Accept-language: en;q-1.0 Accept-encoding: gzipAccept-encoding: gzip
http://api.rezgateway.com/hotels.csv (do not use) (do not use) http://api.rezgateway.com/hotels.do (do not use)http://api.rezgateway.com/hotels.do (do not use)
June 2014
VersioningVersioning
Media-Type request header = application/json;version=1 is better then Media-Type request header = application/json;version=1 is better then http://api.rezgateway.com/v1/hotelshttp://api.rezgateway.com/v1/hotels
Don't remove element without upgrading a version, but can frequently Don't remove element without upgrading a version, but can frequently add optional elements.add optional elements.
Some Best Practices Some Best Practices
Indika Maligaspe
Make version upgrades only when needed and make them Make version upgrades only when needed and make them painless as possible to your clients.painless as possible to your clients.
June 2014
Response BodyResponse Body
Date and Time – use ISO8601, UTCDate and Time – use ISO8601, UTC
Use JavaScript notations (camelCase) – mainly with JSON Use JavaScript notations (camelCase) – mainly with JSON
Keep things meaningfulKeep things meaningful
Some Best Practices Some Best Practices
Indika Maligaspe
"type":”2” vs "type":"Non Contracted Rates" (more meaningful) "type":”2” vs "type":"Non Contracted Rates" (more meaningful)
"firstname":"Bob","firstname":"Bob","lastname":"Singer""lastname":"Singer" vsvs"names":"names":
{{ "firstname":"Bob","firstname":"Bob", "lastname":"Singer""lastname":"Singer" }}
{{ "name":"Hilton Marriott","name":"Hilton Marriott","publishedDate":"2014-05-"publishedDate":"2014-05-
24T00:00:00.000Z"24T00:00:00.000Z"}}
June 2014
Response BodyResponse Body
Plan AheadPlan Ahead
Some Best Practices Some Best Practices
Indika Maligaspe
"Address":{"line1":"", "line2":"","city":"", "state":"",..."Address":{"line1":"", "line2":"","city":"", "state":"",... }}
VsVs
"Addresses":["Addresses":[ "Address":{ "type":"shipping","default":"true","line1":"", "line2":"","city":"","state":"",...}"Address":{ "type":"shipping","default":"true","line1":"", "line2":"","city":"","state":"",...} ]]
*** *** later is extensible for multiple types of addresslater is extensible for multiple types of address
June 2014
Response BodyResponse Body
Control work-flow via linksControl work-flow via links
Some Best Practices Some Best Practices
Indika Maligaspe
Instead of just Instead of just ““ID”:”H123456”ID”:”H123456”
Send where the resource is atSend where the resource is at “ “ID”:”H123456”,ID”:”H123456”, “ “link”:{link”:{
"href":"http://api.rezgateway.com/hotel/id/H123456""href":"http://api.rezgateway.com/hotel/id/H123456" }}
If data is to be submitted to a resource send that to client (Optional)If data is to be submitted to a resource send that to client (Optional)
"link":{ "link":{ "submit":"http://api..regateway.com/hotels/id/H123456/submit""submit":"http://api..regateway.com/hotels/id/H123456/submit" } }
June 2014
Response BodyResponse Body
Pagination – Control from server end.Pagination – Control from server end.
GET Hotels/h1GET Hotels/h1 200 OK200 OK
{{ "href":"http://api.rezgateway.com/hotels?offset=0&limit=25","href":"http://api.rezgateway.com/hotels?offset=0&limit=25",
"offset":0,"offset":0, "limit":25,"limit":25, "first":{"href":"api.rezgateway.com/hotels?offset=0&limit=25"},"first":{"href":"api.rezgateway.com/hotels?offset=0&limit=25"}, "previous":null,"previous":null,
"next":{"href":"api.rezgateway.com/hotels?offset=25&limit=50"},"next":{"href":"api.rezgateway.com/hotels?offset=25&limit=50"}, "last":{"href":"api.rezgateway.com//hotels?offset=550&limit=50"},"last":{"href":"api.rezgateway.com//hotels?offset=550&limit=50"},
…… }}
Some Best Practices Some Best Practices
Indika Maligaspe
*** Some NoSQL Db's do not have integer for offset and limit, in that case the *** Some NoSQL Db's do not have integer for offset and limit, in that case the links could be some key that you send depending on how you have your data links could be some key that you send depending on how you have your data stored.stored.
"next":{"href":"http://api.rezgateway.com/hotels?"next":{"href":"http://api.rezgateway.com/hotels?offset=xYs231&limit=zyt123"},offset=xYs231&limit=zyt123"},
"last":{"href":""last":{"href":"http://api.rezgateway.com/hotels?offset=xZa999&limit=xZb123""},&limit=xZb123""},
……........
June 2014
Response BodyResponse Body
Resource linking – Hypermedia is paramount and is fundamental when Resource linking – Hypermedia is paramount and is fundamental when talking with heterogeneous systems. XML has XLINK, JSON can use talking with heterogeneous systems. XML has XLINK, JSON can use HAL, SIREN etc...HAL, SIREN etc...
GET Hotels/h1GET Hotels/h1 200 OK200 OK {“href”:”http://api.rezgateway.com/Hotel/H123456”},{“href”:”http://api.rezgateway.com/Hotel/H123456”}, ……...,...,
……..,.., "groups":{"groups":{ "href":"http://api.rezgateway/com/groups/Marriott""href":"http://api.rezgateway/com/groups/Marriott" }}
Some Best Practices Some Best Practices
Indika Maligaspe
June 2014
Error Handling Error Handling
Do not send STATUS 200 for an error (intermediaries could cache)Do not send STATUS 200 for an error (intermediaries could cache)
Give all information neededGive all information needed
Your customers are Developers, so it should be easy for them Your customers are Developers, so it should be easy for them
POST /Hotels (if the hotel is already existing)POST /Hotels (if the hotel is already existing)
409 Conflict409 Conflict {{ "status": 409,"status": 409, "code":"REZ111","code":"REZ111", "message":"Hotel alreday existing","message":"Hotel alreday existing", "developerMessage":"Hotel under same name exist. Hotel created on ...","developerMessage":"Hotel under same name exist. Hotel created on ...", "moreInfo":"http://www.rezgateway.com/api/doc/errors/REZ111""moreInfo":"http://www.rezgateway.com/api/doc/errors/REZ111" }}
Some Best Practices Some Best Practices
Indika Maligaspe
June 2014
SecuritySecurity
Avoid Sessions – Authenticate every requestAvoid Sessions – Authenticate every request
Authorize based on content of data not URIAuthorize based on content of data not URI
Use existing Protocols like Oauth, Basic use SSLUse existing Protocols like Oauth, Basic use SSL
Use API keys instead of user Name / Pass Word. Use API keys instead of user Name / Pass Word.
Some Best Practices Some Best Practices
Indika Maligaspe
June 2014
CacheCache
Use ETags (Saves Bandwidth)Use ETags (Saves Bandwidth)
Some Best Practices Some Best Practices
Indika Maligaspe
Server – sends ETag in Content HeaderServer – sends ETag in Content Header Client - request Etag in Accept Header with “If-None-Match”Client - request Etag in Accept Header with “If-None-Match” Server – responds with status “304 Not Modified”Server – responds with status “304 Not Modified”
Server - Server - GET /Hotel/ID/H123456GET /Hotel/ID/H123456HTTP/1.1 200 OKHTTP/1.1 200 OKServer: ApacheServer: ApacheVary: Accept-EncodingVary: Accept-EncodingETag: "11c21b1f-73e4-4fa7550b501c0"ETag: "11c21b1f-73e4-4fa7550b501c0"
Client - Client - If-None-Match: "11c21b1f-73e4-4fa7550b501c0"If-None-Match: "11c21b1f-73e4-4fa7550b501c0"
Server - Server - GET /Hotel/ID/H123456GET /Hotel/ID/H123456HTTP/1.1 302 Not ModifiedHTTP/1.1 302 Not Modified
June 2014
MaintananceMaintanance
Use HTTP redirectsUse HTTP redirects
Create an abstract layer over endpoints (clients do not have to change)Create an abstract layer over endpoints (clients do not have to change)
Use well defined Media-Types Use well defined Media-Types
Some Best Practices Some Best Practices
Indika Maligaspe
June 2014
Indika Maligaspe
Thank You
Reservations Gateway Inc.Reservations Gateway Inc. YOUR LINK to e-TRAVEL SOLUTIONSYOUR LINK to e-TRAVEL SOLUTIONS
Reservations Gateway Inc.Reservations Gateway Inc.
11654 Plaza America Drive , Unit 645 Reston, Virginia 20190-4700
USA
703 286 5331703 433 0146 [email protected] www.rezgateway.com
Tel : Fax :
Email :Web :