SlideShare a Scribd company logo
REST Deep Dive Part II
RESTful API Design
Part I - Recap
1. Architectural Constraints of REST
a. Client-Server
b. Statelessness
c. Cacheability
d. Layered System
e. Code-on-Demand
f. Uniform Interface
2. All about Resources
a. What is a resource?
b. Types of resources
3. All about Representations
4. URI Naming Conventions
RESTful API design steps
1. Identify the resource(s).
○ What are resources?
2. Create model URIs.
○ versioning, namespace, resources naming conventions and resource identifiers.
3. Determine resource structure and request/response format.
4. Assign HTTP methods
○ HTTP methods and status codes.
○ Idempotency, Safety and caching responses.
Example Application
● We are going to build a simple user service, where we store, retrieve and
modify user information.
● User information includes - name, DOB, list of their addresses, password,
phone#, email, type and status of their account.
Resources
● What are resources?
○ General Definition - A resource is anything that’s important enough to be referenced as a
thing. You should make something into a resource, if you want to
■ include all or part of it by reference into another representation,
■ retrieve or cache a representation of it,
■ create a hypertext link to it,
■ or perform CRUD operations on it.
○ Definition of a resource was designed to be intentionally vague. So, if you don’t understand it,
get in line.
○ In RESTful APIs resources can be collections or singletons, they can also contain other
resources.
Resources continued...
● Can you name the resources in our example application?
Resources continued...
● Our example application has 2 resources.
a. User
b. Address (sub-resource).
URIs
● URIs are used to uniquely identify and address a resource in RESTful APIs.
● URIs are made up of 3 parts.
○ Version,
○ Namespace (optional),
○ Resource name.
● We’ll look into what each of the above concepts are, in detail in the following
slides.
More About URIs - Versioning
● APIs are a contract between the client and the server (uniform interface constraint).
● Breaking changes break the contract between the client and the server. In our case, between our
frontend react application and our backend java services.
● Breaking changes include -
○ a change in the format of the request/response data for one or more calls
○ a change in the request/response type (i.e. changing an integer to a float) etc.
● Non-breaking changes tend to be additive. E.g. adding new fields or nested resources to your
resource representations, adding new endpoints such as a PUT or PATCH that was previously
unavailable. API consumers should build client code that is resilient to these kinds of non-breaking
changes.
Versioning continued...
● Version changes should happen according to the following rules, when your
APIs are being consumed by clients.
○ Breaking changes result in a major version change.
○ Non-breaking changes result in a minor version change (optional).
● Version changes should not happen during the development phase of your
APIs. I.e. before exposing them to the client.
● Since we are in the process of developing our example application, we will
use v1 as our API version.
More About URIs - Namespaces
● Namespaces are optional and add a bit of organisation to your APIs mainly
from a documentation point of view.
● Namespaces allow you to group related resources under a common root.
● It can be used for url based routing when there are multiple components (E.g.
microservices).
● Also allows you to define a scope for a particular resource.
○ E.g. In our inhouse IoT application, In case you want to differentiate between motor
configuration and sump configuration, you can use the same resource name under 2
namespaces -
■ /v1/motor/configurations
■ /v1/sump/configurations
● Namespaces should be singular nouns.
Resource naming and URI formatting best practices
● Use nouns for collections and document names, and verbs for controllers
names
○ E.g. collection - /v1/motor/configurations, controller - /v1/motor/change-configuration
● Forward slash (/) to indicate hierarchical relationships.
● Avoid trailing slashes
● Use hyphens to improve readability
● Do not use underscores in URIs
● Use lower case in URIs
● Do not use file extensions
● Never use camel case CRUD function names in URIs
○ E.g. Correct - POST /v1/motor/configurations, Wrong - /v1/motor/createConfigurations,
● Use query params to filter collection type resources.
Resource naming recap
● Plural lowercase nouns.
● DO NOT use verbs in resource names. E.g. /v1/device/getDeviceInfo
● DO NOT use camel case.
● Use hyphens in between words, in case there more than 2 words in your
resource name.
● Use resource ids to identify particular resources in a collection. E.g.
/v1/device/{id}.
● Subresources are identified like this /v1/device/{id}/configurations
URIs for our example application
● Recap - Resources that we identified were user and address (sub-resource).
● URIs are made up of 3 parts,
○ Version,
○ Namespace (optional in general, but mandatory for our example app),
○ Resource name.
● Can you name the URIs that we will use in our application?
● Remember URIs are used to address a particular resource uniquely.
URIs for our example application
● /v1/account/users and /v1/account/users/{id}/addresses
● /v1/account/addresses
Request/Response Format
● Now we need to take a decision on how we are going to represent our
resources.
● REST accepts multiple request and response body types, like form-url-
encoded, form data, plain text, json, binaries etc.
● Most RESTful APIs use either XML or JSON.
● We are going to be using JSONs in our example application.
Idempotence, Safety and Caching
● In computing, an idempotent operation is one that has no additional effect if it is called more than
once with the same input parameters. f(f(f(x))) = f(x).
● E.g. the abs function is idempotent because abs(abs(x)) = abs(x).
● In RESTful APIs a request method is considered "idempotent" if the intended effect on the server of
multiple identical requests with that method is the same as the effect for a single such request.
● Is the DELETE method idempotent?
● A Safe method does not modify the given resource in any way. It retrieves a representation of a
given resource without modifying it.
● “Cacheability” is one of REST’s architectural constraints.
● In RESTful APIs, when a consumer requests a resource’s representation, the request goes through
a cache or a series of caches before hitting the database hosting the resource.
HTTP methods and response codes
● HTTP methods represent the ways in which resources can be accessed or
modified.
● There are 5 major HTTP methods
a. POST
b. GET
c. PUT
d. PATCH
e. DELETE
● In addition to response messages, server responses also contain http
headers, a status message and a status code.
● Status codes range from 1xx - 5xx
HTTP Status Codes
HTTP Status Codes Description
1xx (Informational) An informational response, indicates that the request was received and
understood.
2xx (Successful) The request was successfully received, understood and accepted.
3xx (Redirection) Further action needs to be taken in order to complete the request.
4xx (Client Error) The request contains bad syntax or cannot be fulfilled.
5xx (Server Error) The server failed to fulfill an apparently valid request.
Status Codes continued...
● 1xx - Informational
○ 101 Switching Protocols
● 2xx - Successful,
○ 200 OK
○ 202 Accepted
○ 201 Created
○ 204 No Content
● 3xx - Redirection,
○ 301 Moved Permanently
○ 302 Found
○ 304 Not Modified
● 4xx - Client Errors,
○ 400 Bad Request
○ 401 Unauthorized
○ 403 Forbidden
○ 404 Not Found
● 5xx - Server Errors.
○ 500 Internal Server Error
○ 502 Bad Gateway
○ 504 Gateway Timeout
For More Info visit -
https://tools.ietf.org/html/rfc2616#section-10
POST
● POST method is used to create new resources.
● If the resource is created, the server responds with a 201 Created.
● Sometimes when a POST request performs an action on a resource without a
resource identifier (controller pattern methods) the server can return a 200
(OK) or a 204 (No Content).
● POST responses are not cacheable.
● POST request are neither safe nor idempotent and invoking two identical
POSTs will result in two different resources containing the same information
and different resource ids.
● POSTs cannot return 404.
GET
● GET Request are used to retrieve resource representations (current state of the
resource).
● There are 2 types of GET requests.
a. GET with resource identifier,
b. GET for a collection of resources with or without query params.
● GETs usually return a 200 OK with the response body containing the resource(s) that
were requested.
● Type 1 GET (get with id) should return a 404 Not Found, if the requested resource is
not present in the server.
● Type 2 GET (get collection) should return a 200 with an empty response body, if the
requests resources are not found.
● GET is idempotent, safe and the responses are cacheable.
● PUT request are used to update existing resources.
● If the resource does not exist, the server may choose to create it or it may not.
● If a resource was created, the server must return a 201 Created to inform the client,
that the update resulted in a new resource being created.
● If an existing resource was updated, the server can return either a 200 OK or a 204 No
Content.
● PUT should only be used if you are replacing an entire resource, for partial updates
please use the PATCH method.
● PUT
○ requests are idempotent but are not safe
○ response is not cacheable.
PUT
PATCH
● It is used to partially update a resource.
● It cannot create a resource as it sends partial information only.
● PATCH applies a delta rather than updating the given resource entirely.
● A typical PATCH request is an array of partial modifications to the given resource.
● The array contains a request to update a particular portion of a given resource in the
following format.
[{ “op”: “replace”, “path”: “/email”, “value”: “new.email@example.org” }]
● op is operation, it can be remove, add, replace, move and copy.
● It includes the path to the field that you are changing and the value that needs to be
changed.
● Similar to PUT, PATCH requests are also idempotent, not safe and not cacheable.
JSON Patch standard -
https://tools.ietf.org/html/rfc6902
DELETE
● As the name applies, DELETE method is used to delete resources.
● A successful delete operation should return a 200 OK with a response or if
you don’t wish to return any response from the server, a 204 No Content is
sent back.
● DELETE operations are idempotent (ideally).
● If the item is not present in the server, it may return a 404 Not Found to the
client.
● It is also not cacheable and not safe.
Recap
HTTP Method Request Has Body Response Has Body Safe Idempotent Cacheable
POST Yes Yes No No No
GET No Yes Yes Yes Yes
PUT Yes Optional No Yes No
PATCH Yes Optional No Yes No
DELETE No Optional No Yes No
Back to our example application
● Recap - resource names - users and addresses which was a sub-resource.
● Endpoints - /v1/account/users and /v1/account/users/{id}/addresses.
● Can you make CRUD endpoints for the users and address resources?
● I need to get all addresses that have the pincode as 600014, how do i do
that?
● Also needed is an endpoint to modify the user’s mobile number. The request
should contain the user’s current mobile number, an otp and their updated
mobile number.
● Update a user’s DOB with a resource id and the updated DOB value alone.
Thank you

