SlideShare uma empresa Scribd logo
1 de 28
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

Mais conteúdo relacionado

Mais procurados

Apache Lucene intro - Breizhcamp 2015
Apache Lucene intro - Breizhcamp 2015Apache Lucene intro - Breizhcamp 2015
Apache Lucene intro - Breizhcamp 2015Adrien Grand
 
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
 
ReST (Representational State Transfer) Explained
ReST (Representational State Transfer) ExplainedReST (Representational State Transfer) Explained
ReST (Representational State Transfer) ExplainedDhananjay Nene
 
Mining Product Synonyms - Slides
Mining Product Synonyms - SlidesMining Product Synonyms - Slides
Mining Product Synonyms - SlidesAnkush Jain
 
RFS Search Lang Spec
RFS Search Lang SpecRFS Search Lang Spec
RFS Search Lang SpecJing Kang
 
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 APIsRuben 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
 

Mais procurados (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)
 

Semelhante a A Deep Dive into RESTful API Design Part 2

Restful webservices
Restful webservicesRestful webservices
Restful webservicesSumit Gole
 
REST & RESTful Web Service
REST & RESTful Web ServiceREST & RESTful Web Service
REST & RESTful Web ServiceHoan Vu Tran
 
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 1VivekKrishna34
 
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
 
Restful webservice
Restful webserviceRestful webservice
Restful webserviceDong Ngoc
 
API_Design_Rest_Princple.pdf
API_Design_Rest_Princple.pdfAPI_Design_Rest_Princple.pdf
API_Design_Rest_Princple.pdfHuan 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 & Restoregemziebeth
 
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
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using PhpSudheer Satyanarayana
 
Restful web services with java
Restful web services with javaRestful web services with java
Restful web services with javaVinay 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.pdfAparna 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 ServicesWebStackAcademy
 

Semelhante a 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
 

Último

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 

Último (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 

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.