0% found this document useful (0 votes)
9 views50 pages

Chapter 4A REST intro_

Uploaded by

kefon41944
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views50 pages

Chapter 4A REST intro_

Uploaded by

kefon41944
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Chapter 4:RESTful web

services
Outline
• REST API CONCEPTS
• JSON
• JAX-RS
What is REST?
• REpresentational State Transfer
PhD by Roy Fielding
The Web is the most successful application on the Internet
What makes the Web so successful? Discussion point .
• Addressable Resources
Every “thing” should have an ID
Every “thing” should have a URI
• Constrained interface
Use the standard methods of the protocol
HTTP: GET, POST, PUT, DELETE
• Resources with multiple representations
Different applications need different formats
Different platforms need different representations (XML + JSON)
• Communicate statelessly
Stateless application scale
Any difference with SOAP?

• Actually only the difference is how clients access our service.


• Normally, a service will use SOAP, but if you build a REST service, clients
will be accessing your service with a different architectural style (calls,
serialization like JSON, etc.).
• REST uses some common HTTP methods to
insert/delete/update/retrieve information which is below:

• GET - Requests a specific representation of a resource


• PUT - Creates or updates a resource with the supplied representation
• DELETE - Deletes the specified resource
• POST - Submits data to be processed by the identified resource
• Every “thing” has a URI
Addressability

http://sales.com/customers/323421 http://sales.com/customers/32341/address

• From a URI we know


The protocol (How do we communicate)
The host/port (Where it is on the network)
The resource path(What resource are we communicating with)
Describing a URI

http://sales.com/customers/323421/customers/{customer-id}
• Human readable URIs: Desired but not required

• URI Parameters
http://sales.com/customers?zip=49009

• Query parameters to find other resources


http://sales.com/cars/mercedes/amg/e55;color=black

• Matrix parameters to define resource attributes


• Example:
• https://example.com/resource;attribute1=value1;attribute2=value2
Implications of a Uniform Interface
• Intuitive
You know what operations the resource will support
• Predictable behavior/Simplicity and Decoupling
GET - readonly and idempotent. Never changes the state of the resource
PUT - an idempotent insert or update of a resource.
Idempotent because it is repeatable without side effects.
DELETE - resource removal and idempotent.
POST - non-idempotent, “anything goes” operation
• Clients, developers, admins, operations know what to expect
Much easier for admins to assign security roles
For idempotent messages, clients don’t have to worry about duplicate
messages.
REST
"Representational State Transfer is intended to evoke an image of how a well-
designed Web application behaves: a network of web pages (a virtual state-
machine), where the user progresses through an application by selecting links
(state transitions), resulting in the next page (representing the next state of
the application) being transferred to the user and rendered for their use."
Why REST?
• Less overhead (no SOAP envelope to wrap every call in)
• Less duplication (HTTP already represents operations like DELETE, PUT, GET, etc. that have to
otherwise be represented in a SOAP envelope).
• More standardized - HTTP operations are well understood and operate consistently.
• Some SOAP implementations can get finicky.
• More human readable and testable (harder to test SOAP with just a browser).
• Don't need to use XML (well, you kind of don't have to for SOAP either but it hardly makes sense
since you're already doing parsing of the envelope).
• Libraries have made SOAP (kind of) easy. But you are abstracting away a lot of redundancy
underneath as I have noted. Yes, in theory, SOAP can go over other transports so as to avoid riding
atop a layer doing similar things, but in reality just about all SOAP work you'll ever do is over HTTP.
REST Data Elements

• Resources and Resource Identifiers


•Uniform Interface (GET, PUT, POST, DELETE)
•Resource Oriented
•Simple and simple is beautiful

HTTP Method CRUD Desc.


POST CREATE Create -
GET RETRIEVE Retrieve Safe,Idempotent,Cacheable
PUT UPDATE Update Idempotent
DELETE DELETE Delete Idempotent
REST Core Idiologies

• Simple is better
• The web works and works well
• Some web services should follow the “way of the
web”.
REST API EXAMPLE: Delicious

URL http://del.icio.us/api/[username]/book marks/


