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.
- 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
- 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
- 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.
- 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.
- 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
- 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