Spark for Beginners: Create Restful API with Java and MongoDB

Français Français

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

Note : Refer to the section above to install the Spark environment, and to the official documentation for installing MongoDB.

Adding dependencies MongoDB

To use MongoDB with Apache Spark we need MongoDB Connector for Spark and specifically Spark Connector Java API.

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.

We’re gonna change the pom.xml by adding the following dependencies: mongo-java-driver, spark-core, BSON, morphia, gson. And we’ll specify the Java 1.8 version for the Maven compiler.

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.

Defining Api

We will create a new java Class 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 file and Run As Java Application .


Once our server running one passes the test phase with PostMan.

Github Repo