SlideShare a Scribd company logo
1 of 23
REST &
RESTful WEB
SERVICES
Agenda?
• What is REST?
• What is RESTful Webservices
• HTTP-REST Request Basics
• HTTP-REST Vocabulary
• Authentication (OAuth)
• OAuth 2.0 Web Server Flow
• REST APIs using Apex REST
• Resources
What is REST?
• REST stands for Representational State Transfer
• It is an architectural pattern for developing web services as
opposed to a specification.
• REST web services communicate over the HTTP specification,
using HTTP vocabulary:
– Methods (GET, POST, etc.)
– HTTP URI syntax (paths, parameters, etc.)
– Media types (xml, json, html, plain text, etc)
– HTTP Response codes.
Continued …
• Representational
– Clients possess the information necessary to identify, modify,
and/or delete a web resource.
• State
– All resource state information is stored on the client.
• Transfer
– Client state is passed from the client to the service through
HTTP.
Continued …
The six characteristics of REST:
1. Uniform interface
2. Decoupled client-server interaction
3. Stateless
4. Cacheable
5. Layered
6. Extensible through code on demand (optional)
What is RESTful Web Services ?
• RESTful web services are web services which are REST based.
• Stateless & cacheable.
• Uses URI & HTTP methods.
• Quiet light, extensible and simple services.
• The reason behind the popularity of REST is that the applications
we use are browser-based nowadays and top it all, REST is built on
HTTP.
• Main idea: Providing the communication between client and server
over HTTP protocol rather than other complex architectures like
SOAP and RPC etc.
HTTP-REST Request Basics
• The HTTP request is sent from the client.
– Identifies the location of a resource.
– Specifies the verb, or HTTP method to use when accessing the
resource.
– Supplies optional request headers (name-value pairs) that
provide additional information the server may need when
processing the request.
– Supplies an optional request body that identifies additional data
to be uploaded to the server (e.g. form parameters, attachments,
etc.)
Continued …
Sample Client Requests:
• A typical client GET request:
• A typical client POST request:
GET /view?id=1 HTTP/1.1
User-Agent: Chrome
Accept: application/json
[CRLF]
Requested Resource (path and query string)
Request Headers
(no request body)
POST /save HTTP/1.1
User-Agent: IE
Content-Type: application/x-www-form-urlencoded
[CRLF]
name=x&id=2
Request Headers
Request Body (e.g. form parameters)
Requested Resource (typically no query string)
Continued …
• The HTTP response is sent from the server.
– Gives the status of the processed request.
– Supplies response headers (name-value pairs) that provide
additional information about the response.
– Supplies an optional response body that identifies additional
data to be downloaded to the client (html, xml, binary data, etc.)
Continued …
• Sample Server Responses:
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1337
[CRLF]
<html>
<!-- Some HTML Content.
</html>
Response Status
Response Headers
Response Body (content)
HTTP-REST Vocabulary
HTTP Methods supported by REST:
• GET – Requests a resource at the request URL
– Should not contain a request body, as it will be discarded.
– May be cached locally or on the server.
– May produce a resource, but should not modify on it.
• POST – Submits information to the service for processing
– Should typically return the new or modified resource.
• PUT – Add a new resource at the request URL
• DELETE – Removes the resource at the request URL
• OPTIONS – Indicates which methods are supported
• HEAD – Returns meta information about the request URL
Continued …
A typical HTTP REST URL:
• The protocol identifies the transport scheme that will be used to process
and respond to the request.
• The host name identifies the server address of the resource.
• The path and query string can be used to identify and customize the
accessed resource.
http://my.store.com/fruits/list?category=fruit&limit=20
protocol host name path to a resource query string
What is OAuth?
• A simple open standard for secure API authentication.
• Salesforce supports OAuth versions 1.0A and 2.0 authentication flows.
• Types of OAuth 2.0 authetication flows:
– OAuth 2.0 Web server—The Web server authentication flow is used by
applications that are hosted on a secure server. A critical aspect of the Web server
flow is that the server must be able to protect the consumer secret.
– OAuth 2.0 user-agent—The user-agent authentication flow is used by client
applications (consumers) residing in the user’s device. These consumers cannot
keep the client secret confidential.
– OAuth 2.0 username and password—The username-password authentication
flow can be used to authenticate when the consumer already has the user’s
credentials.
Oauth 2.0 Web Server Flow
Required Paramemters:
• response_type—Value must be code for
this flow.
• client_id—Consumer key from the
connected app definition.
• redirect_uri—URI to redirect the user to
after approval. This must match the value
in the Callback URL field in the connected
app definition exactly, or approval fails.
This value must be URL encoded.
Optional Parameters:
• scope—The scope parameter enables you
to fine-tune what the client application can
access in a Salesforce organization like
&scope=api%20id%20web%20refresh_tok
en
• state—Any state the consumer wants
reflected back to it after approval, during
the callback. This parameter is optional.
This value must be URL encoded.
https://login.salesforce.com/services/oauth2/aut
horize
Once the user approves the access, they
are redirected to the URI specified in
redirect_uri with the following values in
the query string:
• code—Authorization code the
consumer must use to obtain the
access and refresh tokens
•
• state—State that was passed into the
approval step. This isn’t included if
the state parameter wasn’t included
in the original query string.
After obtaining the authorization code, the Web
server exchanges the authorization code for an
access token.
The consumer should make a POST directly to
the token endpoint, with the following
parameters:
• grant_type—Value must be
authorization_code for this flow.
• client_id—Consumer key from the
connected app definition.
• client_secret—Consumer secret from the
connected app definition.
• redirect_uri—URI to redirect the user to
after approval. This must match the value
in the Callback URL field in the connected
app definition exactly, and is the same
value sent by the initial redirect.
• code—Authorization code obtained from
the callback after approval.
POST /services/oauth2/token HTTP/1.1
Host: login.salesforce.com
grant_type=authorization_code&code=aPrxsmIEeq
M9PiQroGEWx1UiMQd95_5JUZ
VEhsOFhS8EVvbfYBBJli2W5fn3zbo.8hojaNW_1g%
3D%3D&client_id=3MVG9lKcPoNI
NVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0QqEW
hqKpoW3svG3XHrXDiCQjK1mdgAvhCs
cA9GE&client_secret=1955279925675241571&
redirect_uri=https%3A%2F%2Fwww.mysite.com%
2Fcode_callback.jsp
After the request is verified, Salesforce
sends a response to the client. The
following parameters are in the body of
the response:
• access_token—Salesforce session ID
that can be used with the Web
services API.
• refresh_token—Token that can be
used in the future to obtain new
access tokens (sessions).
• token_type—Value is Bearer for all
responses that include an access
token.
REST APIs using Apex REST
• Following is the example :
@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {
@HttpGet
global static Account doGet() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substring
(req.requestURI.lastIndexOf('/')+1);
Account result = [SELECT Id, Name, Phone, Website
FROM Account WHERE Id = :accountId];
return result;
}
}
Continued …
Setting up an Apex REST endpoint
• To declare a class as a custom endpoint, you only need to annotate
a global class with “@RestResource” and define the name of the
endpoint.
@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {
Full URI :
“https://na8.salesforce.com/services/apexrest/ Account”
Continued …
Using GET
HTTP GET defines data as a series of query parameters in the URI itself.
For example, here’s a URI:
https://na8.salesforce.com/services/apexrest/Account/001S000000ijvtwI
AA
@HttpGet
global static Account doGet() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substring
(req.requestURI.lastIndexOf('/')+1);
Account result = [SELECT Id, Name, Phone, Website FROM
Account WHERE Id = :accountId];
return result;
}
Resources
• Digging Deeper into OAuth 2.0 on Force.com
• OAuth 2.0 Web Server Authentication Flow
• Getting Started with the Force.com REST API
• Creating REST APIs using Apex REST
Rest & RESTful WebServices

