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 (20)

Understanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple StepsUnderstanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple Steps
 
Web api
Web apiWeb api
Web api
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Introduction to REST - API
Introduction to REST - APIIntroduction to REST - API
Introduction to REST - API
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
 
Introduction to API
Introduction to APIIntroduction to API
Introduction to API
 
SOAP vs REST
SOAP vs RESTSOAP vs REST
SOAP vs REST
 
Restful web services ppt
Restful web services pptRestful web services ppt
Restful web services ppt
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
 
Rest api standards and best practices
Rest api standards and best practicesRest api standards and best practices
Rest api standards and best practices
 
RESTful Architecture
RESTful ArchitectureRESTful Architecture
RESTful Architecture
 
Ajax ppt
Ajax pptAjax ppt
Ajax ppt
 
What is an API?
What is an API?What is an API?
What is an API?
 
REST-API overview / concepts
REST-API overview / conceptsREST-API overview / concepts
REST-API overview / concepts
 
Soap vs rest
Soap vs restSoap vs rest
Soap vs rest
 
An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST
 

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

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
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
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Recently uploaded (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
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...
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
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?
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
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
 

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