Method GET
Querystring tag= Filter by tag
dt= Filter by date
start= The number of the first bookmark to return

end= The number of the last bookmark to return

Returns 200 OK & XML


(delicious/bookmarks+xml)
401 Unauthorized
404 Not Found
Example: http://del.icio.us/api/example_user/bookmarks/?tag=technology&dt=2023-01-01&start=1&end=10
REST API EXAMPLE: Delicious

URL http://del.icio.us/api/[usern ame]/bookmarks/


Method POST
Request Body XML
(delicious/bookmark+xml)
Returns 201 Created & Location
<delicious>
401 Unauthorized <bookmark>
415 Unsupported Media Type <title>Example Bookmark</title>
<url>https://example.com</url>
<tags>
<tag>example</tag>
<tag>test</tag>
</tags>
</bookmark>
</delicious>
REST API EXAMPLE: Delicious

URL http://del.icio.us/api/[usern ame]/bookmarks/[hash]


Method DELETE
Returns 204 No Content
401 Unauthorized
404 Not Found
Designing services with a Uniform Interface
• When in doubt, define a new resource
• /orders
GET - list all orders
POST - submit a new order
• /orders/{order-id}
GET - get an order representation
PUT - update an order
DELETE - cancel an order
• /orders/average-sale
GET - calculate average sale
• /customers
GET - list all customers
POST - create a new customer
• /customers/{cust-id}
GET - get a customer representation
DELETE- remove a customer
• /customers/{cust-id}/orders
GET - get the orders of a customer
Resources with Multiple Representations

• HTTP Headers manage this negotiation


 CONTENT-TYPE: specifies MIME type of message body
 ACCEPT: comma-delimited list of one or more MIME types the client
would like to receive as a response
 In the following example, the client is requesting a customer
representation in either XML or json format
GET /customers/33323

ACCEPT: application/xml, application/json


• Preferences are supported and defined by HTTP specification
GET/customers/33323 ACCEPT: text/html;q=1.0,
application/json;q=0.5;application/xml;q=0.7
REST APIs Revisited
 An API is how a piece of code communicates with another piece of