More Related Content

What's hot

IR with lucene
IR with luceneIR with lucene
IR with lucene
Stelios Gorilas
 
Apache Lucene intro - Breizhcamp 2015
Apache Lucene intro - Breizhcamp 2015Apache Lucene intro - Breizhcamp 2015
Apache Lucene intro - Breizhcamp 2015
Adrien Grand
 
Unit 3 - URLs and URIs
Unit 3 - URLs and URIsUnit 3 - URLs and URIs
Unit 3 - URLs and URIs
Chandan Gupta Bhagat
 
Berlin Buzzwords 2013 - How does lucene store your data?
Berlin Buzzwords 2013 - How does lucene store your data?Berlin Buzzwords 2013 - How does lucene store your data?
Berlin Buzzwords 2013 - How does lucene store your data?
Adrien Grand
 
Url web design
Url web designUrl web design
Url web designCojo34
 
What is in a Lucene index?
What is in a Lucene index?What is in a Lucene index?
What is in a Lucene index?
lucenerevolution
 
Lucene BootCamp
Lucene BootCampLucene BootCamp
Lucene BootCampGokulD
 
Spatial approximate string search Doc
Spatial approximate string search DocSpatial approximate string search Doc
Spatial approximate string search Doc
Sudha Hari Tech Solution Pvt ltd
 
