REST API Best Practice on Java, .Net & PHP
Contents
Target Audience: CAST Administrators
Summary: This documentation is aimed at CAST Administrators who would need to configure REST based applications using CAST AIP. It provides a guide based on field experience of how best to configure REST based applications using CAST AIP so that similar configurations can be reused. The typical examples given below have been applied on different versions of CAST AIP based on various requirements.
These configurations are used over and above CAST AIP 8.2.x EJB Specification offering (see Reference Materials below for links) to overcome limitations. The applicability of this guide should have assessed for newer versions of CAST AIP and Extension.
Introduction to REST
This section gives a brief overview of the framework.
REST (REpresentation State Transfer) describes an architectural style of networked systems such as Web applications. It was first introduced in 2000 in a Ph.D dissertation by Roy Fielding, one of the principal authors of the HTTP specification. REST refers to a collection of architecture constraints and principles. An application or design, if it meets those constraints and principles, is RESTful. Important REST principles for Web applications is that the interaction between the client and server is stateless between requests. Everything is a Resource In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web.
REST Applicability & Implementations:
REST vs technology
Implementation APIs
Implementation
Versions
Support
JSR
JAX-RS
Apache CXF
3.0.14
311 & 339
YES
Jersey
2.15
312 & 339
YES
RESTEasy
3.1.4
313 & 339
YES
Spring
3.x
314 & 339
YES
RESTlet
2.3.10
No directly Support
Wink
No directly Support
Cuubez
1.1.1
No directly Support
JELLO
1.2.7
No directly Support
1.1.3
2.0.12
Tastypie supports HATEOAS[7]
0.13.3
WSO2
4.7.0
3
Symfony Framework
3.3
SOAP/REST Comparision
SOAP and REST can't be compared directly. Because SOAP is a protocol but REST is an Architectural style and a design for network-based software architectures.
SOAP (Protocol)
REST (Architectural style)
JAX-WS is the java API for SOAP web services.
JAX-RS is the java API for RESTful web services.
WSDL: Web Service Description Language
WADL: Web Application Description Language
REST is more dynamic, no need for creating and updating UDDI
SOAP only support XML. Requires more bandwidth in terms of payload.
REST supports different format like text, JSON, XML etc. Sending data over the network as JSON is cheaper than sending it in XML format in terms of payload.
SOAP can use almost any transport to send the request.
Supports SSL, WS-Security, WS-AtomicTransaction, WS-ReliableMessaging which adds some enterprise security features.REST uses HTTP/HTTPS (Transport level security).
SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources.
REST is limited by its HTTP protocol so its transaction support is neither ACID compliant nor can provide two phase commit across distributed transnational resources.
SOAP uses services interfaces to expose the business logic.
REST uses URI to expose business logic.
SOAP defines standards to be strictly followed. SOAP is a successor of XML-RPC and is very similar, but describes a standard way to communicate.
REST does not define too much standards like SOAP. Though as per need "Richardson Maturity Model" can be applied.
Focus on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.
REST is for are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.
SOAP based reads cannot be cached.
REST has better performance and scalability. REST reads can be cached.
SOAP describes functions, and types of data.
WSDL defines contract between client and service.Everything in REST is considered as a resource identified by an URI using POST, GET, PUT, DELETE operations which are similar to Create, Read, update and Delete(CRUD) operations.
SOAP has successful/retry logic built in and provides end-to-end reliability even through SOAP intermediaries.
It doesn't have a standard messaging system and expects clients to deal with communication failures by retrying.
Versions of REST Framework supported by CAST
This section highlights the REST versions supported by CAST AIP version 8.3.x.
CAST Technology support for JAX-RS - 1.2 & Spring MVC - 1.2 :
- JAX-RS - 1.2 : http://doc.castsoftware.com/display/DOCEXT/Web+Services
- Spring MVC - 1.2 : http://doc.castsoftware.com/display/DOCEXT/Web+Services
- WCF - All versions up to 4.5 : http://doc.castsoftware.com/display/DOCEXT/WCF+support+for+Csharp+and+VB.NET+-+1.2
- PHP - 5.x : http://doc.castsoftware.com/display/DOCEXT/PHP+1.1
Where ever we find REST implementation, irrespective of any technology/implementation below are the thumb rule needs to be followed for....
Standard flow: CAST View with REST Layers
Where ever we find REST implementation, irrespective of any technology/implementation below are the thumb rule needs to be followed for....
1. REST Intermediary – REST Service PROVIDER + CONSUMER
2. REST Entry point – REST Service PROVIDER
3. REST End point – REST CONSUMER
REST as Intermediate - Service PROVIDER + CONSUMER
This is the most common scenario, of REST implementation. (i.e.,) There are cases, REST Services are exposed, and these REST services will be consumed with in application boundary source code.
REST Entry point: REST Service PROVIDER
As in enterprise application REST Endpoints will be we exposed for the consumption of external application / up-stream request. In this kind of scenario those exposed Endpoints need to be treated as the Entry point.
REST End point: REST CONSUMER
Considering application boundary our application may need to consume, External application's REST Endpoint.
In these cases those REST End point services which are being consumed by us will be treated as the Endpoint in the transaction.
For an example there could be external REST service(Payment gateway) exposed by outside to the boundary of an application. Our application need to consume those service then we may have REST client as END point.
REST in Java
This section gives a brief overview of REST Implementation in Java.
File Types expected for CAST Analysis
This section highlights all the file types that can be expected to be delivered if the application has implemented this framework.
Java |
---|
.js |
How to identify the implementation of Java:
This section details the approach for identifying the presence in java
REST implementation can be in many from. However in general you may find through Spring, Jersey framework as described belowJava Spring Controller Jersey @RestController
@RequestMapping("/path")
@Path(“/path”)
Using the above "Annotation" you find in your code (i.e.,) JavaScript making call to your REST asCall from JavaScript:
REST Controller (.java file)
(.java file)
Spring to JAX-RS Cheat Sheet:
This is not an exhaustive list, but it does include the most common annotations.
Spring Annotation
JAX-RS Annotation
@RequestMapping(path = "/END_POINT")
@Path("/END_POINT")
@RequestMapping(method = RequestMethod.POST)
@POST
@RequestMapping(method = RequestMethod.GET)
@GET
@RequestMapping(method = RequestMethod.DELETE)
@DELETE
@ResponseBody
N/A
@RequestBody
N/A
@PathVariable("id")
@PathParam("id")
@RequestParam("xyz")
@QueryParam('xyz")
@RequestParam(value="xyz"
@FormParam("xyz")
@RequestMapping(produces = {"application/json"})
@Produces("application/json")
@RequestMapping(consumes = {"application/json"})
@Consumes("application/json")
Java REST Description:
JAX-RS: Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST service. JAX-RS is part of the Java EE6, and make developers to develop REST web application easily.
Jersey: Jersey is the open source, production quality, JAX-RS (JSR 311) Reference Implementation for building RESTful Web services. But, it is also more than the Reference Implementation. Jersey provides an API so that developers may extend Jersey to suit their needs.
How to configure Java REST in CAST AIP:
This section describes all the CAST configuration steps to be followed in order to configure Java REST based application.
The CAST configuration steps given below are based on the code snippets showing a typical transaction flow such as html → Controller → Angular JS Service → REST http GET/POST Operation → Method calls → "File Operation". The Controller is mandatory for REST implementation.Note that there can be multiple type of code implementation styles.
Server Manager Configuration
Once after successful CAST Extend - JAX-RS Annotations installation, Enable the extension through "Server Manager" as below:
Pre-Analysis Configuration
Install JAX-RS Extension from CAST Extend - JAX-RS Annotations. Manage it using Server Manager. Note that there is no need to create any exclusive CMS Job as mandated in other extensions.
Enlighten
This Section gives an overview of the Enlighten diagram
CMS Configuration
NATCC Configuration
This Section describes the TCC configuration which needs to be set.
Where ever we find REST implementation, irrespective of any technology/implementation below are the thumb rule needs to be followed for....REST as Intermediate - Service PROVIDER + CONSUMER
No special configuration required here.REST Entry point: REST as Service PROVIDER
REST End point: REST CONSUMER
REST in .Net
This section gives a brief overview of REST Implementation in Java.
Net’s Web API is an easy way to implement a RESTful web service using all of the goodness that the .net framework provides. Once you understand the basic principles of REST, then a .net Web API will be very easy to implement.
Web API is built on .net’s modular, pluggable pipeline model. This means that when a server hosting a web API receives a request, it passes through .nets request pipeline first. This enables you to easily add your own modules if you find that the default capabilities are not enough for your needs. With the recent announcements on ASP.net vNext this also means you can potentially host your Web API outside of Windows Server which opens up a whole range of usage cases. See http://www.asp.net/vnext for detail.
Web API uses the Controller and Action concepts from MVC so if you already understand .net MVC you are in a good place. If you don’t, then Web API is a great way to learn MVC.
File Types expected for CAST Analysis
This section highlights all the file types that can be expected to be delivered if the application has implemented this framework.
C# |
.cs |
How to identify the implementation of .Net
This section details the approach for identifying the presence in C#
Option 1
C# [ServiceContract] - Interface
[OperationContract] - Service
[WebInvoke] - REST declaration
Note: WCF meant for various implementation / features.
REST can be implemented by the above mentioned pattern.
Using the above elements you will be able find asEmpInfoService.cs
EmploeeeService.cs
Web.config
Option 2
This section details the approach for identifying the presence in C#
C# [HttpPost] - WebAPI
[Route] - Route class
ApiController - Controller class
Note: WCF meant for various implementation / features.
REST can be implemented by the above mentioned pattern.
Using the above elements you will be able find as
ValidateController.cs
.Net REST Description:
This section gives a brief overview of .Net REST.Web API uses the Controller and Action concepts from MVC so if you already understand .net MVC you are in a good place. If you don’t, then Web API is a great way to learn MVC.
Resources are mapped directly to controllers; you would typically have a different controller for each of your main data entities (Product, Person, Order etc). Web API uses the .net routing engine to map URLs to controllers. Typically, APIs are held within a ‘/api/’ route which helps to distinguish API controllers from other non-API in the same website.
Actions are used to map to specific HTTP verbs, for example you would typically have a GET action which returns all of the entities. This action would respond to /api/Products (where ‘products’ is your controller).How to configure .Net REST in CAST AIP:
Server Manager Configuration
NAPre-Analysis Configuration
NAEnlighten
CMS Configuration
NATCC Configuration
eFile
REST in PHP
File Types expected for CAST Analysis
This section highlights all the file types that can be expected to be delivered if the application has implemented this framework.
PHP |
---|
.php |
How to identify the implementation of PHP
This section details the approach for identifying the presence in PHP
PHP : You may find in your PHP Controller files as use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
Class <Class_name> extends Controller {
/**
* @JsonBody
* @Route("/order/{order_id}/update-billing", name="api_order_update", methods={"POST"})
* @param Address $address
* @ParamConverter("orderEntity", class="\Entity\Order", options={"id" = "order_id"})
* @return Response
*/
public function updateBilling(Address $address, OrderEntity $orderEntity) {
--------------
--------------
--------------
}
}
Sample implementation .htaccess file in your api folder http://localhost/api
RewriteEngine On
RewriteBase /api # if hosting api files on root use only /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]Define HTTP routes
$app->post('/users', 'updatedBilling');// Using HTTP POST Method and process updatedBilling function
function updatedBilling() {
global $app;
$req = $app->request(); // Getting parameter with names
$paramEmail = $req->params('email'); // Getting parameter with names
$sql = "INSERT INTO transaction_history(`name`,`email`,`ip`) VALUES (:name, :email, :ip)";
try {
$dbCon = getConnection();
..........................................................
$stmt->execute();
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}<?php
if($_POST){
echo post_to_url("{*}http://localhost/users*", $_POST);
} else{
?>
<form action="" method="post">
<input type="text" name="email" placeholder="Email" /><br>
<input type="submit" value="A D D" />
</form>
<?php
}
?>PHP REST Description:
This section gives a brief overview of PHP REST.How to configure PHP REST in CAST AIP:
Server Manager Configuration
NAPre-Analysis Configuration
NAEnlighten
CMS Configuration
NATCC Configuration
NA
Reference Materials
Topic
Link
JAX-RS vs Spring for REST Endpoints
Protecting JAX-RS Resources with RBAC and Apache Shiro
https://stormpath.com/blog/protecting-jax-rs-resources-rbac-apache-shiro
Difference between normal Spring MVC and Spring RESTful web service
Hypermedia , hypermedia format, hypermedia controls
Richardson Maturity Model
https://martinfowler.com/articles/richardsonMaturityModel.html#level3
HATEOAS
SOAP Vs REST
https://stackoverflow.com/questions/19884295/soap-vs-rest-differences
5 simple steps to create your first RESTful service
http://www.topwcftutorials.net/2013/09/simple-steps-for-restful-service.html
Practical guide to WCF RESTful service
http://www.topwcftutorials.net/2014/02/practical-wcf-restful-service.html
Service Layer Guidelines
Restful webservices in C#
RESTful programming
https://stackoverflow.com/questions/671118/what-exactly-is-restful-programming/671132#671132
Introduction to RESTFul Web Service
http://www.jcombat.com/spring/restful-web-service-introduction
RESTful Web Service example with Spring 4
http://www.jcombat.com/spring/restful-web-service-example-with-spring-mvc
Exception Handling in Spring RESTful Web Service
http://www.jcombat.com/spring/exception-handling-in-spring-restful-web-service
RESTful service with Spring and Jersey
Multi tier architecture for building Web RESTful services
http://prog3.com/sbdm/blog/leonzhouwei/article/details/9263785
Jersey 2.26-b06 User Guide
Introduction to Spring Web MVC framework
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html
PHP: Creating your First API with API Platform, in 5 Minutes
PHP library to support implementing representations for HATEOAS REST web services
Symfony PHP Controller https://symfony.com/doc/current/page_creation.html A Guide to Designing and Building RESTful Web Services with WCF 3.5
WCF - Creating REST Service Step by Step (A Simplest Approach)
Apache CXF : JAX-RS (JSR-339)
CAST AIP Documentation and Troubleshooting Guides
REST API Reference Documentation
http://doc.castsoftware.com/display/DOC83/REST+API+Reference+Documentation
RESTful web services (JSR 311 & 339)
CAST Technology support for JAX-RS - 1.2 & Spring MVC - 1.2