Recently, I attended a talk by some great colleagues of mine about FastAPI, a Python web framework for building REST APIs. It is really simple and easy to use, and you can set up an API in seconds.
In addition to a requirements.txt file, you need just a few lines of code to create a full-fledged REST API with a single GET endpoint:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Now, this is great. I love Python for its simplicity and ease of use. But as a long-time professional Java developer, the challenge for me was to see whether it is possible to do something similar in Java.
I briefly considered Spring Boot, but quickly realized that I would need an Application
class in addition to a RestController
class. Plus, for something simple like this, Spring Boot takes way too long to start up.
Cue Spark (not to be confused with Apache Spark), a micro framework for Java web applications. Spark is actually very similar to FastAPI. It enables creating a REST API in just a few lines of code, but also has a lot of advanced options.
Starting with an empty Maven project, creating a single GET endpoint with Spark consists of just two simple steps. First, add Spark as a dependency to your pom.xml. Then, create a main class with the following contents:
import static spark.Spark.*;
public class MinimalApi {
public static void main(String[] args) {
get("/hello", (request, response) -> "Hello world!");
}
}
Check out the full repository over on my GitHub.
Especially if you discount the boilerplate class definition and main method declaration, this requires even fewer lines of code than FastAPI! One thing that Spark lacks versus FastAPI, though, is the out-of-the-box Swagger/OpenAPI integration.
Python is getting more and more mature with its frameworks and more suitable for running REST APIs in production environments. Some are even saying that a few years down the line, we will all be developing in Python. I’m not going to burn my fingers on such a prediction one way or another. However, this exercise did support my belief that even at well over 25 years old, Java still has a lot to offer to contemporary software development.
0 Comments