ReST (Representational State Transfer) Explained
ReST (Representational State Transfer) ExplainedReST (Representational State Transfer) Explained
ReST (Representational State Transfer) Explained
Dhananjay Nene
 
Mining Product Synonyms - Slides
Mining Product Synonyms - SlidesMining Product Synonyms - Slides
Mining Product Synonyms - Slides
Ankush Jain
 
RFS Search Lang Spec
RFS Search Lang SpecRFS Search Lang Spec
RFS Search Lang SpecJing Kang
 
Search Lucene
Search LuceneSearch Lucene
Search Lucene
Jeremy Coates
 
Kibana: Real-World Examples
Kibana: Real-World ExamplesKibana: Real-World Examples
Kibana: Real-World Examples
Salvatore Cordiano
 
JSON and REST
JSON and RESTJSON and REST
JSON and REST
Robert MacLean
 
Poster Declaratively Describing Responses of Hypermedia-Driven Web APIs
Poster Declaratively Describing Responses of Hypermedia-Driven Web APIsPoster Declaratively Describing Responses of Hypermedia-Driven Web APIs
Poster Declaratively Describing Responses of Hypermedia-Driven Web APIs
Ruben Taelman
 
Bio2RDF Distributed Querying model
Bio2RDF Distributed Querying modelBio2RDF Distributed Querying model
Bio2RDF Distributed Querying modelPeter Ansell
 
