Code reusability and reducing complexity are crucial for creating maintainable and efficient applications in software development. RAML (RESTful API Modeling Language) provides various advanced concepts to help achieve these goals. In this article, we will explore one such concept in RAML that allows us to handle multiple inputs and provide corresponding responses within a single method: Design Named Examples.
This approach eliminates the need for creating separate resources for each scenario, leading to cleaner and more concise code.
Let’s start by considering a common scenario where a single method receives multiple inputs and needs to return appropriate responses based on the input.
First, let’s create the input requests file under the examples folder. We’ll use NamedExample for demonstration purposes:
As shown below:
Next, we need to define the response file:
Now, to ensure that the input data conforms to a specific format, we will add libraries to our RAML specification. Let’s create a userLibrary file under the libraries folder to define the data types for each input:
With the library and request/response files in place, we can now define the RAML specification for our method. Let’s take a look at the RAML file:
In the above RAML specification, we defined a library which allows us to match the incoming request payload with the appropriate type and send the corresponding response.
We have defined the required Query Parameters; these will identify specific logic: enable, disable, delete.
The body section specifies that the request payload should be of type userType.enable, userType.disable, and userType.delete using the type property. We included examples of each type by referencing the requests.raml file.
In the responses section, we defined the expected response for a successful request with the status code 200. The response body is JSON, and we include examples in the responses.raml file.
So, how do we implement the inside code?
Once you import RAML inside the code, it will look like the below:
To execute the operation, you need to validate the Query Params and refer to the implemented logic.
By using the above RAML specification, we can use Design Named Examples to achieve code reusability and reduce complexity.