code.
Example: You can write a function and then expose it with public access
modifiers so that other classes can use it.
That function signature is an API for that class.
However, APIs that are exposed using these classes or libraries only allow
internal communication inside a single application or an individual service.
You would like to integrate two or more services? This is where system-wide
APIs help us.
REST is the most popular, and it has become the standard for writing APIs for
integration and web app consumption.
REST fundamentals…
• Each URI works as an API resource. Therefore, we should use
nouns as endpoints instead of verbs.
• RPC-style endpoints use verbs,
• for example, /api/v1/ getPersons.
• In comparison, in REST, this endpoint could be simply written as
/api/v1/persons.
• The REST endpoint is a unique URI that represents a REST
resource. For example, https:// demo.app/api/v1/persons is
a REST endpoint.
REST is based on the client-server concept
• The client calls the REST API and the server responds.
• REST allows a client (that is, a program, web service, or UI app) to talk
to a remotely (or locally) running server (or web service) using HTTP
requests and responses.
• The client sends an API command wrapped in an HTTP request to the
web service.
• This HTTP request may contain a payload (or input) in the form of query
parameters, headers, or request bodies.
• The called web service responds with a success/failure indicator and the
response data is wrapped inside the HTTP response.
• The HTTP status code normally denotes the status, and the response body
contains the response data.
• For example, an HTTP status code of 200 OK normally represents success.
REST…
An HTTP request is self-descriptive and has enough context for
the server to process it. Therefore, REST calls are stateless.
States are either managed on the client side or on the server
side.
A REST API does not maintain its state. It only transfers states
from the server to the client or vice versa. This is why it is called
REpresentational State Transfer, or REST for short.
REST operates using three key components:
• Resources and URIs
• HTTP methods
• HATEOAS
Handling resources and URIs
• URI syntax : scheme:[//authority]path[?query][#fragment]
• Scheme: This refers to a non-empty sequence of characters followed
by a colon (:). scheme starts with a letter and is followed by any
combination of digits, letters, periods (.), hyphens (-), or plus
characters (+).
• Scheme examples include HTTP, HTTPS, MAILTO, FILE, and FTP.
• URI schemes must be registered with the Internet Assigned Numbers
Authority (IANA). URI Examples:
• www.packt.com
• index.html: This contains no scheme nor authority. It only contains the path.
• https://www.packt.com/index.html:
mailto:[email protected]
telnet://192.168.0.1:23/
ldap://[2020:ab9::9]/c=AB?objectClass?obj
URI syntax…
• Authority: This is an optional field and is preceded by //. It consists of the following
optional subfields:
• Userinfo: This is a subcomponent that might contain a username and a password, which are both
optional.
• Host: This is a subcomponent containing either an IP address or a registered host or domain
name.
• Port: This is an optional subcomponent that is followed by a colon (:).
• Path: A path contains a sequence of segments separated by slash characters (/).
• Query: This is an optional component and is preceded by a question mark (?). The query
component contains a query string of non-hierarchical data.
• Each parameter is separated by an ampersand (&) in the query component and
parameter values are assigned using an equals (=) operator.
• Fragment: This is an optional field and is preceded by a hash (#). The fragment
component includes a fragment identifier that gives direction to a secondary resource.
Class activity
• https://user:[email protected]:8080/path/to/resource
?key1=value1&key2=value2#section1
Questions:
1.What is the scheme? Identify errors in the following URIs and
2.Identify the authority and its subfields: rewrite them correctly:
1. Userinfo
2. Host 1.htp://example.com/path
3. Port
3.What is the path?
2.https://:8080/resource#fragment
4.What are the query parameters? 3.ftp://username:password@@host/resource
Provide their keys and values.
1.What is the fragment?
What is HATEOAS?
• With HATEOAS, RESTful web services provide information dynamically
through hypermedia.
• Hypermedia is a part of the content that you receive from a REST call
response.
• This hypermedia content contains links to different types of media,
such as text, images, and videos.
• Hypermedia links can be contained either in HTTP headers or the
response body.
• Analyze the response of the following command:
$ curl -v https://api.github.com/users
JSON
Example: a JSON array containing objects with Email and Name field
What is JSON?
const data = [
• JavaScript Object Notation {
• Lightweight syntax for representing data "Email": "[email protected]",
• Easier to “parse” for JavaScript client code "Name": "Bob"
• Alternative to XML in AJAX applications },
{
data.forEach(person => { "Email": "[email protected]",
console.log(`Name: ${person.Name}, Email: "Name": "Mark"
${person.Email}`); },
}); {
// Accessing individual elements "Email": "[email protected]",
console.log(data[0].Name); // Output: Bob "Name": "John"
console.log(data[1].Email);
//Output:[email protected] }
];
• The role of the JSON marshalling
Processing JSON data and unmarshalling components in
a typical Java RESTful web service
implementation
• Two type of models:
• Object model - the entire JSON
data is read into memory in a tree
format
• Streaming model: data can be
read or written in blocks. This
model does not read the entire
JSON content into the memory to
get started with parsing; rather, it
reads one element at a time
JAX-RS API
• Some of the popular JAX-RS implementations are as follows:
•Jersey RESTful web service framework:
This framework is an open source framework for developing RESTful web
services in Java.
It serves as a JAX-RS reference implementation.
•Apache CXF: This framework is an open source web services
framework. CXF supports both JAX-WS and JAX-RS web services.
•RESTEasy: This framework is an open source project from JBoss, which
provides various modules to help you build a RESTful web service.
•Restlet: This framework is a lightweight, open source RESTful web
service framework. It has good support for building both scalable
RESTful web service APIs and lightweight REST clients, which suits
mobile platforms well.
JAX-RS…
• JCP Specification
• Lead by Sun, Marc Hadley
• Currently in public draft (which means final draft right around the corner)
• Annotation Framework
• Dispatch URI’s to specific classes and methods that can handle requests
• Allows you to map HTTP requests to method invocations
• IMO, a beautiful example of the power of parameter annotations
• Nice URI manipulation functionality
JAX-RS Annotations
• @Path
Defines URI mappings and templates
• @ProduceMime, @ConsumeMime
What MIME types does the resource produce and consume
• @GET, @POST, @DELETE, @PUT, @HEADER
Identifies which HTTP method the Java method is interested in
@OPTIONS
• designates a method to respond to the HTTP OPTIONS requests.
This method is useful for obtaining a list of HTTP methods
allowed on a resource.
JAX-RS Parameter Annotations
• @PathParam
Allows you to extract URI parameters/named URI template segments
• @QueryParam
Access to specific parameter URI query string
• @HeaderParam
Access to a specific HTTP Header
• @CookieParam
Access to a specific cookie value
• @MatrixParam
Access to a specific matrix parameter
• Above annotations can automatically map HTTP request values to
String and primitive types
Class types that have a constructor that takes a String parameter
Class types that have a static valueOf(String val) method
List or Arrays of above types when there are multiple values
• @Context
Access to contextual information like the incoming URI
@PathParam
//Other imports removed for brevity
• JAX-RS offers annotations to pull javax.ws.rs.PathParam
information out of a request. You
can use this offering to extract the @Path("departments")
following parameters from a public class DepartmentService {
request: a query, URI path, form, @DELETE
cookie, header, and matrix @Path("{id}")
• injects (or binds) the value of the public void
matching path parameter present in removeDepartment(@PathParam("id") Short
the URI path template into a class deptId) {
field, a resource class bean property removeDepartmentEntity(deptId);
(the getter method for accessing }
the attribute), or a method
parameter //Other methods removed for brevity
}
@QueryParam
• injects the value(s) of a HTTP query parameter into a class field, a
resource class bean property (the getter method for accessing the
attribute), or a method parameter.

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Department>
findAllDepartmentsByName(@QueryParam("name") String deptName) {
List<Department> depts= findAllMatchingDepartmentEntities
(deptName);
return depts;
}
@MatrixParam
• Matrix parameters are another way of defining parameters in the URI
path template. The matrix parameters take the form of name-value
pairs in the URI path, where each pair is preceded by semicolon (;).

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("matrix")
public List<Department>
findAllDepartmentsByNameWithMatrix(@MatrixParam("name") String
deptName, @MatrixParam("city") String locationCode) {
List<Department> depts=findAllDepartmentsFromDB(deptName,
city);
return depts;
} .The URI path used in this example looks like
/departments;name=IT;city=Addis Ababa.
@HeaderParam
• The HTTP header fields provide necessary information about the
request and response contents in HTTP. For example, the header field,
Content-Length: 348, for an HTTP request says that the size of the
request body content is 348 octets (8- bit bytes).
• injects the header values present in the request into a class field, a
resource class bean property (the getter method for accessing the
attribute), or a method parameter.
@POST
public void createDepartment(@HeaderParam("Referer")
String referer, Department entity) {
logSource(referer);
createDepartmentInDB(department);
}
@FormParam
submit button on the HTML form, the department details that you entered will be posted to the REST URI,
/resources/departments

<body>
<form method="POST" action="/resources/departments"> @Path("departments")
public class DepartmentService {
Department Id:
@POST
<input type="text" name="departmentId"> @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
<br> public void createDepartment(@FormParam("departmentId")
short
Department Name:
departmentId,
<input type="text" name="departmentName"> @FormParam("departmentName") String departmentName) {
<br> createDepartmentEntity(departmentId, departmentName);
}
<input type="submit" value="Add Department" />
}
</form>
JAX-RS Resource Classes
• JAX-RS annotations are used on POJO
@Path("/items")
public class ItemResource {
classes
@GET
• The default component lifecycle is per- @Path("/{id}")
public Response getItemById(@PathParam("id") int itemId) {
// Retrieve item information based on ID
request }

@POST
Same idea as @Stateless EJBs public Response createItem(Item newItem) {
// Create a new item
• Root resources identified via @Path }
}

annotation on class.
JAX-RS
@Path(“/orders”)
public class OrderService {

@Path(“/{order-id}”)
@GET
@ProduceMime(“application/xml”)
String getOrder(@PathParam(“order-id”) int id) {

}
}
Annotations for specifying request-response
media types
• The Content-Type header field in HTTP describes the
body's content type present in the request and response
messages.
• The content types are represented using the standard
Internet media types
• JAX-RS allows you to specify which Internet media types of
representations a resource can produce or consume by
using the @javax.ws.rs.Produces and
@javax.ws.rs.Consumes annotations, respectively.
@Produces
• The @javax.ws.rs.Produces annotation is used for defining the
Internet media type(s) that a REST resource class method can return
to the client.
• You can define this either at the class level (which will get defaulted
for all methods) or the method level.
• The method-level annotations override the class-level annotations.
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("departments")
@Produces(MediaType.APPLICATION_JSON)
public class DepartmentService{
//Class implementation goes here...
}
Classwork
• Create a JAX-RS resource class that handles basic
CRUD (Create, Read, Update, Delete) operations
for managing a list of "tasks."
Default Response Codes import javax.ws.rs.GET;
import javax.ws.rs.Path;
• GET and PUT import javax.ws.rs.Produces;
200 (OK) @Path("departments")
public class DepartmentService {
• DELETE and POST
@GET
200 (OK) if content sent back with response
@Path("count")
204 (NO CONTENT) if no content sent back
@Produces("text/plain")
public Integer getTotalDepartments() {
return findTotalRecordCount();
}
//Rest of the code goes here
}
Response Object
• JAX-RS has a Response and ResponseBuilder class
Customize response code
Specify specific response headers
JAX-RS allows you to return additional metadata via the
Specify redirect URLs
javax.ws.rs.core. Response class that wraps the entity and
Work with variants additional metadata such as the HTTP headers, HTTP cookie,
and status code. You can create a Response instance by using
@GET javax.ws.rs.core.Response.ResponseBuilder as a factory.
Response getOrder() {
ResponseBuilder builder = Response.status(200);
builder.type(“text/xml”).header(“custom-header”, “33333”);
return builder.build();
}
The use of the Response class to return the response
content along with the additional HTTP header fields
Best practices for designing REST APIs
Using nouns and not verbs when naming a resource in the endpoint
path
 Example: POST /licenses: This is for creating a new license.
Using the plural form for naming the collection resource in the
endpoint path
Versioning your APIs
 Using headers: example: Accept: application/vnd.github.v3+json
 Using an endpoint path: https://demo.app/api/v1/persons.
Using hypermedia (HATEOAS)
Two advantages if you provide explicit URL links in a response.
 First , the REST client is not required to construct the REST URLs on their own.
 Second, any upgrade in the endpoint path will be taken care of automatically
and this, therefore, makes upgrades easier for clients and developers
Nesting resources
• GET /customers/1/addresses: This returns the collection of addresses for
customer 1
• GET /customers/1/addresses/2: This returns the second address of
customer 1
• POST /customers/1/addresses: This adds a new address to customer 1’s
addresses
• PUT /customers/1/addresses/2: This replaces the second address of
customer 1
• PATCH /customers/1/addresses/2: This partially updates the second
address of customer 1
• DELETE /customers/1/addresses/2: This deletes the second address of
customer 1
Securing APIs
• Always use HTTPS for encrypted communication.
• Always look for OWASP’s top API security threats and
vulnerabilities.
• Secure REST APIs should have authentication in place.
• REST APIs are stateless; therefore, REST APIs should not use
cookies or sessions.
• Instead, they should be secured using JWT or OAuth 2.0-based
tokens.
• stateless applications/ services => each service maintains its own
current state, even within a sequence of interactions, and doesn’t
expect others to do so on its behalf.
Introducing our Project: e-commerce app

Adding/removing/updating the products in the cart


Placing an order
Modifying the shipping address
Support for a single currency
The e-commerce app architecture
Review Questions

1. Why have RESTful web services become so popular and,


arguably, the industry standard?
2. What is the difference between RPC and REST?
3. How would you explain HATEOAS?
4. What error codes should be used for server-related issues?
5. Should verbs be used to form REST endpoints, and why?

You might also like