Semantic & Multilingual Strategies in Lucene/Solr: Presented by Trey Grainger...
Semantic & Multilingual Strategies in Lucene/Solr: Presented by Trey Grainger...Semantic & Multilingual Strategies in Lucene/Solr: Presented by Trey Grainger...
Semantic & Multilingual Strategies in Lucene/Solr: Presented by Trey Grainger...
Lucidworks
 
Intelligent crawling and indexing using lucene
Intelligent crawling and indexing using luceneIntelligent crawling and indexing using lucene
Intelligent crawling and indexing using luceneSwapnil & Patil
 
Apache Lucene: Searching the Web and Everything Else (Jazoon07)
Apache Lucene: Searching the Web and Everything Else (Jazoon07)Apache Lucene: Searching the Web and Everything Else (Jazoon07)
Apache Lucene: Searching the Web and Everything Else (Jazoon07)
dnaber
 

What's hot (20)

IR with lucene
IR with luceneIR with lucene
IR with lucene
 
Apache Lucene intro - Breizhcamp 2015
Apache Lucene intro - Breizhcamp 2015Apache Lucene intro - Breizhcamp 2015
Apache Lucene intro - Breizhcamp 2015
 
Unit 3 - URLs and URIs
Unit 3 - URLs and URIsUnit 3 - URLs and URIs
Unit 3 - URLs and URIs
 
Berlin Buzzwords 2013 - How does lucene store your data?
Berlin Buzzwords 2013 - How does lucene store your data?Berlin Buzzwords 2013 - How does lucene store your data?
Berlin Buzzwords 2013 - How does lucene store your data?
 
Url web design
Url web designUrl web design
Url web design
 
ReSTful API Final
ReSTful API FinalReSTful API Final
ReSTful API Final
 
What is in a Lucene index?
What is in a Lucene index?What is in a Lucene index?
What is in a Lucene index?
 
Lucene BootCamp
Lucene BootCampLucene BootCamp
Lucene BootCamp
 
Spatial approximate string search Doc
Spatial approximate string search DocSpatial approximate string search Doc
Spatial approximate string search Doc
 
ReST (Representational State Transfer) Explained
ReST (Representational State Transfer) ExplainedReST (Representational State Transfer) Explained
ReST (Representational State Transfer) Explained
 
Mining Product Synonyms - Slides
Mining Product Synonyms - SlidesMining Product Synonyms - Slides
Mining Product Synonyms - Slides
 
RFS Search Lang Spec
RFS Search Lang SpecRFS Search Lang Spec
RFS Search Lang Spec
 
Search Lucene
Search LuceneSearch Lucene
Search Lucene
 
Kibana: Real-World Examples
Kibana: Real-World ExamplesKibana: Real-World Examples
Kibana: Real-World Examples
 
JSON and REST
JSON and RESTJSON and REST
JSON and REST
 
Poster Declaratively Describing Responses of Hypermedia-Driven Web APIs
Poster Declaratively Describing Responses of Hypermedia-Driven Web APIsPoster Declaratively Describing Responses of Hypermedia-Driven Web APIs
Poster Declaratively Describing Responses of Hypermedia-Driven Web APIs
 
