REST full API Design

Christian Guenther
Christian GuentherChief Solution Architect at Comline AG em Comline AG
RESTFul API Design
Principles, Guidelines and Best Practices
Who am I
Christian Günther
Solution Architect
SAP / Non-SAP
Cloud Computing
NoSQL and Open
Source evangelist
Twitter: @siliconchris
The storyline behind
The company Microdolls Inc.
produces miniature action figures.
The company runs a website with
a web-shop, a doll-designer and
discussion boards.
The website is quite old and they
would like to redesign it.
They would also like to create a
mobile version of the shop and
the doll designer.
microdolls.com
Where imagination meets action
Current situation
The website and all offerings (such as the shopping cart, the doll designer
and the discussion board) is written in PHP
The backend is a MySQL database
Website and DB are directly coupled using embedded sql-statements in
the php-code
The designer consists of php-code that executes scripted ImageMagick
functions on the OS level to manipulate images and return the new image
to the browser
All in all the technical implementation is quite old, but it is not unlike many
other sites with a shop one can find on the internet
Current interaction model
Customers of microdolls.com open their browser and enter the shop’s url
The web server takes the browsers request (this of course being GET
www.microdolls.com/shop/index.php), possibly executes some php code and
returns plain html
The user’s browser then interpreted and renders the html code and presents the
visual representation of the site
Any element, which is not directly included in the html payload (such as images),
are retrieved through subsequent GET-requests with a URL pointing to the image
location on the server.
Issues with the current setup
There is no real separation (be it layered or otherwise) between the different technical
elements such as presentation, application and persistence - everything is very tightly
coupled.
This programming paradigm and the underlying architecture makes it extremely
difficult and time consuming to introduce new functionality.
Reuse of code is mainly done by duplicating needed functionality from one page in
another - that is to say, it is not really reused, but rather used again.
Changes to any element (be it shop, board, designer or database) need to be
thoroughly tested throughout the whole website and all areas.
To enter the mobile market, the company would need to re-create the whole website
with all functionality and would also need to implement new abstraction layers.
The conclusion
Instead of simply trying to
recreate the website on
mobile devices, the
company decides to
redesign their infrastructure
and programming model.
In essence, tear down the
monolithic php site and
establish a micro services
architecture
REST full API Design
SOAP? REST? THRIFT?
Like our fictional company microdolls.com, a lot of companies have designed their
applications in a very monolithic way (in the past, one has to say).
A monolith is an application which provides all of its services through a giant, singular
application. Due to the drawbacks of such an approach, the modern API development
architecture has been steadily moving towards micro services.
Unlike monolithic systems, Microservices deliver their functionality split between multiple,
separate applications and processes, and provide their functionality across multiple
servers when needed.
As Microservice development has grown, so has the need for more diverse and
extensible architecture designs.
There are basically two approaches (technologies) on how to create an API for a micro
services based architecture and one that is rather new: SOAP, REST and Apache THRIFT
SOAP - Simple Object Access Protocol
SOAP is an architectural concept that was created in 1998 by Dave Winer, Don
Box, and Bob Atkinson, in collaboration with Microsoft.
Designed explicitly for the purpose of making communication between web
services easier, SOAP has four main characteristics that made it so popular in
its infancy:
Extensibility through user generated extensions tying into the base
structure;
Neutrality by operating over any transport protocol;
Independence by allowing variable programming paradigms and structures;
Large Data Handling through asynchron calls to conversions, calculations,
etc.
REST - Representational State Transfer
REST was created in 2000 by Roy Fielding in UC, Irvine; later versions of
this architecture were created in collaboration with the W3C Technical
Architecture Group.
While SOAP aimed to be a complete system, REST was designed to be
more lightweight for building the following right into the design;
Scalability by using cached data from the client and intermediate
nodes built into HTTP to self-define;
Portability by tying the transfer of data to the program code during
transfer;
Extensibility by allowing individual elements of the greater network to
develop independent of one another, using uniform interfaces.
Apache THRIFT
Thrift, in 2007 designed by Facebook, was soon released as an open source project under
the Apache Software Foundation label.
The architecture, designed specifically to compete with SOAP and REST while delivering data
quickly in a number of formats, includes a complete stack for the manufacture, maintenance,
and expansion of clients and servers.
The system was designed specifically to include:
Scalability by supporting cross-language services seamlessly between C#, C++,
Cappuccino, Cocoa, Haskell, and more
Simplicity by eschewing the frameworks of REST and the XML of SOAP in favor of a
simple library
Speed by utilizing binary serialization to handle data
Evolution by allowing for soft versioning, supporting third party teams to develop RPC
calls as needed
Text
REST in Peace SOAP
REST vs SOAP: Simplicity wins, again
REST vs SOAP
REST is not always better than SOAP
There are circumstances, where a SOAP-based approach could
be preferable over REST
Those situations, however, are scarce to find
Eg, if you need highly coupled applications, build by your own or
your co-team, you could use SOAP, but
in general, if you build an API that is to be consumed by clients
outside your company or application domain, NEVER use SOAP
What is REST?
REST = Representational State Transfer is an architectural
style and programming paradigm for distributed systems,
especially (but not necessarily only) those found in
applications running on the world wide web
REST gives a coordinated set of constraints to the design of
components in a distributed hypermedia system that can lead
to a higher-performing and more maintainable architecture
To the extent that systems conform to the constraints of
REST they can be called RESTful.
What is REST?
RESTful systems typically, but not always, communicate over
HTTP with the same HTTP verbs (this being GET, POST, PUT
and DELETE) used by a web browser that access a web page
REST interfaces with external systems using resources
identified by a URI which can be operated upon using the
named standard verbs
REST demands that the response to a resource-request must
always return the same content regardless how many times
the URI was accessed
The idea behind REST
With REST the idea is that, rather than using complex
mechanisms such as CORBA, RPC or SOAP to connect
between clients and servers, simple HTTP queries are
used. 
RESTful applications use HTTP requests to POST data
(create), PUT data (update), GET data (make queries),
and DELETE, to delete data on the server.
Thus, REST uses HTTP for all four CRUD (Create/Read/
Update/Delete) operations
The idea behind REST
For example, if a client application wants to get information on the action figure
Neo, it sends our API server an HTTP GET with the URL:
Using jQuery we can implement this AJAX request in our client application simply
like this:
The HTTP reply our server sends back to the client is the raw result data — not
embedded inside an HTML page, not XML-encoded, just the data you need in a
way you can immediately use – a String or a JSON object you can use directly.
$.getJSON("http://microdolls.com/dolls/neo",
function(data) {
console.log("The Action figure neo fancies "+data );
});
http://microdolls.com/dolls/neo
The idea behind REST
REST can easily handle more complex requests, including multiple
parameters. In most cases, you’ll just use HTTP GET parameters in
the URL.
For example, if a specific doll can only uniquely specified by both
template and sex, our API might accept a request like this:
As a convention (although I’d rather see this as a strict guideline),
HTTP GET requests should be for read-only queries; GET should not
change the state of the server and its data. For creation, updating,
and deleting data, use POST, PUT and DELETE requests.
http://microdolls/dolls/?template=matrix&sex=male
WHAT is a RESTFul API?
Short Answer: „A RESTFul API is one that exposes it’s
services in a way that complies to the principles of
REST“
WHAT is a RESTFul API?
The long answer is this: A RESTFul API is one, that can be
consumed by a system, in the same intuitive way a user
consumes and uses a website.
A user does not need to know the structure of a website prior
using it. He/She will learn about the site’s structure along the
way, simply by following presented navigation links (URLs)
A RESTFul API provides the same smooth consumption
pattern. A system connecting to your API the first time, will learn
about the internal structure of the API by navigating the API’s
response
RESTFul API
Guidelines on RESTFul API Design
RESTFul API Design
HTTP is your driver
GET never changes an objects state
Use nouns instead of verbs
Always use plural
Use sub-locations for relations
Use grouping, if applicable
HTTP headers contain the serialization format
Use HATEOAS
Provide operations for collections
Version your API
Transport Errors as HTTP Return Codes
Allow overriding of HTTP methods
HTTP is your driver
Although this should be rather obvious:
A RESTFul API relies entirely on HTTP
All operations on exposed objects are done through well defined
methods
GET - retrieves an object, a collection or displays specific data
POST - creates an object
PUT - updates an object (or a predefined collection of objects)
DELETE - hm? any guess?
GET never changes state
More precisely GET method and query parameters should not
alter the state of an object or data
Use PUT, POST and DELETE methods instead of the GET
method to alter the state.
Do not use GET for state changes:
GET /users/711?activate
or
GET /users/711/activate Nooooooooh!!!
Use nouns instead of verbs
For easy readability nouns are always preferable over verbs.
After all, your API will expose an object as first citizen.
The methods to alter or work with your object are of second concern - the are
implemented using standard HTTP methods.
Therefore never use anything like these:
/getAllUser
but always use the simple
/users
along with a GET/POST/PUT/DELETE HTTP Method
Use plural nouns
As well for easy readability always use plurals
Do not mix up singular and plural nouns. Keep it simple and
use only plural nouns for all resources.
/cars instead of /car
/users instead of /user
/products instead of /product
/settings instead of /setting
Use sub-locations for relations
If a resource is related to another resource use sub-
resources.
GET /cars/711/drivers/
Returns a list of drivers for car 711
GET /cars/711/drivers/4
Returns driver #4 for car 711
Use grouping, if applicable
Identify common or shared properties:
Is there something you can group in a domain specific
context? Something that is shared by most or at least
a majority of objects/services?
Create an abstract class (if we talk of objects) or a
group (if we talk of a service) and apply the shared
property to it - then derive your class from the abstract
class or put your services in that group, respectively.
HTTP headers contain the
serialization format
Both, client and server, need to know which format is
used for the communication.
The format has to be specified in the HTTP-Header.
Content-Type defines the request format.
Accept defines a list of acceptable response formats.
Use HATEOAS
HATEOAS = Hypermedia As The Engine Of Application
State is a principle that hypertext links should be used
to create a better navigation through the API.
In essence that means, in an API designed after the
HATEOAS principle, a client will be able to navigate
through the API by following URLs and links provided
by the server - this is much the same, as a user
navigating through a website by following links on that
site.
As this is a bit of a complicated topic, a more in deep description is provided within this presentation
Provide operations for
collections
Filtering - filter a return list
Sorting - sort a collection
Field Selection - select fields
Paging - display a limited set of resources per query
Filtering
Use a unique query parameter for all fields or a query
language for filtering.
To return a list of alien action figures
GET /dolls?family=alien
To return a list of action figures with a maximum of 2
heads
GET /dolls?heads<=2
Sorting
Allow ascending and descending sorting over multiple
fields.
To return a list of action figures sorted by descending
manufacturers and ascending models.
GET /dolls?sort=-manufactorer,+model
Field Selection
Mobile clients display just a few attributes in a list.
They don’t need all attributes of a resource.
Give the API consumer the ability to choose returned fields.
This will also reduce the network traffic and speed up the
usage of the API.
GET /dolls?
fields=manufacturer,model,id,family
Paging
Use limit and offset. It is flexible for the user and common in leading databases. The
default should be limit=20 and offset=0
GET /dolls?offset=10&limit=5
To send the total entries back to the user use the custom HTTP header: X-Total-
Count.
Links to the next or previous page should be provided in the HTTP header link as well.
It is important to follow this link header values instead of constructing your own URLs.
<https://blog.microdolls.com/catalog/api/v1/dolls?offset=15&limit=5>; rel=„next",
<https://blog.microdolls.com/catalog/api/v1/dolls?offset=50&limit=3>; rel=„last",
<https://blog.microdolls.com/catalog/api/v1/dolls?offset=0&limit=5>; rel=„first",
<https://blog.microdolls.com/catalog/api/v1/dolls?offset=5&limit=5>; rel="prev",
Version your API
Make the API Version mandatory and do not release an unversioned API.
Decide on your API versioning scheme - simple ordinals or year plus
month or the like. It doesn’t really matter, but stick to it for all your APIs
within a domain and/or application system
If using numbers, use simple ordinal number and avoid dot notation such
as 2.5.
Finally it is common sense to prefix the url for the API versioning with the
letter „v“
/catalog/api/v1
Transport errors as HTTP
status codes
It is hard to work with an API that ignores error
handling.
Pure returning of a HTTP 500 with a stacktrace is not
very helpful.
Also, inventing new meanings to established http status
codes makes using your API a nightmare on elm street
Instead use standard HTTP status codes
Use HTTP status codes
The HTTP standard provides over 70 status codes to describe
the return values.
Use these 4 codes for successful requests
200 – OK – Here is your result
201 – OK – New resource was created / resource was updated
204 – OK – The resource was successfully deleted
304 – Not Modified – The client can use cached data
HTTP error status codes
Use these 5 codes for failed requests
400 – Bad Request – The request was invalid or cannot be served. The exact
error should be explained in the error payload. E.g. „The JSON is not valid“
401 – Unauthorized – The request requires an user authentication
403 – Forbidden – The server understood the request, but is refusing it or the
access is not allowed.
404 – Not found – There is no resource behind the URI.
422 – Unprocessable Entity – Should be used if the server cannot process the
enitity, e.g. if an image cannot be formatted or mandatory fields are missing in
the payload.
HTTP 500
API developers should avoid this error in normal
situation and use specific error codes (as shown in the
previous slide).
If an error occurs in the global catch blog (bad luck),
the stracktrace should be logged and not returned as
response.
500 – Internal Server Error
Use error payloads
All exceptions should be mapped in an error payload.
Here is an example how a JSON payload should look
like.
04 "userMessage": "Sorry, the requested resource
does not exist“,
05 "internalMessage": "No doll found in the
database",
Allow overriding HTTP
methods
Some proxies support only POST and GET methods.
To support a RESTful API with these limitations, the API
needs a way to override the HTTP method.
Use the custom HTTP Header X-HTTP-Method-
Override to override the POST Method.
1 de 43