More Related Content

What's hot

What's hot (20)

Android webservices
Android webservicesAndroid webservices
Android webservices
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
RESTful API - Best Practices
RESTful API - Best PracticesRESTful API - Best Practices
RESTful API - Best Practices
 
Rest assured
Rest assuredRest assured
Rest assured
 
REST and RESTful Web Services
REST and RESTful Web ServicesREST and RESTful Web Services
REST and RESTful Web Services
 
Rest API Automation with REST Assured
Rest API Automation with REST AssuredRest API Automation with REST Assured
Rest API Automation with REST Assured
 
HTTP and Your Angry Dog
HTTP and Your Angry DogHTTP and Your Angry Dog
HTTP and Your Angry Dog
 
introduction about REST API
introduction about REST APIintroduction about REST API
introduction about REST API
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
 
Testing RESTful web services with REST Assured
Testing RESTful web services with REST AssuredTesting RESTful web services with REST Assured
Testing RESTful web services with REST Assured
 
Api testing
Api testingApi testing
Api testing
 
Api presentation
Api presentationApi presentation
Api presentation
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Api types
Api typesApi types
Api types
 
React hooks
React hooksReact hooks
React hooks
 

Similar to Rest & RESTful WebServices

Rest WebAPI with OData
Rest WebAPI with ODataRest WebAPI with OData
Rest WebAPI with ODataMahek Merchant
 