Bio2RDF Distributed Querying model
Bio2RDF Distributed Querying modelBio2RDF Distributed Querying model
Bio2RDF Distributed Querying model
 
Semantic & Multilingual Strategies in Lucene/Solr: Presented by Trey Grainger...
Semantic & Multilingual Strategies in Lucene/Solr: Presented by Trey Grainger...Semantic & Multilingual Strategies in Lucene/Solr: Presented by Trey Grainger...
Semantic & Multilingual Strategies in Lucene/Solr: Presented by Trey Grainger...
 
Intelligent crawling and indexing using lucene
Intelligent crawling and indexing using luceneIntelligent crawling and indexing using lucene
Intelligent crawling and indexing using lucene
 
Apache Lucene: Searching the Web and Everything Else (Jazoon07)
Apache Lucene: Searching the Web and Everything Else (Jazoon07)Apache Lucene: Searching the Web and Everything Else (Jazoon07)
Apache Lucene: Searching the Web and Everything Else (Jazoon07)
 

Similar to A Deep Dive into RESTful API Design Part 2

Restful webservices
Restful webservicesRestful webservices
Restful webservices
Sumit Gole
 
REST & RESTful Web Service
REST & RESTful Web ServiceREST & RESTful Web Service
REST & RESTful Web Service
Hoan Vu Tran
 
SOAP vs REST
SOAP vs RESTSOAP vs REST
SOAP vs REST
Nadia Boumaza
 
A Deep Dive into RESTful API Design Part 1
A Deep Dive into RESTful API Design Part 1A Deep Dive into RESTful API Design Part 1
A Deep Dive into RESTful API Design Part 1
VivekKrishna34
 
How to design a good rest api tools, techniques and best practices.
How to design a good rest api  tools, techniques and best practices.How to design a good rest api  tools, techniques and best practices.
How to design a good rest api tools, techniques and best practices.
Nuwan Dias
 
REST and RESTful Services
REST and RESTful ServicesREST and RESTful Services
REST and RESTful Services
Damian T. Gordon
 
Restful webservice
Restful webserviceRestful webservice
Restful webservice
Dong Ngoc
 
ROA.ppt
ROA.pptROA.ppt
ROA.ppt
KGSCSEPSGCT
 
API
APIAPI
API_Design_Rest_Princple.pdf
API_Design_Rest_Princple.pdfAPI_Design_Rest_Princple.pdf
API_Design_Rest_Princple.pdf
Huan Le Trong
 
Ladies Be Architects - Integration - Multi-Org, Security, JSON, Backup & Restore
Ladies Be Architects - Integration - Multi-Org, Security, JSON, Backup & RestoreLadies Be Architects - Integration - Multi-Org, Security, JSON, Backup & Restore
Ladies Be Architects - Integration - Multi-Org, Security, JSON, Backup & Restore
gemziebeth
 
computer network introduction. psc notes . Assisant professor in cse.
computer network introduction. psc notes . Assisant professor in cse.computer network introduction. psc notes . Assisant professor in cse.
computer network introduction. psc notes . Assisant professor in cse.
bushraphd2022
 
Cqrs api
Cqrs apiCqrs api
Cqrs api
Brandon Mueller
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using Php
Sudheer Satyanarayana
 
Restful web services with java
Restful web services with javaRestful web services with java
Restful web services with java
Vinay Gopinath
 
Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdf
Aparna Sharma
 
RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座Li Yi
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 

Similar to A Deep Dive into RESTful API Design Part 2 (20)

Restful webservices
Restful webservicesRestful webservices
Restful webservices
 
REST & RESTful Web Service
REST & RESTful Web ServiceREST & RESTful Web Service
REST & RESTful Web Service
 
SOAP vs REST
SOAP vs RESTSOAP vs REST
SOAP vs REST
 
A Deep Dive into RESTful API Design Part 1
A Deep Dive into RESTful API Design Part 1A Deep Dive into RESTful API Design Part 1
A Deep Dive into RESTful API Design Part 1
 