Recomendados

Rest API por
Rest APIRest API
Rest APIRohana K Amarakoon
5.5K visualizações61 slides
What is REST API? REST API Concepts and Examples | Edureka por
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaEdureka!
1.6K visualizações23 slides
Understanding REST APIs in 5 Simple Steps por
Understanding REST APIs in 5 Simple StepsUnderstanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple StepsTessa Mero
5K visualizações29 slides
API for Beginners por
API for BeginnersAPI for Beginners
API for BeginnersGustavo De Vita
8.7K visualizações69 slides
Understanding REST por
Understanding RESTUnderstanding REST
Understanding RESTNitin Pande
6.4K visualizações9 slides
REST API Design & Development por
REST API Design & DevelopmentREST API Design & Development
REST API Design & DevelopmentAshok Pundit
1.2K visualizações26 slides

Mais conteúdo relacionado

Mais procurados

Web API authentication and authorization por
Web API authentication and authorization Web API authentication and authorization
Web API authentication and authorization Chalermpon Areepong
781 visualizações20 slides
Introduction to API por
Introduction to APIIntroduction to API
Introduction to APIrajnishjha29
2.1K visualizações15 slides
Introduction to REST - API por
Introduction to REST - APIIntroduction to REST - API
Introduction to REST - APIChetan Gadodia
1.1K visualizações13 slides
ReST (Representational State Transfer) Explained por
ReST (Representational State Transfer) ExplainedReST (Representational State Transfer) Explained
ReST (Representational State Transfer) ExplainedDhananjay Nene
21.9K visualizações192 slides
RESTful Web Services por
RESTful Web ServicesRESTful Web Services
RESTful Web ServicesChristopher Bartling
34.7K visualizações38 slides
What is an API por
What is an APIWhat is an API
What is an APIElliott Richmond
657 visualizações33 slides

