Chapter 4A REST intro_
Chapter 4A REST intro_
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?
http://sales.com/customers/323421 http://sales.com/customers/32341/address
http://sales.com/customers/323421/customers/{customer-id}
• Human readable URIs: Desired but not required
• URI Parameters
http://sales.com/customers?zip=49009
• Simple is better
• The web works and works well
• Some web services should follow the “way of the
web”.
REST API EXAMPLE: Delicious
@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