How to design a good rest api tools, techniques and best practices.
How to design a good rest api  tools, techniques and best practices.How to design a good rest api  tools, techniques and best practices.
How to design a good rest api tools, techniques and best practices.
 
REST and RESTful Services
REST and RESTful ServicesREST and RESTful Services
REST and RESTful Services
 
Restful webservice
Restful webserviceRestful webservice
Restful webservice
 
ROA.ppt
ROA.pptROA.ppt
ROA.ppt
 
API
APIAPI
API
 
API_Design_Rest_Princple.pdf
API_Design_Rest_Princple.pdfAPI_Design_Rest_Princple.pdf
API_Design_Rest_Princple.pdf
 
Ladies Be Architects - Integration - Multi-Org, Security, JSON, Backup & Restore
Ladies Be Architects - Integration - Multi-Org, Security, JSON, Backup & RestoreLadies Be Architects - Integration - Multi-Org, Security, JSON, Backup & Restore
Ladies Be Architects - Integration - Multi-Org, Security, JSON, Backup & Restore
 
Cqrs api v2
Cqrs api v2Cqrs api v2
Cqrs api v2
 
computer network introduction. psc notes . Assisant professor in cse.
computer network introduction. psc notes . Assisant professor in cse.computer network introduction. psc notes . Assisant professor in cse.
computer network introduction. psc notes . Assisant professor in cse.
 
HTTP
HTTPHTTP
HTTP
 
Cqrs api
Cqrs apiCqrs api
Cqrs api
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using Php
 
Restful web services with java
Restful web services with javaRestful web services with java
Restful web services with java
 
Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdf
 
RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 

Recently uploaded

Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 

Recently uploaded (20)

Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 

