Build a Simple RESTful CRUD API in .NET 5 (ASP.Net Core) with MongoDB in 2021

Dominique Kleeven
5 min readFeb 17, 2021

A quick tutorial about creating a CRUD RESTFul API in ASP.Net Core (.NET 5) using MongoDB.

Prerequisites

  • IDE of choice (I’ll be using Jetbrains Rider).
  • Docker Desktop (for deploying MongoDB).
  • Basic knowledge of RESTful API’s, ASPNetCore, and MongoDB
  • AspDotNetCore 3.1 or .NET 5

The entire solution can be found on my Github.

Setting up MongoDB

First, we’ll be deploying a local instance of MongoDB for development purposes. I’ll be using Docker Desktop for this.

In your terminal/command prompt type in the following command:

docker run --name mongodb -v /my/own/datadir:/data/db -p 27017:27017 --restart unless-stopped -d mongo

replace /my/own/datadir with a path on your computer. For example: /mongodb/data

That’s it your MongoDB instance should now be running. You can check by typing docker container list in your terminal/command prompt

docker container list results

Create a new project.

Create a new project using the ASP.NET Core Web API template.

Creating a new project

After creating your project your directory should look like this:

Directory structure after creating the project.

You can ignore the WeatherForecast classes or just remove them, your choice.

Install the required Nuget Packages

Install the following Nuget packages

  1. MongoDB.Driver
  2. MongoDB.Bson

Your Nuget package list should look like this:

Installed Packages

Configuring the MongoDB Connection

Change your appsettings.json (located in the root directory of your project) to the following info:

appsettings.json

Next, create a class called DatabaseSettings.

Next, adding the Database Configuration to our Startup class.

Inside the ConfigureServices method add the following lines of code:

Now we’re ready to create our domain classes.

Setting up our domain classes.

Our RESTFul API will provide the functionality of a Todo application. So we’ll be creating a TodoList and TodoItem class inside a new directory called Domain.

TodoList.cs

TodoList class

TodoItem.cs

Setting up our Mongo Database Services

Next, create a new directory called Services. We’ll be creating a single class called TodoListService which will contain our database access logic.

TodoListService.cs

Explanation

In the constructor, we’ve created a new MongoClient which connects to our Database. From our database, we can specify our collection, in this case: todolists.

Besides our constructor, we’ve added the basic CRUD functionality that we need. MongoDB.Driver enables us to easily fetch data and insert data from our collection.

Dependency Injection

Next, we’ll have to define our Service in the Startup.cs file. In the ConfigureServices method add the following line of code:

services.AddScoped<TodoListService>();

This will use dependency injection to inject our service so we can access it in our API Controller.

Setting up our RESTful API Controller

We’ve arrived at the last part, which is creating the API Controller itself.

In the Controllers, directory add a new class called TodoListsController.

TodoListsController.cs

TodoListController.cs

Explaination

The constructor accepts our TodoListService which is automatically dependency injected by ASP.Net Core since we’ve defined it in our Startup.cs.

Besides the constructor, we’ve added a method for each operation (C — Create, R — Read, U — Update, and D — Delete).

Each method defines its HTTP Method (HttpGet, HttpPut, HttpPost, and HttpDelete) and calls the TodoList service and calls the corresponding method.

Starting & Trying out our API

Start your project and if the tutorial was followed correctly you should see a Swagger Page.

Swagger Documentation

Creating a TodoList

Click on the POST method (/api/TodoLists) and click on Try it out.

Enter the following information into the text box.

Feel free to change some of the values if you want to.

Click on Execute.

It should return the response code 200 and the newly created TodoList.

Response Body

Retrieving All TodoLists

Click on the GET method (/api/TodoLists) and click on Try it out.

Click on Execute.

It should now show your recently created Todolist it the Response Body.

Response Body

Updating our TodoList
First, fully copy a TodoList.

Click on the PUT method (/api/TodoLists) and click on Try it out.

Paste your copied TodoList into the text box and change it to your liking. In my case it looks like this:

Click on Execute.

It should return the 200 response code and your updated TodoList in the response body.

My Updated TodoList Response

Retrieving a specific TodoList

First, copy the Id from your TodoList.

Click on the GET method (/api/TodoLists/{Id}) and click on Try it out.

In the ID input field paste your copied ID.

Id Input Field

Click on Execute.

It should return the 200 response code and your specified TodoList.

Request Response

Deleting a specific TodoList

First, copy the Id from your TodoList.

Click on the DELETE method (api/TodoLists/{id}) and click on Try it out.

In the Id input field paste your copied ID.

Id Input Field

Click on Execute.

Your TodoList is now deleted.

That's it, folks. You’ve now successfully set up a to-do list CRUD RESTful API using MongoDB as a Database.

You can find the entire project on my Github.

https://github.com/dominiquekleeven/medium-crud-api-mongodb

Thanks for reading and I hope you’ve learned something.

--

--