Api design and development
Api design and developmentApi design and development
Api design and developmentoquidave
 
SCWCD : The web client model : CHAP : 1
SCWCD  : The web client model : CHAP : 1SCWCD  : The web client model : CHAP : 1
SCWCD : The web client model : CHAP : 1Ben Abdallah Helmi
 
Httpbasics 1207412539273264-9-converted
Httpbasics 1207412539273264-9-convertedHttpbasics 1207412539273264-9-converted
Httpbasics 1207412539273264-9-convertedcomputerorganization
 
.NET Core, ASP.NET Core Course, Session 19
 .NET Core, ASP.NET Core Course, Session 19 .NET Core, ASP.NET Core Course, Session 19
.NET Core, ASP.NET Core Course, Session 19aminmesbahi
 
Oauth2 and OWSM OAuth2 support
Oauth2 and OWSM OAuth2 supportOauth2 and OWSM OAuth2 support
Oauth2 and OWSM OAuth2 supportGaurav Sharma
 
Protecting your APIs with Doorkeeper and OAuth 2.0
Protecting your APIs with Doorkeeper and OAuth 2.0Protecting your APIs with Doorkeeper and OAuth 2.0
Protecting your APIs with Doorkeeper and OAuth 2.0Mads Toustrup-Lønne
 
Rest webservice ppt
Rest webservice pptRest webservice ppt
Rest webservice pptsinhatanay
 
(4) OAuth 2.0 Obtaining Authorization
(4) OAuth 2.0 Obtaining Authorization(4) OAuth 2.0 Obtaining Authorization
(4) OAuth 2.0 Obtaining Authorizationanikristo
 
Ch 3: Web Application Technologies
Ch 3: Web Application TechnologiesCh 3: Web Application Technologies
Ch 3: Web Application TechnologiesSam Bowne
 
The OAuth 2.0 Authorization Framework
The OAuth 2.0 Authorization FrameworkThe OAuth 2.0 Authorization Framework
The OAuth 2.0 Authorization FrameworkSamuele Cozzi
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API RecommendationsJeelani Shaik
 
Http request&response session 1 - by Vignesh.N
Http request&response session 1 - by Vignesh.NHttp request&response session 1 - by Vignesh.N
Http request&response session 1 - by Vignesh.NNavaneethan Naveen
 
HTTP Status Codes Cheat Sheet: An Exhaustive List
HTTP Status Codes Cheat Sheet: An Exhaustive ListHTTP Status Codes Cheat Sheet: An Exhaustive List
HTTP Status Codes Cheat Sheet: An Exhaustive ListMainstreethost
 

Similar to Rest & RESTful WebServices (20)

Rest WebAPI with OData
Rest WebAPI with ODataRest WebAPI with OData
Rest WebAPI with OData
 
Api design and development
Api design and developmentApi design and development
Api design and development
 
SCWCD : The web client model
SCWCD : The web client modelSCWCD : The web client model
SCWCD : The web client model
 
SCWCD : The web client model : CHAP : 1
SCWCD  : The web client model : CHAP : 1SCWCD  : The web client model : CHAP : 1
SCWCD : The web client model : CHAP : 1
 
Httpbasics 1207412539273264-9-converted
Httpbasics 1207412539273264-9-convertedHttpbasics 1207412539273264-9-converted
Httpbasics 1207412539273264-9-converted
 
.NET Core, ASP.NET Core Course, Session 19
 .NET Core, ASP.NET Core Course, Session 19 .NET Core, ASP.NET Core Course, Session 19
.NET Core, ASP.NET Core Course, Session 19
 
Oauth2 and OWSM OAuth2 support
Oauth2 and OWSM OAuth2 supportOauth2 and OWSM OAuth2 support
Oauth2 and OWSM OAuth2 support
 