A Deep Dive into RESTful API Design Part 2

  • 1. REST Deep Dive Part II RESTful API Design
  • 2. Part I - Recap 1. Architectural Constraints of REST a. Client-Server b. Statelessness c. Cacheability d. Layered System e. Code-on-Demand f. Uniform Interface 2. All about Resources a. What is a resource? b. Types of resources 3. All about Representations 4. URI Naming Conventions
  • 3. RESTful API design steps 1. Identify the resource(s). ○ What are resources? 2. Create model URIs. ○ versioning, namespace, resources naming conventions and resource identifiers. 3. Determine resource structure and request/response format. 4. Assign HTTP methods ○ HTTP methods and status codes. ○ Idempotency, Safety and caching responses.
  • 4. Example Application ● We are going to build a simple user service, where we store, retrieve and modify user information. ● User information includes - name, DOB, list of their addresses, password, phone#, email, type and status of their account.
  • 5. Resources ● What are resources? ○ General Definition - A resource is anything that’s important enough to be referenced as a thing. You should make something into a resource, if you want to ■ include all or part of it by reference into another representation, ■ retrieve or cache a representation of it, ■ create a hypertext link to it, ■ or perform CRUD operations on it. ○ Definition of a resource was designed to be intentionally vague. So, if you don’t understand it, get in line. ○ In RESTful APIs resources can be collections or singletons, they can also contain other resources.
  • 6. Resources continued... ● Can you name the resources in our example application?
  • 7. Resources continued... ● Our example application has 2 resources. a. User b. Address (sub-resource).
  • 8. URIs ● URIs are used to uniquely identify and address a resource in RESTful APIs. ● URIs are made up of 3 parts. ○ Version, ○ Namespace (optional), ○ Resource name. ● We’ll look into what each of the above concepts are, in detail in the following slides.
  • 9. More About URIs - Versioning ● APIs are a contract between the client and the server (uniform interface constraint). ● Breaking changes break the contract between the client and the server. In our case, between our frontend react application and our backend java services. ● Breaking changes include - ○ a change in the format of the request/response data for one or more calls ○ a change in the request/response type (i.e. changing an integer to a float) etc. ● Non-breaking changes tend to be additive. E.g. adding new fields or nested resources to your resource representations, adding new endpoints such as a PUT or PATCH that was previously unavailable. API consumers should build client code that is resilient to these kinds of non-breaking changes.
  • 10. Versioning continued... ● Version changes should happen according to the following rules, when your APIs are being consumed by clients. ○ Breaking changes result in a major version change. ○ Non-breaking changes result in a minor version change (optional). ● Version changes should not happen during the development phase of your APIs. I.e. before exposing them to the client. ● Since we are in the process of developing our example application, we will use v1 as our API version.
  • 11. More About URIs - Namespaces ● Namespaces are optional and add a bit of organisation to your APIs mainly from a documentation point of view. ● Namespaces allow you to group related resources under a common root. ● It can be used for url based routing when there are multiple components (E.g. microservices). ● Also allows you to define a scope for a particular resource. ○ E.g. In our inhouse IoT application, In case you want to differentiate between motor configuration and sump configuration, you can use the same resource name under 2 namespaces - ■ /v1/motor/configurations ■ /v1/sump/configurations ● Namespaces should be singular nouns.
  • 12. Resource naming and URI formatting best practices ● Use nouns for collections and document names, and verbs for controllers names ○ E.g. collection - /v1/motor/configurations, controller - /v1/motor/change-configuration ● Forward slash (/) to indicate hierarchical relationships. ● Avoid trailing slashes ● Use hyphens to improve readability ● Do not use underscores in URIs ● Use lower case in URIs ● Do not use file extensions ● Never use camel case CRUD function names in URIs ○ E.g. Correct - POST /v1/motor/configurations, Wrong - /v1/motor/createConfigurations, ● Use query params to filter collection type resources.
  • 13. Resource naming recap ● Plural lowercase nouns. ● DO NOT use verbs in resource names. E.g. /v1/device/getDeviceInfo ● DO NOT use camel case. ● Use hyphens in between words, in case there more than 2 words in your resource name. ● Use resource ids to identify particular resources in a collection. E.g. /v1/device/{id}. ● Subresources are identified like this /v1/device/{id}/configurations
  • 14. URIs for our example application ● Recap - Resources that we identified were user and address (sub-resource). ● URIs are made up of 3 parts, ○ Version, ○ Namespace (optional in general, but mandatory for our example app), ○ Resource name. ● Can you name the URIs that we will use in our application? ● Remember URIs are used to address a particular resource uniquely.
  • 15. URIs for our example application ● /v1/account/users and /v1/account/users/{id}/addresses ● /v1/account/addresses
  • 16. Request/Response Format ● Now we need to take a decision on how we are going to represent our resources. ● REST accepts multiple request and response body types, like form-url- encoded, form data, plain text, json, binaries etc. ● Most RESTful APIs use either XML or JSON. ● We are going to be using JSONs in our example application.
  • 17. Idempotence, Safety and Caching ● In computing, an idempotent operation is one that has no additional effect if it is called more than once with the same input parameters. f(f(f(x))) = f(x). ● E.g. the abs function is idempotent because abs(abs(x)) = abs(x). ● In RESTful APIs a request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. ● Is the DELETE method idempotent? ● A Safe method does not modify the given resource in any way. It retrieves a representation of a given resource without modifying it. ● “Cacheability” is one of REST’s architectural constraints. ● In RESTful APIs, when a consumer requests a resource’s representation, the request goes through a cache or a series of caches before hitting the database hosting the resource.
  • 18. HTTP methods and response codes ● HTTP methods represent the ways in which resources can be accessed or modified. ● There are 5 major HTTP methods a. POST b. GET c. PUT d. PATCH e. DELETE ● In addition to response messages, server responses also contain http headers, a status message and a status code. ● Status codes range from 1xx - 5xx
  • 19. HTTP Status Codes HTTP Status Codes Description 1xx (Informational) An informational response, indicates that the request was received and understood. 2xx (Successful) The request was successfully received, understood and accepted. 3xx (Redirection) Further action needs to be taken in order to complete the request. 4xx (Client Error) The request contains bad syntax or cannot be fulfilled. 5xx (Server Error) The server failed to fulfill an apparently valid request.
  • 20. Status Codes continued... ● 1xx - Informational ○ 101 Switching Protocols ● 2xx - Successful, ○ 200 OK ○ 202 Accepted ○ 201 Created ○ 204 No Content ● 3xx - Redirection, ○ 301 Moved Permanently ○ 302 Found ○ 304 Not Modified ● 4xx - Client Errors, ○ 400 Bad Request ○ 401 Unauthorized ○ 403 Forbidden ○ 404 Not Found ● 5xx - Server Errors. ○ 500 Internal Server Error ○ 502 Bad Gateway ○ 504 Gateway Timeout For More Info visit - https://tools.ietf.org/html/rfc2616#section-10
  • 21. POST ● POST method is used to create new resources. ● If the resource is created, the server responds with a 201 Created. ● Sometimes when a POST request performs an action on a resource without a resource identifier (controller pattern methods) the server can return a 200 (OK) or a 204 (No Content). ● POST responses are not cacheable. ● POST request are neither safe nor idempotent and invoking two identical POSTs will result in two different resources containing the same information and different resource ids. ● POSTs cannot return 404.
  • 22. GET ● GET Request are used to retrieve resource representations (current state of the resource). ● There are 2 types of GET requests. a. GET with resource identifier, b. GET for a collection of resources with or without query params. ● GETs usually return a 200 OK with the response body containing the resource(s) that were requested. ● Type 1 GET (get with id) should return a 404 Not Found, if the requested resource is not present in the server. ● Type 2 GET (get collection) should return a 200 with an empty response body, if the requests resources are not found. ● GET is idempotent, safe and the responses are cacheable.
  • 23. ● PUT request are used to update existing resources. ● If the resource does not exist, the server may choose to create it or it may not. ● If a resource was created, the server must return a 201 Created to inform the client, that the update resulted in a new resource being created. ● If an existing resource was updated, the server can return either a 200 OK or a 204 No Content. ● PUT should only be used if you are replacing an entire resource, for partial updates please use the PATCH method. ● PUT ○ requests are idempotent but are not safe ○ response is not cacheable. PUT
  • 24. PATCH ● It is used to partially update a resource. ● It cannot create a resource as it sends partial information only. ● PATCH applies a delta rather than updating the given resource entirely. ● A typical PATCH request is an array of partial modifications to the given resource. ● The array contains a request to update a particular portion of a given resource in the following format. [{ “op”: “replace”, “path”: “/email”, “value”: “new.email@example.org” }] ● op is operation, it can be remove, add, replace, move and copy. ● It includes the path to the field that you are changing and the value that needs to be changed. ● Similar to PUT, PATCH requests are also idempotent, not safe and not cacheable. JSON Patch standard - https://tools.ietf.org/html/rfc6902
  • 25. DELETE ● As the name applies, DELETE method is used to delete resources. ● A successful delete operation should return a 200 OK with a response or if you don’t wish to return any response from the server, a 204 No Content is sent back. ● DELETE operations are idempotent (ideally). ● If the item is not present in the server, it may return a 404 Not Found to the client. ● It is also not cacheable and not safe.
  • 26. Recap HTTP Method Request Has Body Response Has Body Safe Idempotent Cacheable POST Yes Yes No No No GET No Yes Yes Yes Yes PUT Yes Optional No Yes No PATCH Yes Optional No Yes No DELETE No Optional No Yes No
  • 27. Back to our example application ● Recap - resource names - users and addresses which was a sub-resource. ● Endpoints - /v1/account/users and /v1/account/users/{id}/addresses. ● Can you make CRUD endpoints for the users and address resources? ● I need to get all addresses that have the pincode as 600014, how do i do that? ● Also needed is an endpoint to modify the user’s mobile number. The request should contain the user’s current mobile number, an otp and their updated mobile number. ● Update a user’s DOB with a resource id and the updated DOB value alone.