What is a REST API?
[AI Generated image of a REST API architecture]
We are building a distributed system, that has a backend and a frontend. The backend is a REST API, that the frontend will consume. The backend is built using Javalin, which is a lightweight web framework for Java and Kotlin. The frontend is built using React, which is a popular JavaScript library for building user interfaces. JSON is the data format that we will use to communicate between the frontend and the backend.
Compared to 2nd semester where we built a web application using server side rendering, we are now building a distributed system, where the frontend and the backend are separate applications. The backend is a REST API, that the frontend will consume.
A REST API is a web service that follows the principles of Representational State Transfer (REST). Instead of returning HTML pages, a REST API returns data in a format that can be easily consumed by other applications, such as JSON or XML.
The output of a REST API is typically data in a structured format, such as JSON like this:
{
"id": 1,
"title": "The Road Not Taken",
"author": "Robert Frost",
"content": "Two roads diverged in a yellow wood, And sorry I could not travel both..."
}
or
[
{
"id": 1,
"title": "The Road Not Taken",
"author": "Robert Frost",
"content": "Two roads diverged in a yellow wood, And sorry I could not travel both..."
},
{
"id": 2,
"title": "Stopping by Woods on a Snowy Evening",
"author": "Robert Frost",
"content": "Whose woods these are I think I know. His house is in the village though..."
}
]
With Javalin, we can easily create a REST API by defining endpoints that handle HTTP requests and return JSON responses. For example, we can create an endpoint that returns a list of poems like this:
app.get("/poems", ctx -> {
List<Poem> poems = poemController.getAllPoems();
ctx.json(poems); // This will return the list of poems as a JSON response (converted automatically by Javalin using Jackson under the hood)
});