Web technology Unit-I Part D - message format
Web technology Unit-I  Part D - message formatWeb technology Unit-I  Part D - message format
Web technology Unit-I Part D - message format
 
Protecting your APIs with Doorkeeper and OAuth 2.0
Protecting your APIs with Doorkeeper and OAuth 2.0Protecting your APIs with Doorkeeper and OAuth 2.0
Protecting your APIs with Doorkeeper and OAuth 2.0
 
Rest
Rest Rest
Rest
 
Rest webservice ppt
Rest webservice pptRest webservice ppt
Rest webservice ppt
 
(4) OAuth 2.0 Obtaining Authorization
(4) OAuth 2.0 Obtaining Authorization(4) OAuth 2.0 Obtaining Authorization
(4) OAuth 2.0 Obtaining Authorization
 
Ch 3: Web Application Technologies
Ch 3: Web Application TechnologiesCh 3: Web Application Technologies
Ch 3: Web Application Technologies
 
The OAuth 2.0 Authorization Framework
The OAuth 2.0 Authorization FrameworkThe OAuth 2.0 Authorization Framework
The OAuth 2.0 Authorization Framework
 
HTTP Basics
HTTP BasicsHTTP Basics
HTTP Basics
 
Unit v
Unit v Unit v
Unit v
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API Recommendations
 
Ch-1_.ppt
Ch-1_.pptCh-1_.ppt
Ch-1_.ppt
 
Http request&response session 1 - by Vignesh.N
Http request&response session 1 - by Vignesh.NHttp request&response session 1 - by Vignesh.N
Http request&response session 1 - by Vignesh.N
 
HTTP Status Codes Cheat Sheet: An Exhaustive List
HTTP Status Codes Cheat Sheet: An Exhaustive ListHTTP Status Codes Cheat Sheet: An Exhaustive List
HTTP Status Codes Cheat Sheet: An Exhaustive List
 

Recently uploaded

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 