Mais procurados(20)

Web API authentication and authorization por Chalermpon Areepong
Web API authentication and authorization Web API authentication and authorization
Web API authentication and authorization
Chalermpon Areepong781 visualizações
Introduction to API por rajnishjha29
Introduction to APIIntroduction to API
Introduction to API
rajnishjha292.1K visualizações
Introduction to REST - API por Chetan Gadodia
Introduction to REST - APIIntroduction to REST - API
Introduction to REST - API
Chetan Gadodia1.1K visualizações
ReST (Representational State Transfer) Explained por Dhananjay Nene
ReST (Representational State Transfer) ExplainedReST (Representational State Transfer) Explained
ReST (Representational State Transfer) Explained
Dhananjay Nene21.9K visualizações
RESTful Web Services por Christopher Bartling
RESTful Web ServicesRESTful Web Services
RESTful Web Services
Christopher Bartling34.7K visualizações
What is an API por Elliott Richmond
What is an APIWhat is an API
What is an API
Elliott Richmond657 visualizações
Introduction to the Web API por Brad Genereaux
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
Brad Genereaux14.5K visualizações
API Best Practices por Sai Koppala
API Best PracticesAPI Best Practices
API Best Practices
Sai Koppala850 visualizações
Api Testing por Vishwanath KC
Api TestingApi Testing
Api Testing
Vishwanath KC560 visualizações
Introdução APIs RESTful por Douglas V. Pasqua
Introdução APIs RESTfulIntrodução APIs RESTful
Introdução APIs RESTful
Douglas V. Pasqua1.2K visualizações
REST API and CRUD por Prem Sanil
REST API and CRUDREST API and CRUD
REST API and CRUD
Prem Sanil155.9K visualizações
Design Beautiful REST + JSON APIs por Stormpath
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
Stormpath225.9K visualizações
Api-First service design por Stefaan Ponnet
Api-First service designApi-First service design
Api-First service design
Stefaan Ponnet1.3K visualizações
Restful api design por Mizan Riqzia
Restful api designRestful api design
Restful api design
Mizan Riqzia1.5K visualizações
Building APIs with the OpenApi Spec por Pedro J. Molina
Building APIs with the OpenApi SpecBuilding APIs with the OpenApi Spec
Building APIs with the OpenApi Spec
Pedro J. Molina1K visualizações
Restful Web Services por Angelin R
Restful Web ServicesRestful Web Services
Restful Web Services
Angelin R12.3K visualizações
API Governance in the Enterprise por Apigee | Google Cloud
API Governance in the EnterpriseAPI Governance in the Enterprise
API Governance in the Enterprise
Apigee | Google Cloud18K visualizações
Effective API Lifecycle Management por SmartBear
Effective API Lifecycle Management Effective API Lifecycle Management
Effective API Lifecycle Management
SmartBear1.2K visualizações
An Introduction To REST API por Aniruddh Bhilvare
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
Aniruddh Bhilvare25.1K visualizações

