Mastering Producing Liferay Headless APIs

Setting Up REST Builder API Projects

Liferay's REST Builder simplifies custom API development by providing a structured, code-generation approach. This process begins with creating your initial API and IMPL modules and continues with defining API endpoints and data structures using intuitive YAML configuration files. These files specify the API's paths and parameters, laying the groundwork for the implementation of custom business logic.

This lesson explores how to set up API projects and populate them with scaffolding using REST Builder.

Since REST Builder relies on deploying custom OSGi modules, it is only available for Liferay PaaS and Self-Hosted deployments. It is not available for Liferay SaaS.

Creating API Project Foundations

To initiate an API project, first create the necessary Liferay workspace modules and configuring them for REST Builder. As a best practice, you should segment project code between separate api and impl OSGi modules. The api module should store your interface and exception definitions, while the impl module should include your implementation code. You must also install and apply REST BUILDER in the impl module as a plugin.

While it’s possible to setup projects manually, you can use the blade create -t api command to accelerate setup by generating the standard file and folder structure expected by REST Builder.

After initializing the modules, you must create two YAML configuration files within the impl module's root folder: rest-config.yaml and rest-openapi.yaml. The first file defines basic project-level configurations, such as class names and code organization. The second file defines the specific of your API endpoints, including request/response formats, paths, and parameters.

When complete, the rest-openapi.yaml should contain three primary sections:

  • components: Defines entity schemas. REST Builder creates corresponding Java beans for each entity defined in components.schemas. See the OpenAPI specification for supported schema data types.
  • info: Lists details such as the module’s name, license, and version.
  • paths: Contains the API’s specifications, including endpoints, data structures, and other essential information
YAML editors or the Swagger Editor can help prevent indentation issues when configuring these files.

Understanding Methods and Parameters

For RESTful APIs, paths are the URLs that identify specific resources or actions through its methods and parameters. These paths establish the entry points for interacting with your APIs, guiding users and applications to data and functions.

To define paths effectively, consider these key factors:

  • Plan HTTP Methods: Designate the intended HTTP methods for each API endpoint to interact with the necessary resources (GET, POST, PUT, DELETE, PATCH).
  • Set Path Parameters: Establish dynamic elements to serve as value-specific placeholders within URLs. For example, /users/{userId} uses userId to represent a particular user’s ID.
  • Define Request Bodies: Define the data structure sent in request bodies for POST and PUT methods, typically using JSON or XML format.
  • Define Responses: Specify the full range of responses, defining the content, format, and structure of the returned data for both success codes and error codes.

Carefully defining paths enables you to create clear and predictable interfaces for interacting with your APIs. This significantly improves API usability. See Producing and Implementing APIs with REST Builder for more information on defining schemas and paths.

Adding Business Logic

After building, configuring, and preparing your modules, you can execute the buildREST Gradle task to generate scaffolding code in your api and impl modules. This includes the Java classes for your implementation logic. While the specific implementation details depend on your team’s use case and business needs, adhering to best practices for data conversion, security, organization, and processing is vital for effective APIs.

Data Conversion Best Practices

From a REST consumer perspective, raw key values and lookup codes introduce unnecessary complexity. Ideal REST APIs convert these internal representations into meaningful values. When returning data, follow these guidelines:

  • Resolve Key Values: Replace numeric and UUID identifiers with readable names.
  • Expand Lookup Codes: Return specific, unambiguous status codes (e.g., Active instead of 1).
  • Format Timestamps: Convert timestamps to human-readable formats or ISO 8601 when appropriate.
  • Include Related Data: Embed all relevant details in the response to avoid additional consumer API calls to resolve references.

Security Best Practices

Security is paramount when exposing APIs. Proper error handling, authentication, and authorization prevent unintended data exposure. To implement proper security practices within your APIs, follow these guidelines:

  • Return 404 Instead of 403: Avoid revealing the existence of resources to unauthorized users by returning a generic "Not Found" instead of "Forbidden."
  • Validate All Inputs: Sanitize and validate input data to prevent injection attacks.
  • Restrict Data Exposure: Use Liferay's permission checks to limit user access to authorized data.
  • Implement Secure Authentication: Require OAuth 2.0 or other strong authentication mechanisms for access.
  • Limit Data Scope: Use Liferay's field selection features to reduce data exposure.

Organization Best Practices

REST Builder enables developers to group API endpoints in various ways. Since choosing the right approach impacts authorization and maintainability, consider these guidelines:

  • Consider OAuth 2.0 Scoping: Liferay OAuth 2.0 does not support fine-grained path-level authorization. If different endpoints require distinct authorization levels, separate them into different REST Builder projects.
  • Group Related Entities: Group frequently interacting entities, similar to how Liferay groups all CMS-related entities under one API.
  • Avoid Monolithic APIs: While grouping is beneficial, excessively large APIs can become difficult to maintain.

Processing Best Practices

Efficient data processing is key to API performance and user experience. To optimize processing within your REST Builder APIs, follow these guidelines:

  • Implementing Pagination and Filtering: Benefit from Liferay’s pagination and filtering to optimize response sizes.
  • Leveraging Asynchronous Processing: Consider async processing for long-running operations to improve performance. Liferay’s batch APIs illustrate this: starting a batch returns an ID to query status and completion, without blocking the calling consumer.
  • Configuring Logging and Auditing: Use Liferay’s built-in logging features and the Audit framework to track API usage and potential issues.

Conclusion

REST Builder streamlines API development by generating essential scaffolding for Liferay projects. This approach to extending Liferay APIs provides precise control over your API endpoints, requests, responses, and business logic. While coding inevitably involves overhead, adhering to best practices ensures your implementations are efficient, maintainable, and secure.

  • Creating API Project Foundations

  • Understanding Methods and Parameters

  • Adding Business Logic

  • Conclusion

Capabilities

Product

Education

Contact Us

Connect

Powered by Liferay
© 2024 Liferay Inc. All Rights Reserved • Privacy Policy