Using Rails as an API means a user is provided a web application and also an accessible API. An Application Programming Interface (API) is a computing interface that defines interactions between multiple software intermediaries.
With the recent shift of developers moving towards client-side frameworks, there has been great development in the use of Rails to built back-end frameworks. Many developers are using their web application as API clients, which are then delivered with HTML and JavaScript, and can easily use the JSON methods of API.
In Rails, it is suggested that you expose your models and APIs through
The first thing to do when building a REST API is to identify which resources will be exposed by your module.
Note: resources are not necessarily domain entities, although they may appear to be so.
Let’s take an example of an instance that manages a classroom. Some examples of resources that can be exposed are:
There are four main HTTP methods that can be used for this application:
Add a new student through a POST
on /students
. Take a look at code below:
{
"name": "Alex Williams",
"student_ID": 22100110
}
This will result in the following JSON response:
{
"id": 57498072,
"name": "Alex Williams",
"student_ID": 22100110
}
Similarly, calling a GET
on /books/57498072
will result in the response, “JSON which will check the JSON id
column and compare it with the column id: 57498072
,” and yield the following result:
{
"id": 57498072,
"name": "Alex Williams",
"student_ID": 22100110
}
It is easier to create and parse data in this JSON format. For this purpose, we use the Bennu infrastructure. This Bennu infrastructure is useful as it provides a library used to conduct externalization. The following resources are used:
JsonViewer - Given a particular domain object, it creates a JsonElement that represents that domain object.
JsonCreator - Given a particular JSON object, it creates a new domain object.
JsonUpdater - Given a particular JSON object, it updates an existing domain object.
JsonAdapter - Implements the three interfaces above.
After identifying required endpoints, a user should implement it on the server side. This is done by making use of domain information and producing JSON responses to endpoints. Moreover, the Bennu infrastructure provides the bennu-json
library to further assist with our process.
In order to expose a particular endpoint, we use the BennuRestResource
class provided by the Bennu infrastructure.
Take a look at the example below where a new ClassRoom
class ic created using the BennuRestResource
class. This will create a new folder of classroom
, as defined in @path
, which gives the user access control to the #admin
and returns a created jsonElement
.
public class ClassRoom extends BennuRestResource {
@POST
@Path("/classroom")
@Produces(MediaType.APPLICATION_JSON)
public String createOrder(JsonElement jsonElement) {
accessControl("#admin");
return create(jsonElement);
}
...
}