Welcome, we will discover in this tutorial how to create RestFull API with MongoDB as NOSQL database using the Java language. at the end of this tutorial you will be able to create your own API interacting with NOSQL database (mongodb). The code will be done in Java you will find it the Github repo links at the end of the tutorial.
Demo on Youtube
- You will need the Java Development Kit (JDK) for Spark works locally.
- you will nedd also Maven to manage the application lifecycle.
- You will of course need to install Apache Spark.
- You will need to install MongoDB.
- Bases knowledge of operation of Rest full services
Adding dependencies MongoDB
First we’ll create a new Maven project with Eclipse, for this example I will create a small product management application. I choose
tn.esprit as Group Id and shop as Artifact Id. See above.
Then performs maven install to download and install dependencies once you get a BUILD SUCCESS you can move to the next step.
Creating the Product entity
we will quickly create a Product entity that has the following properties: Id, Name, Price.
Creating ProductService and database connection
Once our entity created and ready for jobs, we go to the creation of our service (business layer). it is in ProductService(java class) that will connect to the mongodb database, and we’re going to create two method addProduct and getAllProduct . above the source commented.
We will create a new java Class Api.java that will contain the routes of our Api using Apache Spark.
Execution & test PostMan
To run our application, we must first generate it with Manven by running maven install. Then we will create a new connection to our mongodb database by running the following command:
In the end, right click on the Api.java file and Run As Java Application .
Once our server running one passes the test phase with PostMan.