Create a Java REST API with Quarkus and Eclipse JNoSQL for MongoDB
Otavio Santana6 min read • Published Jan 30, 2024 • Updated Jan 30, 2024
FULL APPLICATION
Rate this tutorial
In this tutorial, you will learn how to create a RESTful API using Quarkus, a framework for building Java applications,
and integrate it with Eclipse JNoSQL to work with MongoDB. We will create a simple API to manage developer records.
Combining Quarkus with Eclipse JNoSQL allows you to work with NoSQL databases using a unified API, making switching
between different NoSQL database systems easier.
For this tutorial, you’ll need:
- Java 17.
- Maven.
- A MongoDB cluster.
- Docker (Option 1)
- MongoDB Atlas (Option 2)
You can use the following Docker command to start a standalone MongoDB instance:
1 docker run --rm -d --name mongodb-instance -p 27017:27017 mongo
- Configure your project by selecting the desired options, such as the group and artifact ID.
- Add the necessary dependencies to your project. For this tutorial, we will add:
- JNoSQL Document MongoDB [quarkus-jnosql-document-mongodb]
- RESTEasy Reactive [quarkus-resteasy-reactive]
- RESTEasy Reactive Jackson [quarkus-resteasy-reactive-jackson]
- OpenAPI [quarkus-smallrye-openapi]
- Generate the project, download the ZIP file, and extract it to your preferred location. Remember that the file structure may vary with different Quarkus versions, but this should be fine for the tutorial. The core focus will be modifying the
pom.xml
file and source code, which remains relatively consistent across versions. Any minor structural differences should be good for your progress, and you can refer to version-specific documentation if needed for a seamless learning experience.
At this point, your
pom.xml
file should look like this:1 <dependencies> 2 <dependency> 3 <groupId>io.quarkus</groupId> 4 <artifactId>quarkus-resteasy-reactive-jackson</artifactId> 5 </dependency> 6 <dependency> 7 <groupId>io.quarkiverse.jnosql</groupId> 8 <artifactId>quarkus-jnosql-document-mongodb</artifactId> 9 <version>1.0.5</version> 10 </dependency> 11 <dependency> 12 <groupId>io.quarkus</groupId> 13 <artifactId>quarkus-smallrye-openapi</artifactId> 14 </dependency> 15 <dependency> 16 <groupId>io.quarkus</groupId> 17 <artifactId>quarkus-resteasy-reactive</artifactId> 18 </dependency> 19 <dependency> 20 <groupId>io.quarkus</groupId> 21 <artifactId>quarkus-arc</artifactId> 22 </dependency> 23 <dependency> 24 <groupId>io.quarkus</groupId> 25 <artifactId>quarkus-junit5</artifactId> 26 <scope>test</scope> 27 </dependency> 28 <dependency> 29 <groupId>io.rest-assured</groupId> 30 <artifactId>rest-assured</artifactId> 31 <scope>test</scope> 32 </dependency> 33 </dependencies>
By default, quarkus-jnosql-document-mongodb
is in version
1.0.5
, but the latest release is 3.2.2.1
. You should update your pom.xml
to use the latest version:1 <dependency> 2 <groupId>io.quarkiverse.jnosql</groupId> 3 <artifactId>quarkus-jnosql-document-mongodb</artifactId> 4 <version>3.2.2.1</version> 5 </dependency>
Before you dive into the implementation, it’s essential to configure your MongoDB database properly. In MongoDB, you
must often set up credentials and specific configurations to connect to your database instance. Eclipse JNoSQL provides
a flexible configuration mechanism that allows you to manage these settings efficiently.
You can find detailed configurations and setups for various databases, including MongoDB, in the Eclipse JNoSQL GitHub
repository.
To run your application locally, you can configure the database name and properties in your application’s
application.properties
file. Open this file and add the following line to set the database name:1 quarkus.mongodb.connection-string=mongodb://localhost:27017 2 jnosql.document.database=school
This configuration will enable your application to:
- Use the “school” database.
- Connect to the MongoDB cluster available at the provided connection string.
In production, make sure to enable access control and enforce authentication. See the security checklist for more
details.
It’s worth mentioning that Eclipse JNoSQL leverages Eclipse MicroProfile Configuration, which is designed to facilitate
the implementation of twelve-factor applications, especially in configuration management. It means you can override
properties through environment variables, allowing you to switch between different configurations for development,
testing, and production without modifying your code. This flexibility is a valuable aspect of building robust and easily
deployable applications.
Now that your database is configured, you can proceed with the tutorial and create your RESTful API with Quarkus and
Eclipse JNoSQL for MongoDB.
In this step, we will create a simple
Developer
entity using Java records. Create a new record in the src/main/java
directory named Developer
.1 import jakarta.nosql.Column; 2 import jakarta.nosql.Entity; 3 import jakarta.nosql.Id; 4 5 import java.time.LocalDate; 6 import java.util.Objects; 7 import java.util.UUID; 8 9 10 public record Developer( 11 @Id String id, 12 @Column String name, 13 @Column LocalDate birthday 14 ) { 15 16 public static Developer newDeveloper(String name, LocalDate birthday) { 17 Objects.requireNonNull(name, "name is required"); 18 Objects.requireNonNull(birthday, "birthday is required"); 19 return new Developer( 20 UUID.randomUUID().toString(), 21 name, 22 birthday); 23 } 24 25 public Developer update(String name, LocalDate birthday) { 26 Objects.requireNonNull(name, "name is required"); 27 Objects.requireNonNull(birthday, "birthday is required"); 28 return new Developer( 29 this.id(), 30 name, 31 birthday); 32 } 33 }
Now, let’s create a RESTful API to manage developer records. Create a new class in
src/main/java
named DevelopersResource
.1 import jakarta.inject.Inject; 2 import jakarta.nosql.document.DocumentTemplate; 3 import jakarta.ws.rs.*; 4 import jakarta.ws.rs.core.MediaType; 5 import jakarta.ws.rs.core.Response; 6 7 import java.time.LocalDate; 8 import java.util.List; 9 10 11 12 13 public class DevelopersResource { 14 15 16 DocumentTemplate template; 17 18 19 public List<Developer> listAll( String name) { 20 if (name == null) { 21 return template.select(Developer.class).result(); 22 } 23 24 return template.select(Developer.class) 25 .where("name") 26 .like(name) 27 .result(); 28 } 29 30 public record NewDeveloperRequest(String name, LocalDate birthday) { 31 } 32 33 34 public Developer add(NewDeveloperRequest request) { 35 var newDeveloper = Developer.newDeveloper(request.name(), request.birthday()); 36 return template.insert(newDeveloper); 37 } 38 39 40 41 public Developer get( String id) { 42 return template.find(Developer.class, id) 43 .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND)); 44 } 45 46 public record UpdateDeveloperRequest(String name, LocalDate birthday) { 47 } 48 49 50 51 public Developer update( String id, UpdateDeveloperRequest request) { 52 var developer = template.find(Developer.class, id) 53 .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND)); 54 var updatedDeveloper = developer.update(request.name(), request.birthday()); 55 return template.update(updatedDeveloper); 56 57 } 58 59 60 61 public void delete( String id) { 62 template.delete(Developer.class, id); 63 } 64 }
Now that we've created our RESTful API for managing developer records, it's time to put it to the test. We'll
demonstrate how to interact with the API using various HTTP requests and command-line tools.
1 ./mvnw compile quarkus:dev
You can use the
POST
request to create a new developer record. We'll use curl
for this demonstration:1 curl -X POST "http://localhost:8080/developers" -H 'Content-Type: application/json' -d '{"name": "Max", "birthday": " 2 2022-05-01"}'
This
POST
request sends a JSON payload with the developer’s name and birthday to the API endpoint. You’ll receive a
response with the details of the newly created developer.To retrieve a list of developers, you can use the
GET
request:1 curl http://localhost:8080/developers
This
GET
request returns a list of all developers stored in the database.
To fetch details of a specific developer, provide their unique id in the URL:1 curl http://localhost:8080/developers/a6905449-4523-48b6-bcd8-426128014582
This request will return the developer’s information associated with the provided id.
You can update a developer’s information using the
PUT
request:1 curl -X PUT "http://localhost:8080/developers/a6905449-4523-48b6-bcd8-426128014582" -H 'Content-Type: application/json' 2 -d '{"name": "Owen", "birthday": "2022-05-01"}'
In this example, we update the developer with the given id by providing a new name and birthday in the JSON payload.
Finally, to delete a developer record, use the DELETE request:
1 curl -X DELETE "http://localhost:8080/developers/a6905449-4523-48b6-bcd8-426128014582"
This request removes the developer entry associated with the provided
id
from the database.Following these simple steps, you can interact with your RESTful API to manage developer records effectively. These HTTP
requests allow you to create, read, update, and delete developer entries, providing full control and functionality for
your API.
Explore and adapt these commands to suit your specific use cases and requirements.
OpenAPI is a powerful tool that allows you to test and explore your API visually. You can access the OpenAPI
documentation for your Quarkus project at the following URL:
1 http://localhost:8080/q/swagger-ui/
OpenAPI provides a user-friendly interface that displays all the available endpoints and their descriptions and allows
you to make API requests directly from the browser. It’s an essential tool for API development because it:
- Facilitates API testing: You can send requests and receive responses directly from the OpenAPI interface, making it easy to verify the functionality of your API.
- Generates documentation: This is crucial for developers who need to understand how to use your API effectively.
- Allows for exploration: You can explore all the available endpoints, their input parameters, and expected responses, which helps you understand the API’s capabilities.
- Assists in debugging: It shows request and response details, making identifying and resolving issues easier.
In conclusion, using OpenAPI alongside your RESTful API simplifies the testing and exploration process, improves
documentation, and enhances the overall developer experience when working with your API. It’s an essential tool in
modern API development practices.
In this tutorial, you’ve gained valuable insights into building a REST API using Quarkus and seamlessly integrating it
with Eclipse JNoSQL for MongoDB. You now can efficiently manage developer records through a unified API, streamlining
your NoSQL database operations. However, to take your MongoDB experience even further and leverage the full power of
MongoDB Atlas, consider migrating your application to MongoDB Atlas.
MongoDB Atlas offers a powerful document model, enabling you to store data as JSON-like objects that closely resemble
your application code. With MongoDB Atlas, you can harness your preferred tools and programming languages. Whether you
manage your clusters through the MongoDB CLI for Atlas or embrace infrastructure-as-code (IaC) tools like Terraform or
Cloudformation, MongoDB Atlas provides a seamless and scalable solution for your database needs.
Access the source code used in this tutorial.