Destaque

[S lide] java_sig-spring-framework por
[S lide] java_sig-spring-framework[S lide] java_sig-spring-framework
[S lide] java_sig-spring-frameworkptlong96
2K visualizações72 slides
Aspgems tensor-flow example por
Aspgems   tensor-flow exampleAspgems   tensor-flow example
Aspgems tensor-flow exampleJuantomás García Molina
1.4K visualizações30 slides
11 APIs (Adam Du Vander) por
11 APIs (Adam Du Vander)11 APIs (Adam Du Vander)
11 APIs (Adam Du Vander)Future Insights
15.2K visualizações55 slides
RESTful API Design Best Practices Using ASP.NET Web API por
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💻 Spencer Schneidenbach
8.2K visualizações69 slides
SAP API Business Hub - SAP Community Webinar por
SAP API Business Hub - SAP Community Webinar SAP API Business Hub - SAP Community Webinar
SAP API Business Hub - SAP Community Webinar Harsh Jegadeesan
1.2K visualizações18 slides
SAP TechEd 2015 INT103 Enabling Digital Transformation with APIs and SAP API... por
SAP TechEd  2015 INT103 Enabling Digital Transformation with APIs and SAP API...SAP TechEd  2015 INT103 Enabling Digital Transformation with APIs and SAP API...
SAP TechEd 2015 INT103 Enabling Digital Transformation with APIs and SAP API...Harsh Jegadeesan
1.9K visualizações31 slides

Destaque(7)

[S lide] java_sig-spring-framework por ptlong96
[S lide] java_sig-spring-framework[S lide] java_sig-spring-framework
[S lide] java_sig-spring-framework
ptlong962K visualizações
11 APIs (Adam Du Vander) por Future Insights
11 APIs (Adam Du Vander)11 APIs (Adam Du Vander)
11 APIs (Adam Du Vander)
Future Insights15.2K visualizações
RESTful API Design Best Practices Using ASP.NET Web API por 💻 Spencer Schneidenbach
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
💻 Spencer Schneidenbach8.2K visualizações
SAP API Business Hub - SAP Community Webinar por Harsh Jegadeesan
SAP API Business Hub - SAP Community Webinar SAP API Business Hub - SAP Community Webinar
SAP API Business Hub - SAP Community Webinar
Harsh Jegadeesan1.2K visualizações
SAP TechEd 2015 INT103 Enabling Digital Transformation with APIs and SAP API... por Harsh Jegadeesan
SAP TechEd  2015 INT103 Enabling Digital Transformation with APIs and SAP API...SAP TechEd  2015 INT103 Enabling Digital Transformation with APIs and SAP API...
SAP TechEd 2015 INT103 Enabling Digital Transformation with APIs and SAP API...
Harsh Jegadeesan1.9K visualizações
SAP API Management and API Business Hub (TechEd Barcelona) por Harsh Jegadeesan
SAP API Management and API Business Hub (TechEd Barcelona)SAP API Management and API Business Hub (TechEd Barcelona)
SAP API Management and API Business Hub (TechEd Barcelona)
Harsh Jegadeesan2.9K visualizações

Similar a REST full API Design

