RESTful WEB API For CRUD Operations In MongoDB

Introduction

In my previous article we did CRUD operations using MongoDB shell commands and as promised here I am with this article sharing how to create RESTful Web API for CRUD operations in MongoDB using .NET drivers. As you already know that MongoDB is the future of modern web applications so it is very important for .NET developers to get their hands on MongoDB drivers, so this article is my little effort in this direction. I hope you would like it and appreciate my work.

In this article we are to going to create Web APIs for manipulating and performing CRUD operations on student resource of our project.

Application Architecture

Application we are going to build is very simple. We are going to use MongoDB as our database and will create .NET Web APIs for data operation on MongoDB and there will be a test client to use our Web APIs.



Database Setup

Creating database is a piece of cake in MongoDB. You can refer my previous article for more details. We just need to write the following command to create database named studentsDB and collection named students:

use studentsDB
db.students.insert({ "_id" : 1, "RollNo" : "rol1", "Name" : "vikas", "Class" : "12th" })


Above command will create collection and insert a record on it.

For the sake of simplicity I am only creating one collection ‘students’ and will perform all our operations on this collection.

Creating Web API

Open Visual Studio to create a new project, I am using Visual Studio 2013 community edition. You can use Visual Studio 2013 or above version for the same.

Steps:

  1. Select Web, then ASP.NET MVC 4 Web Application.

  2. Give Project Name: Students.API.

    Web Application

  3. Select Web API and click OK.

    MVC Project

  4. That’s the power of Visual studio within few clicks we are ready with a dummy Web API project. By default controllers contain Home and Value Controller you can choose to delete them because we will create our own student controller to manage client calls. But before that there are other things we need to take care of. It’s just the beginning of fun ride of our journey.

Creating Data Model

Data Model is the project in our solution which contains Models of our application.

