How to Build a REST API in SAP Hybris Commerce

How to Build a REST API in SAP Hybris Commerce

Key takeaways

  • The RESTful architectural style of software communication is used to make a system flexible and scalable. Explore how to create a REST API in Hybris.

  • Documenting REST APIs is important. Know how to keep the records to influence the quality of code.

  • Find out the key concepts and features of Hybris Commerce RESTful Web Services.

  • Go through the flow of Hybris REST API and see the role of endpoints and methods used.

  • Learn how to use OOTB basics to create new functionality for specific needs.

  • Aimprosoft’s experience: read examples of API implementations that successfully work in our B2B and B2C online stores.

One of the most demanded services from Aimprosoft’s offering over a decade is Hybris development. Many clients got assistance from Hybris development company in the transformation from B2B to B2C, feature extension, and migration from Hybris alternatives. Technology may help in many challenging cases.

Communication behind the Hybris application interface doesn’t differ from the communication of any other web or mobile application. Here is a REST API standard in communication between a server-side and client, which is an adopted standard.

In this article, we’re going to cover steps and tips on how to build a REST API in Hybris.

What is a REST API?

Representational State Transfer, REST in short, is an architectural style that uses HTTP(S) as the data transfer protocol for requests and responses. It is a set of rules for a software developer on how they should arrange the writing of server application code so that all systems can easily exchange data and the application can be scaled.

Assume there is a server that receives inbound REST messages and sends some data instead of HTML, and the one who calls decides what to do with that data, whether to represent it on the web page or redirect. Requests can come from any client.

Unlike its predecessor, SOAP, REST is an architectural style rather than a standard protocol. This is why REST APIs are sometimes referred to as RESTful APIs. REST is a general style followed by API. The main advantage of the REST API is simplicity. However, it is tightly tied to HTTP(S) as the main communication way.

What is Hybris?

Hybris (now SAP Commerce Cloud) is an eCommerce Java-based product addressing the needs of B2B/B2C enterprises of omnichannel sales and customer experience that is a part of an SAP Customer Experience portfolio. Besides a diverse OOTB functionality, the platform is flexible to customizations. One of the ways to fit the SAP Commerce platform to specific business needs is a REST API that enables third-party web services and more.

A REST API for Hybris is SAP-backed and can be created by Hybris developers of software service companies like AImprosoft. Both target to marry SAP Commerce with any application.

Hybris is the premier provider of Volkswagen, Carlsberg, Henkel, Indesit, and others.

CHECK WHY

Like all serious things, there are the main principles. Let’s elaborate on them in our checklist to know how to make a REST API in Hybris.

Generating Hybris API Documentation

Comprehensive SAP Hybris Commerce API documentation helps in API adoption and governance. Hybris REST API templates (OCC templates) are documented in Swagger in OpenAPI format. It provides a well-structured approach to see the list of all available resources and learn details on how to use, integrate, and update APIs. It is based on Springfox that allows a specification to be generated automatically based on Spring configuration.

Developers can follow the best practices and document their APIs from a user’s perspective to streamline API exploration better. Precise definitions of used terms for requests, responses, methods, and resources will make peers the right and quick understanding.

Swagger provides information in two data formats, XML and JSON, the most popular data types for communication among clients. Note, when developing a custom REST solution, there are no limitations with data formats.

SAP Hybris REST API documentation in Swagger
Hybris REST API documentation in Swagger

OCC and its features

REST in the Hybris Commerce has its unique naming highlighting the omnichannel concept. Storefront Hybris APIs are named OCC REST, where OCC means Omni Commerce Connect. A set of OCC addons serves to provide new functionality for ecommerce projects. It tunes the communication between the Hybris platform commerce layer and web services.

Developing an SAP Hybris REST API, keep in mind transparency to live up to the Hybris concept. You can easily reuse data across the whole transaction flow with a REST API. That results in development speed increase and reduces the interface development costs. The OCC is designed to be smoothly integrated with other web systems and be an interface provider for third-party partners.

AddOns are here to accelerate sales through B2B/B2C systems leading to the desirable revenue.

READ HOW

Say you want to make secure transactions for customers and cards or any detached front-end application like third-parties or mobile interfaces, the OCC has a set of necessary features to accomplish the goal.