Talking to 25% of the web - In-depth report and analysis on the WordPress RES... por
Talking to 25% of the web - In-depth report and analysis on the WordPress RES...Talking to 25% of the web - In-depth report and analysis on the WordPress RES...
Talking to 25% of the web - In-depth report and analysis on the WordPress RES...Stephane Beladaci
1.2K visualizações45 slides
Rest api best practices – comprehensive handbook por
Rest api best practices – comprehensive handbookRest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbookKaty Slemon
91 visualizações44 slides
RESTful applications: The why and how by Maikel Mardjan por
RESTful applications: The why and how by Maikel MardjanRESTful applications: The why and how by Maikel Mardjan
RESTful applications: The why and how by Maikel MardjanJexia
492 visualizações25 slides
PPT - A slice of cake php por
PPT - A slice of cake phpPPT - A slice of cake php
PPT - A slice of cake phpKonstant Infosolutions Pvt. Ltd.
3.6K visualizações21 slides
Fundamentals of Web Development For Non-Developers por
Fundamentals of Web Development For Non-DevelopersFundamentals of Web Development For Non-Developers
Fundamentals of Web Development For Non-DevelopersLemi Orhan Ergin
64.2K visualizações42 slides
Website and it's importance por
Website and it's importanceWebsite and it's importance
Website and it's importanceRobinSingh347
40 visualizações5 slides

Similar a REST full API Design(20)

Talking to 25% of the web - In-depth report and analysis on the WordPress RES... por Stephane Beladaci
Talking to 25% of the web - In-depth report and analysis on the WordPress RES...Talking to 25% of the web - In-depth report and analysis on the WordPress RES...
Talking to 25% of the web - In-depth report and analysis on the WordPress RES...
Stephane Beladaci1.2K visualizações
Rest api best practices – comprehensive handbook por Katy Slemon
Rest api best practices – comprehensive handbookRest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbook
Katy Slemon91 visualizações
RESTful applications: The why and how by Maikel Mardjan por Jexia
RESTful applications: The why and how by Maikel MardjanRESTful applications: The why and how by Maikel Mardjan
RESTful applications: The why and how by Maikel Mardjan
Jexia492 visualizações
Fundamentals of Web Development For Non-Developers por Lemi Orhan Ergin
Fundamentals of Web Development For Non-DevelopersFundamentals of Web Development For Non-Developers
Fundamentals of Web Development For Non-Developers
Lemi Orhan Ergin64.2K visualizações
Website and it's importance por RobinSingh347
Website and it's importanceWebsite and it's importance
Website and it's importance
RobinSingh34740 visualizações
Secc tutorials development and deployment of rest web services in java_v2.0 por Aravindharamanan S
Secc tutorials development and deployment of rest web services in java_v2.0Secc tutorials development and deployment of rest web services in java_v2.0
Secc tutorials development and deployment of rest web services in java_v2.0
Aravindharamanan S123 visualizações
Things you must know on ruby on rails single page application por Andolasoft Inc
Things you must know on ruby on rails single page applicationThings you must know on ruby on rails single page application
Things you must know on ruby on rails single page application
Andolasoft Inc99 visualizações
sMash_for_zOS-users por Otto Kee LeakPeng
sMash_for_zOS-userssMash_for_zOS-users
sMash_for_zOS-users
Otto Kee LeakPeng2K visualizações
REST: So What's It All About? (SAP TechEd 2011, MOB107) por Sascha Wenninger
REST: So What's It All About? (SAP TechEd 2011, MOB107)REST: So What's It All About? (SAP TechEd 2011, MOB107)
REST: So What's It All About? (SAP TechEd 2011, MOB107)
Sascha Wenninger3.7K visualizações
REST & RESTful APIs: The State of Confusion por Glenn Antoine
REST & RESTful APIs: The State of ConfusionREST & RESTful APIs: The State of Confusion
REST & RESTful APIs: The State of Confusion
Glenn Antoine4.2K visualizações
zendframework2 restful por tom_li
zendframework2 restfulzendframework2 restful
zendframework2 restful
tom_li424 visualizações
Overview of Rest Service and ASP.NET WEB API por Pankaj Bajaj
Overview of Rest Service and ASP.NET WEB APIOverview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB API
Pankaj Bajaj2K visualizações
APIs Design - Creation - Management.pdf por WilliamELKAIMPhd
APIs Design - Creation - Management.pdfAPIs Design - Creation - Management.pdf
APIs Design - Creation - Management.pdf
WilliamELKAIMPhd22 visualizações
IRJET- Rest API for E-Commerce Site por IRJET Journal
IRJET- Rest API for E-Commerce SiteIRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce Site
IRJET Journal30 visualizações
Cics Web 2.0 With Atom Feeds And Php por CICS ROADSHOW
Cics Web 2.0 With Atom Feeds And PhpCics Web 2.0 With Atom Feeds And Php
Cics Web 2.0 With Atom Feeds And Php
CICS ROADSHOW2.6K visualizações
REST - What's It All About? (SAP TechEd 2012, CD110) por Sascha Wenninger
REST - What's It All About? (SAP TechEd 2012, CD110)REST - What's It All About? (SAP TechEd 2012, CD110)
REST - What's It All About? (SAP TechEd 2012, CD110)
Sascha Wenninger1.8K visualizações
Web 2 0 Fullfeatures por vsnmurthy
Web 2 0 FullfeaturesWeb 2 0 Fullfeatures
Web 2 0 Fullfeatures
vsnmurthy428 visualizações

Último

HarshithAkkapelli_Presentation.pdf por
HarshithAkkapelli_Presentation.pdfHarshithAkkapelli_Presentation.pdf
HarshithAkkapelli_Presentation.pdfharshithakkapelli
12 visualizações16 slides
Myths and Facts About Hospice Care: Busting Common Misconceptions por
Myths and Facts About Hospice Care: Busting Common MisconceptionsMyths and Facts About Hospice Care: Busting Common Misconceptions
Myths and Facts About Hospice Care: Busting Common MisconceptionsCare Coordinations
6 visualizações1 slide
Fleet Management Software in India por
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India Fleetable
12 visualizações1 slide
tecnologia18.docx por
tecnologia18.docxtecnologia18.docx
tecnologia18.docxnosi6702
5 visualizações5 slides
Agile 101 por
Agile 101Agile 101
Agile 101John Valentino
9 visualizações20 slides
FOSSLight Community Day 2023-11-30 por
FOSSLight Community Day 2023-11-30FOSSLight Community Day 2023-11-30
FOSSLight Community Day 2023-11-30Shane Coughlan
5 visualizações18 slides

