Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

Join us at AWS re:Invent 2024! Learn how to use MongoDB for AI use cases.
MongoDB Developer
Java
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Languageschevron-right
Javachevron-right

Create a Java REST API with Quarkus and Eclipse JNoSQL for MongoDB

Otavio Santana6 min read • Published Jan 30, 2024 • Updated Jan 30, 2024
QuarkusMongoDBJava
FULL APPLICATION
Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty

Introduction

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.

Prerequisites

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:
1docker run --rm -d --name mongodb-instance -p 27017:27017 mongo
Or you can use MongoDB Atlas and try the M0 free tier to deploy your cluster.

Create a Quarkus project

  • 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>

Database configuration

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:
1quarkus.mongodb.connection-string=mongodb://localhost:27017
2jnosql.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.

Create a developer entity

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.
1import jakarta.nosql.Column;
2import jakarta.nosql.Entity;
3import jakarta.nosql.Id;
4
5import java.time.LocalDate;
6import java.util.Objects;
7import java.util.UUID;
8
9@Entity
10public 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}

Create a REST API

Now, let’s create a RESTful API to manage developer records. Create a new class in src/main/java named DevelopersResource.
1import jakarta.inject.Inject;
2import jakarta.nosql.document.DocumentTemplate;
3import jakarta.ws.rs.*;
4import jakarta.ws.rs.core.MediaType;
5import jakarta.ws.rs.core.Response;
6
7import java.time.LocalDate;
8import java.util.List;
9
10@Path("developers")
11@Consumes({MediaType.APPLICATION_JSON})
12@Produces({MediaType.APPLICATION_JSON})
13public class DevelopersResource {
14
15 @Inject
16 DocumentTemplate template;
17
18 @GET
19 public List<Developer> listAll(@QueryParam("name") 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 @POST
34 public Developer add(NewDeveloperRequest request) {
35 var newDeveloper = Developer.newDeveloper(request.name(), request.birthday());
36 return template.insert(newDeveloper);
37 }
38
39 @Path("{id}")
40 @GET
41 public Developer get(@PathParam("id") 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 @Path("{id}")
50 @PUT
51 public Developer update(@PathParam("id") 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 @Path("{id}")
60 @DELETE
61 public void delete(@PathParam("id") String id) {
62 template.delete(Developer.class, id);
63 }
64}

Test the REST API

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.

Start the project:

1./mvnw compile quarkus:dev

Create a new developer with POST

You can use the POST request to create a new developer record. We'll use curl for this demonstration:
1curl -X POST "http://localhost:8080/developers" -H 'Content-Type: application/json' -d '{"name": "Max", "birthday": "
22022-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.

Read the developers with GET

To retrieve a list of developers, you can use the GET request:
1curl 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:
1curl http://localhost:8080/developers/a6905449-4523-48b6-bcd8-426128014582
This request will return the developer’s information associated with the provided id.

Update a developer with PUT

You can update a developer’s information using the PUT request:
1curl -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.

Delete a developer with DELETE

Finally, to delete a developer record, use the DELETE request:
1curl -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.

Using OpenAPI to test and explore your API

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:
1http://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:
  1. 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.
  2. Generates documentation: This is crucial for developers who need to understand how to use your API effectively.
  3. Allows for exploration: You can explore all the available endpoints, their input parameters, and expected responses, which helps you understand the API’s capabilities.
  4. 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.

Conclusion

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.
Ready to explore the benefits of MongoDB Atlas? Get started now by trying MongoDB Atlas.
Access the source code used in this tutorial.
Any questions? Come chat with us in the MongoDB Community Forum.

Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Article

Streamlining Java Application Development With MongoDB: A Comprehensive Guide to Using Testcontainers


Jul 22, 2024 | 7 min read
Tutorial

Serverless Development with AWS Lambda and MongoDB Atlas Using Java


Jul 20, 2023 | 6 min read
Tutorial

Implementing Bulk Writes using Spring Boot for MongoDB


Mar 22, 2023 | 3 min read
Quickstart

Java - Client Side Field Level Encryption


Mar 01, 2024 | 14 min read
Table of Contents