Steps:

  1. Add a new class library project to your solution and name it Students.DataModel.

    Add new project

    Class library

  2. Delete the default Class1.cs because we won’t need it.

  3. Create a folder named Models and add a class named Student.cs to it. This class is going to be our Model Class for Student entity of students collection.

    model

    Class

  4. Similarly create a folder named StudentsRepository and add StudentsRepository.cs class to it.

  5. In the same manner create one more folder named UnitOfWork and add StudentsUnitOfWork.cs to it.

  6. Before adding any code to Student class we need to add reference of official MongoDB drivers to our Data Model project so that we can communicate to MongoDB.

  7. Right click on the Data Model project, select Manage NuGet Packages and search for MongoDB.

    Data Model project

  8. Replace the code of Student Class with the following code:
    1. using MongoDB.Bson.Serialization.Attributes;  
    2. namespace Students.DataModel.Models  
    3. {  
    4.     publicclassStudent  
    5.     {  
    6.         [BsonElement("_id")]  
    7.         publicint StudentID  
    8.         {  
    9.             get;  
    10.             set;  
    11.         }  
    12.         publicstring RollNo  
    13.         {  
    14.             get;  
    15.             set;  
    16.         }  
    17.         publicstring Name  
    18.         {  
    19.             get;  
    20.             set;  
    21.         }  
    22.         publicstring Class  
    23.         {  
    24.             get;  
    25.             set;  
    26.         }  
    27.     }  
    28. }  
    Here, [BsonElement("_id")] attribute tells MongoDB that StudentID is going to be used as unique key i.e. _id in student collection. Rest is very simple no need to explain anything.

  9. Replace code of StudentRepository class with the following code:
    1. using MongoDB.Driver;  
    2. using MongoDB.Driver.Builders;  
    3. using System;  
    4. using System.Collections.Generic;  
    5. using System.Linq;  
    6. using System.Linq.Expressions;  
    7. namespace Students.DataModel.StudentRepository  
    8. {  
    9.     publicclassStudentRepository < T > where T: class  
    10.     {  
    11.         privateMongoDatabase _database;  
    12.         privatestring _tableName;  
    13.         privateMongoCollection < T > _collection;  
    14.         // constructor to initialise database and table/collection   
    15.         public StudentRepository(MongoDatabase db, string tblName)  
    16.         {  
    17.             _database = db;  
    18.             _tableName = tblName;  
    19.             _collection = _database.GetCollection < T > (tblName);  
    20.         }  
    21.         ///<summary>  
    22.             /// Generic Get method to get record on the basis of id  
    23.         ///</summary>  
    24.         ///<param name="i"></param>  
    25.         ///<returns></returns>  
    26.         ublic T Get(int i)  
    27.         {  
    28.             return _collection.FindOneById(i);  
    29.           
    30.             ///<summary>  
    31.             /// Get all records   
    32.             ///</summary>  
    33.             ///<returns></returns>  
    34.         ublicIQueryable < T > GetAll()  
    35.         {  
    36.             MongoCursor < T > cursor = _collection.FindAll();  
    37.                 return cursor.AsQueryable < T > ();  
    38.         }  
    39.         ///<summary>  
    40.         /// Generic add method to insert enities to collection   
    41.         ///</summary>  
    42.         ///<param name="entity"></param>  
    43.         publicvoid Add(T entity)  
    44.         {  
    45.             _collection.Insert(entity);  
    46.         }  
    47.         ///<summary>  
    48.         /// Generic delete method to delete record on the basis of id  
    49.         ///</summary>  
    50.         ///<param name="queryExpression"></param>  
    51.         ///<param name="id"></param>  
    52.         publicvoid Delete(Expression < Func < T, int >> queryExpression, int id)  
    53.         {  
    54.             var query = Query < T > .EQ(queryExpression, id);  
    55.             _collection.Remove(query);  
    56.         }  
    57.         ///<summary>  
    58.         /// Generic update method to delete record on the basis of id  
    59.         ///</summary>  
    60.         ///<param name="queryExpression"></param>  
    61.         ///<param name="id"></param>  
    62.         ///<param name="entity"></param>  
    63.         publicvoid Update(Expression < Func < T, int >> queryExpression, int id, T entity)  
    64.         {  
    65.             var query = Query < T > .EQ(queryExpression, id);  
    66.             _collection.Update(query, Update < T > .Replace(entity));  
    67.         }  
    68.     }  
    69. }  
    Above class is self-explanatory, it is a generic class to handle operation on various collection and different entities. We have created five generic methods to perform CRUD operation on any collection.

    First method, will grab one document from the collection initialized on constructor on the basis of integer id provided as the parameter.

    Second method, will grab all records from the collection as queryable. See how the FindAll() method returns MongoCursor which then will return entities as queryable.

    Third method, as the name suggests will add one entity received as parameter to specified collection.

    Fourth method, will delete record on the basis of id provided. Firstly, it will query the collection to search for the document with the id provided and then delete the same.

    Fifth method, will query the collection on the basis of id and then update (replace the document found with the new document provided). Id of the old document should match the new document provided.

  10. Now it’s time to replace StudentsUnitOfWork Class with the following code:
    1. using MongoDB.Driver;  
    2. using Students.DataModel.Models;  
    3. using Students.DataModel.StudentRepository;  
    4. using System.Configuration;  
    5. namespace Students.DataModel.UnitOfWork  
    6. {  
    7.     public class StudentsUnitOfWork  
    8.     {  
    9.         private MongoDatabase _database;  
    10.         protected StudentRepository < Student > _students;  
    11.         public StudentsUnitOfWork()  
    12.         {  
    13.             var connectionString = ConfigurationManager.AppSettings["MongoDBConectionString"];  
    14.             var client = newMongoClient(connectionString);  
    15.             var server = client.GetServer();  
    16.             var databaseName = ConfigurationManager.AppSettings["MongoDBDatabaseName"];  
    17.             _database = server.GetDatabase(databaseName);  
    18.         }  
    19.         public StudentRepository < Student > Students  
    20.         {  
    21.             get  
    22.             {  
    23.                 if (_students == null) _students = newStudentRepository < Student > (_database, "students");  
    24.                 return _students;  
    25.             }  
    26.         }  
    27.     }  
    28. }  
    Here we created StudentsUnitOfWork class which establishes connection with the MongoDB Server and the database we want to perform CRUD operations and it will simply return the StudentRepository as its property.

  11. Add new key value pair in the appSettings section to web config of Students.API project.
    1. <appSettings>  
    2.    <addkey="MongoDBConectionString"value="mongodb://localhost:27017" />  
    3. <addkey="MongoDBDatabaseName"value="studentsDB"/>  
    Note: You would need to resolve compilation error if any, by adding appropriate namespace and references to your project.

Creating Services

Now we need services to handle StudentsUnitOfWork and call appropriate method to communicate with the database and return the result to our controller.

Steps

  1. Add new class library project to your solution named Students.Services.

  2. Add an interface named IStudentService and a class StudentService that will inherit the interface added to the Students.Services.

  3. Replace interface code with the following code:
    1. using Students.DataModel.Models;  
    2. using System.Linq;  
    3. namespace Students.Services  
    4. {  
    5.     publicinterfaceIStudentService  
    6.     {  
    7.         void Insert(Student student);  
    8.         Student Get(int i);  
    9.         IQueryable < Student > GetAll();  
    10.         void Delete(int id);  
    11.         void Update(Student student);  
    12.     }  
    13. }  
  4. It’s time to add code to your StudentService class and as it will inherit the above interface we will have to provide the body for all the methods of interface. Let’s replace service class code with the following code:
    1. using Students.DataModel.Models;  
    2. using Students.DataModel.UnitOfWork;  
    3. using System.Linq;  
    4. namespace Students.Services  
    5. {  
    6.     public class StudentService: IStudentService  
    7.     {  
    8.         private readonly StudentsUnitOfWork _sUnitOfwork;  
    9.         public StudentService()  
    10.         {  
    11.             _sUnitOfwork = newStudentsUnitOfWork();  
    12.         }  
    13.         public Student Get(int i)  
    14.         {  
    15.             return _sUnitOfwork.Students.Get(i);  
    16.         }  
    17.         public IQueryable < Student > GetAll()  
    18.         {  
    19.             return _sUnitOfwork.Students.GetAll();  
    20.         }  
    21.         public void Delete(int id)  
    22.         {  
    23.             _sUnitOfwork.Students.Delete(s => s.StudentID, id);  
    24.         }  
    25.         public void Insert(Student student)  
    26.         {  
    27.             _sUnitOfwork.Students.Add(student);  
    28.         }  
    29.         public void Update(Student student)  
    30.         {  
    31.             _sUnitOfwork.Students.Update(s => s.StudentID, student.StudentID, student);  
    32.         }  
    33.     }  
    34. }  
    Let’s understand what we are trying to achieve with above code.

We have created a private object of StudentsUnitOfWork and initialized it in the constructor. In our first method Get, we are calling generic Get method of StudentsUnitOfWork property’s students (StudentsRepository) which will return Student object. Similarly, second method will return IQueryable objects of student class. Insert method is pretty simple and we are sending a new student object to be added to the StudentsUnitOfWork. Delete and Update method are similar in the sense that in both method lamba expression is used which will delete and update records respectively.

Updating Web API

Let me remind you that our Web API project comes with default controllers Home and Value Controller we need to create our own controller named StudentController for creating RESTful Web APIs. Here are the steps for the same:

  1. Right click on the Controllers folder in the Students.API project and new controller.

    Add controller

  2. Replace the default code of controller with the following code:
    1. using System.Linq;  
    2. using System.Web.Http;  
    3. using Students.DataModel.Models;  
    4. using Students.Services;  
    5. using System.Net.Http;  
    6. using System.Net;  
    7. namespace Students.API.Controllers  
    8. {  
    9.     public class StudentsController: ApiController  
    10.     {  
    11.         privatereadonlyIStudentService _studentService;  
    12.         public StudentsController()  
    13.             {  
    14.                 _studentService = newStudentService();  
    15.             }  
    16.             // GET api/student/id  
    17.         public HttpResponseMessage Get(int id)  
    18.         {  
    19.             var student = _studentService.Get(id);  
    20.             if (student != nullreturn Request.CreateResponse(HttpStatusCode.OK, student);  
    21.             return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Student not found for provided id.");  
    22.         }  
    23.         public HttpResponseMessage GetAll()  
    24.         {  
    25.             var students = _studentService.GetAll();  
    26.             if (students.Any()) return Request.CreateResponse(HttpStatusCode.OK, students);  
    27.             return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No students found.");  
    28.         }  
    29.         public void Post([FromBody] Student student)  
    30.         {  
    31.             _studentService.Insert(student);  
    32.         }  
    33.         public void Delete(int id)  
    34.         {  
    35.             _studentService.Delete(id);  
    36.         }  
    37.         public void Put([FromBody] Student student)  
    38.         {  
    39.             _studentService.Update(student);  
    40.         }  
    41.     }  
    42. }  
    We created five methods or we can say five APIs for handling CRUD operation. In the constructor we created object of the StudentService and in controllers’ method we will call service methods for handling client request.

First method will make call to service to fetch record on the basis of id provided on the URL.

Second method will make call to service to fetch all records.

Third method will post a new record to service to insert in the database.

Fourth method will make call to service to delete record from database.

Fifth method will make call to service to update record in the database.

All the above methods are HTTP VERBS and Web API will itself recognize request with the name of the VERB.

Now our APIs are ready to test, save the solution and build the solution. But how are we going to test our APIs? Not to worry we don’t need to create full-fledged client for this. Right click the Web API project and select Manage NuGet Packages and search for test client and install ‘A simple Test Client for ASP.NET Web API’.

install WEB API

It will install a test client to test our APIs. Yes we are ready to test now but before running your application make sure your MongoDB server is running.

Testing Web API

Steps to test Web API:
  1. Run your application.

  2. ASP.NET Web API home page will be loaded on the browser, click on the API link to see the list of APIs created by you.

    run page

  3. Click on the APIs link to test them. If you click on any of the link it will redirect you to the documentation page of the API clicked, there you will see a Test API button on the right corner of the screen. Click on the Test API button to test the API.

    Test API

    Responce for get

    responce

    Request information

Conclusion

We created simple RESTful Web API to interact with our resource. We used MongoDB in the back-end as our database. My example is very simple that’s why I tried to keep things simple, even I tried to keep our application structure very simple, I didn’t implemented security and error handling in the application. You can find the source on GitHub. Thanks for reading.

read learn code