Último(20)

HarshithAkkapelli_Presentation.pdf por harshithakkapelli
HarshithAkkapelli_Presentation.pdfHarshithAkkapelli_Presentation.pdf
HarshithAkkapelli_Presentation.pdf
harshithakkapelli12 visualizações
Myths and Facts About Hospice Care: Busting Common Misconceptions por Care Coordinations
Myths and Facts About Hospice Care: Busting Common MisconceptionsMyths and Facts About Hospice Care: Busting Common Misconceptions
Myths and Facts About Hospice Care: Busting Common Misconceptions
Care Coordinations6 visualizações
Fleet Management Software in India por Fleetable
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India
Fleetable12 visualizações
tecnologia18.docx por nosi6702
tecnologia18.docxtecnologia18.docx
tecnologia18.docx
nosi67025 visualizações
Agile 101 por John Valentino
Agile 101Agile 101
Agile 101
John Valentino9 visualizações
FOSSLight Community Day 2023-11-30 por Shane Coughlan
FOSSLight Community Day 2023-11-30FOSSLight Community Day 2023-11-30
FOSSLight Community Day 2023-11-30
Shane Coughlan5 visualizações
The Path to DevOps por John Valentino
The Path to DevOpsThe Path to DevOps
The Path to DevOps
John Valentino5 visualizações
nintendo_64.pptx por paiga02016
nintendo_64.pptxnintendo_64.pptx
nintendo_64.pptx
paiga020165 visualizações
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P... por NimaTorabi2
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
NimaTorabi215 visualizações
Introduction to Git Source Control por John Valentino
Introduction to Git Source ControlIntroduction to Git Source Control
Introduction to Git Source Control
John Valentino5 visualizações
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra... por Marc Müller
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra....NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
Marc Müller41 visualizações
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated... por TomHalpin9
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
TomHalpin96 visualizações
ShortStory_qlora.pptx por pranathikrishna22
ShortStory_qlora.pptxShortStory_qlora.pptx
ShortStory_qlora.pptx
pranathikrishna225 visualizações
Software evolution understanding: Automatic extraction of software identifier... por Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...
Ra'Fat Al-Msie'deen10 visualizações
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports por Ra'Fat Al-Msie'deen
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug ReportsBushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
Ra'Fat Al-Msie'deen8 visualizações
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with... por sparkfabrik
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
sparkfabrik8 visualizações
FIMA 2023 Neo4j & FS - Entity Resolution.pptx por Neo4j
FIMA 2023 Neo4j & FS - Entity Resolution.pptxFIMA 2023 Neo4j & FS - Entity Resolution.pptx
FIMA 2023 Neo4j & FS - Entity Resolution.pptx
Neo4j12 visualizações
WebAssembly por Jens Siebert
WebAssemblyWebAssembly
WebAssembly
Jens Siebert52 visualizações
EV Charging App Case por iCoderz Solutions
EV Charging App Case EV Charging App Case
EV Charging App Case
iCoderz Solutions8 visualizações

