The Application Programming Interface (API) is a software that defines communications between multiple software applications. An API sets the rules by which these applications talk to each other.
The Representational State Transfer (REST) is an architectural style for designing distributed hypermedia systems. A
There are several ways to make a REST API in Java. We will see how to make a
curl
set up in the terminal for testing.To demo each REST API, we will implement a basic GET
endpoint and test it on the terminal using curl
.
Why re-invent the wheel when there are good frameworks out there with lots of additional features? Well, those frameworks come with their
If we are building a minor service or a console application, we should consider making it without a framework.
To start, open your IDE and create a Java project.
In the src
directory, let’s create a class called API
and write the main
method.
HttpServer
to talk to port 8080
, as shown below:import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;public class API {public static void main(String[] args) throws IOException {HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);server.createContext("/api/greeting", (exchange -> {if ("GET".equals(exchange.getRequestMethod())) {String responseText = "Hello World! from our framework-less REST API\n";exchange.sendResponseHeaders(200, responseText.getBytes().length);OutputStream output = exchange.getResponseBody();output.write(responseText.getBytes());output.flush();} else {exchange.sendResponseHeaders(405, -1);// 405 Method Not Allowed}exchange.close();}));server.setExecutor(null); // creates a default executorserver.start();}}
Line 11 creates a serverContext
that adds the /api/greeting
context path.
The lambda expression encapsulates the HTTP request received and a response to be generated in one exchange.
If the HTTP request method is GET,
it will return the response text “Hello World! from our framework-less REST API”.
If the GET
request is valid, the response status will be set to 200
Run the project, our API is up and running on port 8080
.
To test our framework-less REST API, run this on the following terminal:
curl localhost:8080/api/greeting
The command will return this string:
Hello World! from our framework-less REST API
Spring Boot is built on top of the popular Spring framework to reduce overall development time and increase efficiency. Spring Boot has minimal to none configurations and a default setup for unit and integration tests. Its default configuration approach opinionates Spring Boot.
Most Java developers use Spring Boot to develop REST APIs and microservices. The spring/Springboot community is huge, and top companies use it.
But, enough about what Spring Boot is; let’s build a REST API with Spring Boot.
We can use the Spring Initializr to set up our project by clicking this link, which will fill in the details of the configuration for us.
Click “Generate” and then import the project into an IDE.
After importing the project in directory src/main/java/com/demo/Spring/Boot/Rest/API
, create a RestController class APIRestController
and annotate it with @RestController
, as shown below:
package com.example.demo;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/api")public class APIRestController {@Getmapping("/greeting")public String greeting(){return "Hello World! from my Spring Boot REST API";}}
The above piece of code is shorter than the framework-less REST API because Spring Boot has done many abstractions for us:
The @RestController
annotation tells Spring Boot to treat the APIRestController
class as a RESTful controller.
For the @RequestMapping("/api")
, just like how we saw our framework-less REST API create an HTTP server context path, this annotation adds the request path /api
. Any GET
, POST
, PUT
, or DELETE
endpoint builds on top of /api
. We will see that our GET request will map to /api/greeting
when we test our API.
The @GetMapping("/greeting")
annotation states that the below method is for a GET
request. There is @PostMapping()
, @DeletMapping()
, etc. for their specific HTTP methods, but that’s out of the scope of this shot.
The greeting()
method returns a Hello World! string from my Spring Boot REST API
– we will see this when we test our API.
We can run the project in our IDE or on the terminal using this command:
$ mvn spring-boot:run
To test our Spring Boot REST API, run this on the terminal:
curl localhost:8080/api/greeting
The command will return this string:
Hello World! from our Spring Boot REST API
Spark is an unopinionated lightweight pure Java micro web framework. It requires minimal effort, and we can get started quickly.
Spark was built with productivity and rapid development in mind. It’s excellent for building microservices. In Spark documentation, a header states, Microservices, microservices everywhere!.
NodeJS or TypeScript developers looking to try out Java for API development will meet a familiar ExpressJS-looking syntax in Spark.
Now, let’s build a Spark REST API.
First, let’s create a new Maven project using any IDE.
In our POM.xml file, we would add the Spark dependency:
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>2.9.3</version>
</dependency>
If you are not familiar with Maven, click here for more detailed instructions on how to use IntelliJ IDEA and Eclipse.
We can now create a class named API
.
Then, we import Spark to the class:
import static spark.Spark.*;
In this class, we will create the main method for all our HTTP methods.
get("/greeting", (req, res) -> "Hello World! from my Spark REST API");
import static spark.Spark.*;public class API {public static void main(String[] args) {get("/greeting", (req, res) -> "Hello World! from our Spark REST API");}}
We can see that Spark is lightweight and development is as rapid as it gets.
Run the project, and our API will be up and running on spark default port 4567
.
To test our Spring Boot REST API, run this on the terminal:
$ curl http://localhost:4567/greeting
The command will return this string:
Hello World! from our Spark REST API
We’ve seen three ways to make a REST API in Java and tested each API via the terminal in this shot.
There are more ways we can make a REST API in Java using:
Thank you for reading! If you found this shot useful, react and share. Cheers! You can follow me on Twitter.