To develop a REST API in Hybris environment, first, pay attention to the main criteria or key features of it:

  • HTTP(S) is a management method within a client-server architecture with clients, servers, and resources.

  • Stateless calls mean separate and unconnected requests. This allows saving memory storage while keeping customer data between requests. Data is not preserved. Note that some ID (customer ID or cart ID) in this case can be provided for every request.

  • RESTful implementation is available with URL resources as type and identifier need to work with.

  • Data creation is based on the URL parameter list or RequestBody.

The OCC of higher version – 2 – primarily differs from its legacy predecessor by stateful interaction responses. It uses the same format XML or JSON for information deliveryб though. There is a separate servlet for OCC 2 API with deployment and configuration details in the web.xml.

Compared to the basic authentication, the OAuth 2.0 authorization for the commerce-driven OCC Web Services provides access without saving or even obtaining the user’s credentials. The REST-based communication is designed so that the refreshed tokens come from the client. When it sends, for example, an old token, a response with the instruction ‘update’ comes to the client. Then the client sends a request to refresh the token and receives a new access token.

Product information and reviews, cart and order details, optimized search, stock levels, points of service, promotions and vouchers, customer data, and user administration with a proper level of security is a list of functionality available for API clients by means of OCC.

The servlet for the OCC V2 REST API can be as follows:

...
    <servlet>
        <servlet-name>springmvc-v2</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>
                org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            </param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                de.hybris.platform.ycommercewebservices.v2.config.WebConfig
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc-v2</servlet-name>
        <url-pattern>/v2/*</url-pattern>
    </servlet-mapping>
...

SAP Commerce is rich for OCC APIs applicable in many use cases. However, you’re free to develop some custom features. The yocc extension will help you build new OCC extensions that you can apply with OCC APIs, subsequently extending your commerce project functionality.

The OCC REST API for Hybris is used for the Spartacus single-page accelerators (SPA). Accelerator in Hybris terms refers to a standards storefront generated by Hybris. That is one of the simple use cases developers face while working under online commerce projects.

A library of components Spartacus based on Angular created for developing branded JS-based storefronts for SAP Commerce Cloud interacts with Hybris Commerce using REST API.

While many OCC APIs are available within SAP Commerce, you can also develop custom functionality by using the yocc extension template to create new OCC extensions for use with OCC APIs.

Hybris Data Hub may raise your interest by its bridging characteristics.

I’M INTERESTED

Architecture of OCC REST API

In order to create an API in SAP Commerce, you should understand what is at its core. Every unit or system has a basic structure that explains how its components interact with each other. This is architecture.

The interactions of system components are supported by OСС APIs whose role is to set the Hybris commerce functionality in motion via RESTful Web service APIs.

SAP Commerce capabilities are multifaceted but in addition, the platform allows developers to save time for the first steps and build an API in SAP Commerce Cloud by using templates.

Look at commercewebservicescommons. This extension contains a core logic for ycommercewebservices and ycommercewebservicestest extensions. The latter is used for tests not being obligatory for creating a custom Hybris Commerce REST API. First, you can try ycommercewebservices as a template to develop your custom extension where you can add or change existing services.

To connect commerce platforms to the specific software, you need to know how to develop an API in Hybris. Let’s discover what endpoints are, how to use HTTP(S) methods to access them and steps of the standard flow.

What are endpoints?

Follow the idea about endpoints. An endpoint is the end of the communication channel for your application to interact with other applications. An API sends a request for data from a client to receive a response from a server. APIs access resources they need to carry out their function from endpoints where resources are located. Endpoints include URLs – Uniform Resource Locators that show the path information can be reached.

HTTP(S) methods of the OCC REST API

The main HTTP(S) methods are GET, POST, PUT, PATCH, and HEAD, indicating the operation type. If you build an API in Hybris, you can check a recommendation on how to use them with nuances of application because developers are allowed to use them in their own way.

Definition of the request types you will use with aт SAP Commerce REST API most frequently:

  • GET – trigger commerce facade methods (the layer where a code logic is) that look for and retrieve data from a server at the specified resource
  • POST – create an item and send it to the server (by separate URL parameters or RequestBody)
  • PUT – update an entire entity with uploaded data; missing fields are NULL or default value (by separate URL parameters or RequestBody)
  • PATCH – make partial updates (frequently minor, e.g., one field of the resource) to resources at a location (by separate URL parameters or RequestBody)
  • HEAD – retrieve the requested items information in the number set in the response header
  • DELETE – remove the resource.

Be ready that POST, PUT, and PATCH requests need to be validated in the OCC module as usual.

Address Controller in Swagger used in SAP Commerce projects
Address Controller in Swagger

REST API flow in Hybris

Steps one by one how an SAP Hybris Commerce REST full API works:

  1. A Web Service call passes through a token-based authorization OAuth2.

  2. URL to method resolver. A selection of controllers to process the request is defined here.

  3. Filtering. It stands for checking the information related to the incoming call to the server.

  4. Cache control is a stage of accumulating and freeing up the cache to enable statelessness.

  5. Data retrieval. The request reaches the commerce web services controller in commerce facades (most usually) to retrieve the data. It can or can’t require additional validation.

  6. Data validation of incoming requests is sent to the server.

  7. OCC error handling. If there is an error in the requested data, an OCC error response is shown (e.g., “Service not available”).

  8. Commerce services facades. The request reaches the business logic of the project, where the flow of code processing on the different code layers is activated.

  9. Database interaction. The sent request interacts with the database of the Hybris platform to find the requested information.

  10. Commerce services facades. On the way back, the information in a database structure goes through commerce facades.

  11. OCC error handling. Again, the OCC error mechanism checks the data for errors to respond to the client with the correct data.

  12. Data conversion. Retrieved data from the commerce facades is converted to the predefined DTO (data transfer object). DTO mapping shows data from a called URL. You can see it in the Example Value section in Swagger. Note, in the commerce layer, changes with data objects are impossible.

  13. Web Service Response. A response with the data in XML or JSON format is sent to the call if there are no errors or exceptions.

  14. AddOns here add custom logic while validation, conversion, or mapping processes, for example.

A REST API flow typical for SAP Hybris projects
The example of a REST API flow

The ycommercewebservices extension, for example, can be a starting point for you while developing the extended functionality of the commerce project. The Spring MVC framework lies in the core of its web services application. Thus, you can call the specific resources requesting a web services controller. As Hybris is built on Spring MVC, knowing how it works and the ability to use it will enable you to make customizations.

OOTB Web Services of Hybris

Hybris provides a wide variety of web services out of the box focused on different commerce needs. Below we are going to name a few to reveal the basics for your custom API implementations and a custom example to show how it can be.

RESTful APIs in Hybris differ from other APIs by URLs and access control. The point is in an approach of RESTful implementation in OCC. For example, there is no need to use the JSESSIONID cookie because starting with v2 an OCC RESTful API is stateless.

OAuth2 in Hybris provides four default roles for resource access:

  1. ROLE_CLIENT
  2. ROLE_CUSTOMERGROUP
  3. ROLE_TRUSTEDCLIENT
  4. ROLE_CUSTOMERMANAGERGROUP

Based on it, you can create any number of roles with capitalized names to set rules for access control. Access Control is used while Filtering the call’s data and in Web Service Controller.

Let’s see some of the implemented RESTful API examples that access resources from a particular user:

  • to get user resources, you can use this path

    https://localhost:9002/rest/v2/{baseSiteID}/users/{userID}/...
    
  • orders of a single user or as a global resource for all users (in the case, you have the proper rights) can be obtained this way

    https://localhost:9002/rest/v2/{baseSiteID}/users/{userID}/orders/{orderID}
    

Those are examples of rules for an SAP Commerce API under the RESTful standard available for use already.

Custom gift cards resources

Say you want to create a request to get information about gift cards of the specified users. You need to insert the gift card’s owner in the URL path. Non-anonymous gift cards for registered users are located under the following path:

https://localhost:9002/rest/v2/{baseSiteID}/users/{userID}/giftcards/{giftcardID}

Valid carID values are:

  • current represents the last modified gift card of the specified user.
  • ${code} is a code of the non-anonymous gift card and works for registered users only.

Gift cards of the specified user can be accessed this way if you are permitted to do so.

Customization and extension with REST APIs

The Spring MVC is at the core of the OCC Web Services. The Commerce Facades has a REST-based web services part. So it is possible to customize and extend a standard REST API with the ycommercewebservices extension by creating new AddOns easily.

Hybris differs by its simplicity and transparency. It is transferred into the structure principle of AddOns. The REST API extension scenario may look like this:

  1. define a Controller class with the getNewResource method;
  2. create a Controller in the \acceleratoraddon\web\src directory;
  3. get a request https://localhost:9002/rest/v2/{baseSiteId}/newResource (use v1 for OCC1);
  4. add the AddOn entry to the extensioninfo.xml by the addoninstall script and get generated the project.properties file.
@Controller
@RequestMapping(value = "/{baseSiteId}/newResource")
public class NewController
{
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public NewResourceWsDTO getNewResource()
    {
        return new NewResourceWsDTO("newSampleResource");
    }
}

An example of how to create a new endpoint while customizing or extending the existing REST API.

After the server was brought up and configured, a NewResource Controller will appear in Swagger.

Successful running after installation is expected provided that:

  1. <path autoload=”true” dir= … /> is the AddOn entry;
  2. the localextensions.xml file contains the addonsupport extension ( or it is loaded in the automatically loaded directory);
  3. the localextensions.xml file contains your new AddOn and a ycommercewebservices extension template (or they are in the automatically loaded directory);
  4. the project.properties.template file is defined properly for the AddOn.

Now you are armed to make your e-commerce system more flexible to reach the desired scalability. Hybris developers are that type of specialists who think in scale by default. Thus, the right set of starting tools can set off the development of incredible competitive solutions.

Want to add something specific for your SAP Hybris store?

Let’s discuss the extensions.

Contact us

The REST API Implementation cases in Hybris

Before wrapping up, it might be interesting for you to go through some implementation cases.

  1. JS-based custom storefront (SPA – Single Page Application in Hybris), be it on Spartacus, Vue.js, or any JS technology.

  2. Integration with third-party APIs. For example, we at Aimprosoft developed an online store based on the standard Hybris storefront with a Vue.js-based product catalog. Thus, a search was simplified a lot due to the user experience and the checkout experience left to be of a traditional storefront look. A buyer is able to search for products and add them to the cart with a Quick Order feature. When they pass on to the checkout, the standard storefront with address, payment, shipping address, and card.

  3. An SAP Hybris API integration solution is one more case when you can integrate your SAP Commerce Cloud with the partners via REST APIs. To connect a partner’s catalog to the Hybris-based store is a pretty frequent desire our B2B customers express. The smart integration can be done with REST endpoint access to keep the system integrity secured.

  4. The more enhanced functionality in 1811 and higher versions makes SAP Commerce Cloud API integration possible for both SAP ecosystem products (ERP, CRM) and any ad-hoc systems.

  5. And other challenging cases our Hybris developers can cope with.

Conclusion

Summing up, we would like to emphasize that Hybris has an excellent base of templates for developers who are going to make an API in Hybris. Developers can make great use of it and create excellent custom functionality to improve their business without wasting time reinventing the wheel. Since customers’ desires do not always coincide with OOTB solutions, and most often they do, developers can significantly expand and customize the functionality of an online store thanks to the basic ready-made sets to start with. What is more pleasant, with minimal cost spendings and manhour consume. Contact us if you have any questions or would like to discuss your technical issues. Let’s see how we can help you.

FAQ

How to secure the endpoints?

As API endpoints are entry points into organization intranets, the information they provide is often sensitive. The recommended actions to secure corporate data are a usage of the HTTPS protocol, API keys authorization, password hashing, limited rate of requests and API client permissions as short as possible, input validation. By protecting your endpoints, you save data integrity and prevent data breaches.

When do I need a custom REST solution?

In general, developing a custom RESTful solution is reasonable when you have a limited bandwidth and resources, have a need to aggregate data from third-party sources, and add extended business logic for your system. In the case of Hybris, it is sound when a standard OOTB capabilities are not enough for achieving strategic sales and marketing goals.

What are the benefits of a REST solution?

The primary advantage of RESTful solutions is the possibility to create applications of any complexity. Сonsider this: REST APIs streamline resource usage due to their ability to organize complicated applications. Their modular structure enables developers to be flexible when they design a REST API in Hybris or any other APIs. Its stateless client/server protocol allows it to free up your server from the superfluous cache. It uses an OAuth protocol request verification that is standard-based protection in REST APIs. Also, RESTful APIs support multiple types of calls and different data formats.