REST full API Design

  • 1. RESTFul API Design Principles, Guidelines and Best Practices
  • 2. Who am I Christian Günther Solution Architect SAP / Non-SAP Cloud Computing NoSQL and Open Source evangelist Twitter: @siliconchris
  • 3. The storyline behind The company Microdolls Inc. produces miniature action figures. The company runs a website with a web-shop, a doll-designer and discussion boards. The website is quite old and they would like to redesign it. They would also like to create a mobile version of the shop and the doll designer. microdolls.com Where imagination meets action
  • 4. Current situation The website and all offerings (such as the shopping cart, the doll designer and the discussion board) is written in PHP The backend is a MySQL database Website and DB are directly coupled using embedded sql-statements in the php-code The designer consists of php-code that executes scripted ImageMagick functions on the OS level to manipulate images and return the new image to the browser All in all the technical implementation is quite old, but it is not unlike many other sites with a shop one can find on the internet
  • 5. Current interaction model Customers of microdolls.com open their browser and enter the shop’s url The web server takes the browsers request (this of course being GET www.microdolls.com/shop/index.php), possibly executes some php code and returns plain html The user’s browser then interpreted and renders the html code and presents the visual representation of the site Any element, which is not directly included in the html payload (such as images), are retrieved through subsequent GET-requests with a URL pointing to the image location on the server.
  • 6. Issues with the current setup There is no real separation (be it layered or otherwise) between the different technical elements such as presentation, application and persistence - everything is very tightly coupled. This programming paradigm and the underlying architecture makes it extremely difficult and time consuming to introduce new functionality. Reuse of code is mainly done by duplicating needed functionality from one page in another - that is to say, it is not really reused, but rather used again. Changes to any element (be it shop, board, designer or database) need to be thoroughly tested throughout the whole website and all areas. To enter the mobile market, the company would need to re-create the whole website with all functionality and would also need to implement new abstraction layers.
  • 7. The conclusion Instead of simply trying to recreate the website on mobile devices, the company decides to redesign their infrastructure and programming model. In essence, tear down the monolithic php site and establish a micro services architecture
  • 9. SOAP? REST? THRIFT? Like our fictional company microdolls.com, a lot of companies have designed their applications in a very monolithic way (in the past, one has to say). A monolith is an application which provides all of its services through a giant, singular application. Due to the drawbacks of such an approach, the modern API development architecture has been steadily moving towards micro services. Unlike monolithic systems, Microservices deliver their functionality split between multiple, separate applications and processes, and provide their functionality across multiple servers when needed. As Microservice development has grown, so has the need for more diverse and extensible architecture designs. There are basically two approaches (technologies) on how to create an API for a micro services based architecture and one that is rather new: SOAP, REST and Apache THRIFT
  • 10. SOAP - Simple Object Access Protocol SOAP is an architectural concept that was created in 1998 by Dave Winer, Don Box, and Bob Atkinson, in collaboration with Microsoft. Designed explicitly for the purpose of making communication between web services easier, SOAP has four main characteristics that made it so popular in its infancy: Extensibility through user generated extensions tying into the base structure; Neutrality by operating over any transport protocol; Independence by allowing variable programming paradigms and structures; Large Data Handling through asynchron calls to conversions, calculations, etc.
  • 11. REST - Representational State Transfer REST was created in 2000 by Roy Fielding in UC, Irvine; later versions of this architecture were created in collaboration with the W3C Technical Architecture Group. While SOAP aimed to be a complete system, REST was designed to be more lightweight for building the following right into the design; Scalability by using cached data from the client and intermediate nodes built into HTTP to self-define; Portability by tying the transfer of data to the program code during transfer; Extensibility by allowing individual elements of the greater network to develop independent of one another, using uniform interfaces.
  • 12. Apache THRIFT Thrift, in 2007 designed by Facebook, was soon released as an open source project under the Apache Software Foundation label. The architecture, designed specifically to compete with SOAP and REST while delivering data quickly in a number of formats, includes a complete stack for the manufacture, maintenance, and expansion of clients and servers. The system was designed specifically to include: Scalability by supporting cross-language services seamlessly between C#, C++, Cappuccino, Cocoa, Haskell, and more Simplicity by eschewing the frameworks of REST and the XML of SOAP in favor of a simple library Speed by utilizing binary serialization to handle data Evolution by allowing for soft versioning, supporting third party teams to develop RPC calls as needed
  • 13. Text REST in Peace SOAP REST vs SOAP: Simplicity wins, again
  • 14. REST vs SOAP REST is not always better than SOAP There are circumstances, where a SOAP-based approach could be preferable over REST Those situations, however, are scarce to find Eg, if you need highly coupled applications, build by your own or your co-team, you could use SOAP, but in general, if you build an API that is to be consumed by clients outside your company or application domain, NEVER use SOAP
  • 15. What is REST? REST = Representational State Transfer is an architectural style and programming paradigm for distributed systems, especially (but not necessarily only) those found in applications running on the world wide web REST gives a coordinated set of constraints to the design of components in a distributed hypermedia system that can lead to a higher-performing and more maintainable architecture To the extent that systems conform to the constraints of REST they can be called RESTful.
  • 16. What is REST? RESTful systems typically, but not always, communicate over HTTP with the same HTTP verbs (this being GET, POST, PUT and DELETE) used by a web browser that access a web page REST interfaces with external systems using resources identified by a URI which can be operated upon using the named standard verbs REST demands that the response to a resource-request must always return the same content regardless how many times the URI was accessed
  • 17. The idea behind REST With REST the idea is that, rather than using complex mechanisms such as CORBA, RPC or SOAP to connect between clients and servers, simple HTTP queries are used.  RESTful applications use HTTP requests to POST data (create), PUT data (update), GET data (make queries), and DELETE, to delete data on the server. Thus, REST uses HTTP for all four CRUD (Create/Read/ Update/Delete) operations
  • 18. The idea behind REST For example, if a client application wants to get information on the action figure Neo, it sends our API server an HTTP GET with the URL: Using jQuery we can implement this AJAX request in our client application simply like this: The HTTP reply our server sends back to the client is the raw result data — not embedded inside an HTML page, not XML-encoded, just the data you need in a way you can immediately use – a String or a JSON object you can use directly. $.getJSON("http://microdolls.com/dolls/neo", function(data) { console.log("The Action figure neo fancies "+data ); }); http://microdolls.com/dolls/neo
  • 19. The idea behind REST REST can easily handle more complex requests, including multiple parameters. In most cases, you’ll just use HTTP GET parameters in the URL. For example, if a specific doll can only uniquely specified by both template and sex, our API might accept a request like this: As a convention (although I’d rather see this as a strict guideline), HTTP GET requests should be for read-only queries; GET should not change the state of the server and its data. For creation, updating, and deleting data, use POST, PUT and DELETE requests. http://microdolls/dolls/?template=matrix&sex=male
  • 20. WHAT is a RESTFul API? Short Answer: „A RESTFul API is one that exposes it’s services in a way that complies to the principles of REST“
  • 21. WHAT is a RESTFul API? The long answer is this: A RESTFul API is one, that can be consumed by a system, in the same intuitive way a user consumes and uses a website. A user does not need to know the structure of a website prior using it. He/She will learn about the site’s structure along the way, simply by following presented navigation links (URLs) A RESTFul API provides the same smooth consumption pattern. A system connecting to your API the first time, will learn about the internal structure of the API by navigating the API’s response
  • 22. RESTFul API Guidelines on RESTFul API Design
  • 23. RESTFul API Design HTTP is your driver GET never changes an objects state Use nouns instead of verbs Always use plural Use sub-locations for relations Use grouping, if applicable HTTP headers contain the serialization format Use HATEOAS Provide operations for collections Version your API Transport Errors as HTTP Return Codes Allow overriding of HTTP methods
  • 24. HTTP is your driver Although this should be rather obvious: A RESTFul API relies entirely on HTTP All operations on exposed objects are done through well defined methods GET - retrieves an object, a collection or displays specific data POST - creates an object PUT - updates an object (or a predefined collection of objects) DELETE - hm? any guess?
  • 25. GET never changes state More precisely GET method and query parameters should not alter the state of an object or data Use PUT, POST and DELETE methods instead of the GET method to alter the state. Do not use GET for state changes: GET /users/711?activate or GET /users/711/activate Nooooooooh!!!
  • 26. Use nouns instead of verbs For easy readability nouns are always preferable over verbs. After all, your API will expose an object as first citizen. The methods to alter or work with your object are of second concern - the are implemented using standard HTTP methods. Therefore never use anything like these: /getAllUser but always use the simple /users along with a GET/POST/PUT/DELETE HTTP Method
  • 27. Use plural nouns As well for easy readability always use plurals Do not mix up singular and plural nouns. Keep it simple and use only plural nouns for all resources. /cars instead of /car /users instead of /user /products instead of /product /settings instead of /setting
  • 28. Use sub-locations for relations If a resource is related to another resource use sub- resources. GET /cars/711/drivers/ Returns a list of drivers for car 711 GET /cars/711/drivers/4 Returns driver #4 for car 711
  • 29. Use grouping, if applicable Identify common or shared properties: Is there something you can group in a domain specific context? Something that is shared by most or at least a majority of objects/services? Create an abstract class (if we talk of objects) or a group (if we talk of a service) and apply the shared property to it - then derive your class from the abstract class or put your services in that group, respectively.
  • 30. HTTP headers contain the serialization format Both, client and server, need to know which format is used for the communication. The format has to be specified in the HTTP-Header. Content-Type defines the request format. Accept defines a list of acceptable response formats.
  • 31. Use HATEOAS HATEOAS = Hypermedia As The Engine Of Application State is a principle that hypertext links should be used to create a better navigation through the API. In essence that means, in an API designed after the HATEOAS principle, a client will be able to navigate through the API by following URLs and links provided by the server - this is much the same, as a user navigating through a website by following links on that site. As this is a bit of a complicated topic, a more in deep description is provided within this presentation
  • 32. Provide operations for collections Filtering - filter a return list Sorting - sort a collection Field Selection - select fields Paging - display a limited set of resources per query
  • 33. Filtering Use a unique query parameter for all fields or a query language for filtering. To return a list of alien action figures GET /dolls?family=alien To return a list of action figures with a maximum of 2 heads GET /dolls?heads<=2
  • 34. Sorting Allow ascending and descending sorting over multiple fields. To return a list of action figures sorted by descending manufacturers and ascending models. GET /dolls?sort=-manufactorer,+model
  • 35. Field Selection Mobile clients display just a few attributes in a list. They don’t need all attributes of a resource. Give the API consumer the ability to choose returned fields. This will also reduce the network traffic and speed up the usage of the API. GET /dolls? fields=manufacturer,model,id,family
  • 36. Paging Use limit and offset. It is flexible for the user and common in leading databases. The default should be limit=20 and offset=0 GET /dolls?offset=10&limit=5 To send the total entries back to the user use the custom HTTP header: X-Total- Count. Links to the next or previous page should be provided in the HTTP header link as well. It is important to follow this link header values instead of constructing your own URLs. <https://blog.microdolls.com/catalog/api/v1/dolls?offset=15&limit=5>; rel=„next", <https://blog.microdolls.com/catalog/api/v1/dolls?offset=50&limit=3>; rel=„last", <https://blog.microdolls.com/catalog/api/v1/dolls?offset=0&limit=5>; rel=„first", <https://blog.microdolls.com/catalog/api/v1/dolls?offset=5&limit=5>; rel="prev",
  • 37. Version your API Make the API Version mandatory and do not release an unversioned API. Decide on your API versioning scheme - simple ordinals or year plus month or the like. It doesn’t really matter, but stick to it for all your APIs within a domain and/or application system If using numbers, use simple ordinal number and avoid dot notation such as 2.5. Finally it is common sense to prefix the url for the API versioning with the letter „v“ /catalog/api/v1
  • 38. Transport errors as HTTP status codes It is hard to work with an API that ignores error handling. Pure returning of a HTTP 500 with a stacktrace is not very helpful. Also, inventing new meanings to established http status codes makes using your API a nightmare on elm street Instead use standard HTTP status codes
  • 39. Use HTTP status codes The HTTP standard provides over 70 status codes to describe the return values. Use these 4 codes for successful requests 200 – OK – Here is your result 201 – OK – New resource was created / resource was updated 204 – OK – The resource was successfully deleted 304 – Not Modified – The client can use cached data
  • 40. HTTP error status codes Use these 5 codes for failed requests 400 – Bad Request – The request was invalid or cannot be served. The exact error should be explained in the error payload. E.g. „The JSON is not valid“ 401 – Unauthorized – The request requires an user authentication 403 – Forbidden – The server understood the request, but is refusing it or the access is not allowed. 404 – Not found – There is no resource behind the URI. 422 – Unprocessable Entity – Should be used if the server cannot process the enitity, e.g. if an image cannot be formatted or mandatory fields are missing in the payload.
  • 41. HTTP 500 API developers should avoid this error in normal situation and use specific error codes (as shown in the previous slide). If an error occurs in the global catch blog (bad luck), the stracktrace should be logged and not returned as response. 500 – Internal Server Error
  • 42. Use error payloads All exceptions should be mapped in an error payload. Here is an example how a JSON payload should look like. 04 "userMessage": "Sorry, the requested resource does not exist“, 05 "internalMessage": "No doll found in the database",
  • 43. Allow overriding HTTP methods Some proxies support only POST and GET methods. To support a RESTful API with these limitations, the API needs a way to override the HTTP method. Use the custom HTTP Header X-HTTP-Method- Override to override the POST Method.