Recently uploaded (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Rest & RESTful WebServices

  • 2. Agenda? • What is REST? • What is RESTful Webservices • HTTP-REST Request Basics • HTTP-REST Vocabulary • Authentication (OAuth) • OAuth 2.0 Web Server Flow • REST APIs using Apex REST • Resources
  • 3. What is REST? • REST stands for Representational State Transfer • It is an architectural pattern for developing web services as opposed to a specification. • REST web services communicate over the HTTP specification, using HTTP vocabulary: – Methods (GET, POST, etc.) – HTTP URI syntax (paths, parameters, etc.) – Media types (xml, json, html, plain text, etc) – HTTP Response codes.
  • 4. Continued … • Representational – Clients possess the information necessary to identify, modify, and/or delete a web resource. • State – All resource state information is stored on the client. • Transfer – Client state is passed from the client to the service through HTTP.
  • 5. Continued … The six characteristics of REST: 1. Uniform interface 2. Decoupled client-server interaction 3. Stateless 4. Cacheable 5. Layered 6. Extensible through code on demand (optional)
  • 6. What is RESTful Web Services ? • RESTful web services are web services which are REST based. • Stateless & cacheable. • Uses URI & HTTP methods. • Quiet light, extensible and simple services. • The reason behind the popularity of REST is that the applications we use are browser-based nowadays and top it all, REST is built on HTTP. • Main idea: Providing the communication between client and server over HTTP protocol rather than other complex architectures like SOAP and RPC etc.
  • 7. HTTP-REST Request Basics • The HTTP request is sent from the client. – Identifies the location of a resource. – Specifies the verb, or HTTP method to use when accessing the resource. – Supplies optional request headers (name-value pairs) that provide additional information the server may need when processing the request. – Supplies an optional request body that identifies additional data to be uploaded to the server (e.g. form parameters, attachments, etc.)
  • 8. Continued … Sample Client Requests: • A typical client GET request: • A typical client POST request: GET /view?id=1 HTTP/1.1 User-Agent: Chrome Accept: application/json [CRLF] Requested Resource (path and query string) Request Headers (no request body) POST /save HTTP/1.1 User-Agent: IE Content-Type: application/x-www-form-urlencoded [CRLF] name=x&id=2 Request Headers Request Body (e.g. form parameters) Requested Resource (typically no query string)
  • 9. Continued … • The HTTP response is sent from the server. – Gives the status of the processed request. – Supplies response headers (name-value pairs) that provide additional information about the response. – Supplies an optional response body that identifies additional data to be downloaded to the client (html, xml, binary data, etc.)
  • 10. Continued … • Sample Server Responses: HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1337 [CRLF] <html> <!-- Some HTML Content. </html> Response Status Response Headers Response Body (content)
  • 11. HTTP-REST Vocabulary HTTP Methods supported by REST: • GET – Requests a resource at the request URL – Should not contain a request body, as it will be discarded. – May be cached locally or on the server. – May produce a resource, but should not modify on it. • POST – Submits information to the service for processing – Should typically return the new or modified resource. • PUT – Add a new resource at the request URL • DELETE – Removes the resource at the request URL • OPTIONS – Indicates which methods are supported • HEAD – Returns meta information about the request URL
  • 12. Continued … A typical HTTP REST URL: • The protocol identifies the transport scheme that will be used to process and respond to the request. • The host name identifies the server address of the resource. • The path and query string can be used to identify and customize the accessed resource. http://my.store.com/fruits/list?category=fruit&limit=20 protocol host name path to a resource query string
  • 13. What is OAuth? • A simple open standard for secure API authentication. • Salesforce supports OAuth versions 1.0A and 2.0 authentication flows. • Types of OAuth 2.0 authetication flows: – OAuth 2.0 Web server—The Web server authentication flow is used by applications that are hosted on a secure server. A critical aspect of the Web server flow is that the server must be able to protect the consumer secret. – OAuth 2.0 user-agent—The user-agent authentication flow is used by client applications (consumers) residing in the user’s device. These consumers cannot keep the client secret confidential. – OAuth 2.0 username and password—The username-password authentication flow can be used to authenticate when the consumer already has the user’s credentials.
  • 14. Oauth 2.0 Web Server Flow
  • 15. Required Paramemters: • response_type—Value must be code for this flow. • client_id—Consumer key from the connected app definition. • redirect_uri—URI to redirect the user to after approval. This must match the value in the Callback URL field in the connected app definition exactly, or approval fails. This value must be URL encoded. Optional Parameters: • scope—The scope parameter enables you to fine-tune what the client application can access in a Salesforce organization like &scope=api%20id%20web%20refresh_tok en • state—Any state the consumer wants reflected back to it after approval, during the callback. This parameter is optional. This value must be URL encoded. https://login.salesforce.com/services/oauth2/aut horize
  • 16. Once the user approves the access, they are redirected to the URI specified in redirect_uri with the following values in the query string: • code—Authorization code the consumer must use to obtain the access and refresh tokens • • state—State that was passed into the approval step. This isn’t included if the state parameter wasn’t included in the original query string.
  • 17. After obtaining the authorization code, the Web server exchanges the authorization code for an access token. The consumer should make a POST directly to the token endpoint, with the following parameters: • grant_type—Value must be authorization_code for this flow. • client_id—Consumer key from the connected app definition. • client_secret—Consumer secret from the connected app definition. • redirect_uri—URI to redirect the user to after approval. This must match the value in the Callback URL field in the connected app definition exactly, and is the same value sent by the initial redirect. • code—Authorization code obtained from the callback after approval. POST /services/oauth2/token HTTP/1.1 Host: login.salesforce.com grant_type=authorization_code&code=aPrxsmIEeq M9PiQroGEWx1UiMQd95_5JUZ VEhsOFhS8EVvbfYBBJli2W5fn3zbo.8hojaNW_1g% 3D%3D&client_id=3MVG9lKcPoNI NVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0QqEW hqKpoW3svG3XHrXDiCQjK1mdgAvhCs cA9GE&client_secret=1955279925675241571& redirect_uri=https%3A%2F%2Fwww.mysite.com% 2Fcode_callback.jsp
  • 18. After the request is verified, Salesforce sends a response to the client. The following parameters are in the body of the response: • access_token—Salesforce session ID that can be used with the Web services API. • refresh_token—Token that can be used in the future to obtain new access tokens (sessions). • token_type—Value is Bearer for all responses that include an access token.
  • 19. REST APIs using Apex REST • Following is the example : @RestResource(urlMapping='/Account/*') global with sharing class MyRestResource { @HttpGet global static Account doGet() { RestRequest req = RestContext.request; RestResponse res = RestContext.response; String accountId = req.requestURI.substring (req.requestURI.lastIndexOf('/')+1); Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId]; return result; } }
  • 20. Continued … Setting up an Apex REST endpoint • To declare a class as a custom endpoint, you only need to annotate a global class with “@RestResource” and define the name of the endpoint. @RestResource(urlMapping='/Account/*') global with sharing class MyRestResource { Full URI : “https://na8.salesforce.com/services/apexrest/ Account”
  • 21. Continued … Using GET HTTP GET defines data as a series of query parameters in the URI itself. For example, here’s a URI: https://na8.salesforce.com/services/apexrest/Account/001S000000ijvtwI AA @HttpGet global static Account doGet() { RestRequest req = RestContext.request; RestResponse res = RestContext.response; String accountId = req.requestURI.substring (req.requestURI.lastIndexOf('/')+1); Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId]; return result; }
  • 22. Resources • Digging Deeper into OAuth 2.0 on Force.com • OAuth 2.0 Web Server Authentication Flow • Getting Started with the Force.com REST API • Creating REST APIs using Apex REST

Editor's Notes

  1. Paraphrased from Wikipedia: The REST architectural style describes six constraints applied to the architecture: Uniform interface This is the API of the web service, describing operations and data structures. It simplifies and decouples the architecture of both client and server, enabling each to evolve independently. Client–server decoupling Clients are separated from servers by a uniform interface. For portability, clients must not concern themselves with data storage. For simplicity and scalability, servers must not concern themselves with the UI or user state. Servers and clients may be replaced and developed independently, as long as the interface is not altered. Stateless No client context should be store on the server between requests. Each request contains all of the information necessary to service the request and session state is held in the client. The server can be stateful, but server-side state must be addressable by URL as a resource. This makes servers: More scalable. More visible for monitoring. More reliable in the event of partial network failures Cacheable Clients may cache responses, so responses must define whether they are cachable to prevent clients reusing stale or inappropriate data in response to further requests. Well-managed caching can eliminate repetitive client–server interactions, further improving scalability and performance. Layered system A client’s connection to a server may pass directly to the service or through several intermediaries, allowing: Scalability by enabling load balancing and by providing shared caches The enforcement of security policies. Code on demand (optional) Servers may temporarily extend or customize the functionality of a client by transferring logic to be executed. (e.g. client-side JavaScript) If a service violates any constraint other than “code on demand”, it cannot strictly be referred to as REST web service. Complying with these constraints, and thus conforming to the REST architectural style, will improve a service’s Performance Scalability Simplicity Modifiability Visibility Portability Reliability
  2. Resource – identified by a URL (or uniform resource locator) Method – the action verb to perform on a resource e.g. GET, POST, PUT, DELETE, etc. Request Headers – name-value pairs of meta-information about the request e.g. Content types expected by the client Request Body – data to be streamed from the client to the server e.g. Attachments, form parameters, etc.
  3. Note: A REST web service may return the representation of a resource in many formats (HTML, XML, JSON, binary). It is the client’s responsibility to use the “Accept” request header to identify the expected content type of the returned resource.
  4. Status – An HTTP status code and status message e.g. 404 Not Found, 200 OK Response Headers – name-value pairs of meta-information about the response e.g. Content-Type Response Body – Additional data to be streamed from the server to the client e.g. HTML document, XML document, binary data
  5. HTTP Methods: GET – The same request URL should return the same resource every time. The request URL should represent a web resource. POST – A generic method for submitting information to the service. The outcome is defined by the service. The request URL need not represent a web resource. PUT – Adds a new resource at the request URL. The resource should then be available through a GET request using the same request URL. DELETE – Removes the resource at the request URL. The resource should no longer be available via a GET request at that URL. OPTIONS – Indicates which HTTP methods are supported at the request URL. Useful for identifying HEAD – Same as GET but only returns meta-information about the resource. The response body will be empty. Useful for requesting information about a resource without having to request the resource itself. Other HTTP verbs are NOT typically supported in a REST service. The above guidelines are required if you wish to remain compliant with the HTTP specification Actual usage of HTTP verbs may vary from implementation to implementation. When producing a service for consumption by a third-party, it is recommended that the service adhere to the HTTP specification Difference between POST and PUT: “The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.” – Emphasis added, W3C HTTP Method specification, referenced at end of presentation Methods Naving No Request Body: GET, DELETE, OPTIONS, HEAD Methods Having a Request Body: POST – body may contain form parameters or other information to be uploaded to the service PUT – body contains the resource to be represented at the request URL Methods Supplying No Response Body HEAD OPTIONS