SparkJava
As noted earlier, we will be using a Java micro-framework called SparkJava to build the server that serves our RESTful HTTP API.
You need to add the following to the dependencies
clause of build.gradle
:
implementation 'com.sparkjava:spark-core:2.9.3'
implementation 'org.slf4j:slf4j-api:1.7.30'
implementation 'org.slf4j:slf4j-simple:1.7.30'
Then open the Gradle tool window and refresh the Gradle project.
Create a file ApiServer.java
with the following content:
import static spark.Spark.*;
public class ApiServer {
public static void main(String[] args) {
get("/", (req, res) -> "Welcome to CourseSearch API!");
}
}
Run the application. You will see some logging messages (about jetty server session) in IntelliJ "Run" window highlighted in red. These are not error messages; don't worry the app is running! Open your browser and visit http://localhost:4567/ to see the welcome message!
Notice the app does not stop until you stop from within the IntelliJ Run window.
Aside-1: Here, we are using your computer as a server. This server is not accessible over the Web; you can only access it on your local computer. That's where the localhost comes from. To learn more, checkout What is Localhost? Explained for Beginners.
Aside-2: The number 4567
is a port number. In computer networking, a port is a communication endpoint. Port numbers start from 0
. The numbers 0
to 1024
are reserved for privileged services (used by operating system, etc.). For local development, we usually use numbers $\ge$ 3000
. By default, Spark runs on port 4567
. If you want to use another port, consult Spark's documentation.
Aside-3: Did you notice the strange Java syntax with the ->
:
get("/", (req, res) -> "Welcome to CourseSearch API!");
This is an example of Java's Lambda expression. You need to know a bit about this. If lambda is entirely new to you, please read the Appendix: Java' Lambda.
Aside-4: Spark is unfortunately in a bit of namespace collision in the Java world. There is a database called Apache Spark which is very popular among Java programmers. It's unfortunate that they share the same name because if you get stuck and search for a solution online, the "spark java" keywords will return mixed results. The good news is that SparkJava is a tiny library which is also well documented. It's Docs and Tutorials provide you with (almost) all there is to know about it.
Aside-5: There are many alternatives to SparkJava, namely the Play framework, Javalin and Spring. The latter is the most advanced and complete Java framework there is for backend and server-side programming. The benefit of using SparkJava is in that it is simple and lightweight; it will get out of your way and let you focus on the core concepts.