Skip to content

Commit a4c4c11

Browse files
committed
part one tutorial
1 parent a878405 commit a4c4c11

File tree

5 files changed

+234
-0
lines changed

5 files changed

+234
-0
lines changed

source/fundamentals/crud.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ CRUD Operations
1212

1313
Write </fundamentals/crud/write-operations>
1414
Read </fundamentals/crud/read-operations>
15+
Create a RESTful API with the .NET/C# Driver </fundamentals/crud/restful-api-tutorial>
1516

1617
- :ref:`csharp-crud-read-operations`
1718
- :ref:`csharp-crud-write-operations`
19+
- :ref:`csharp-crud-restful-api-tutorial`
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
.. _csharp-crud-restful-api-tutorial:
2+
3+
============================================
4+
Create a RESTful API with the .NET/C# Driver
5+
============================================
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: crud, code example, tutorial
13+
:description: Learn how to use the .NET/C# Driver to create a RESTful API for your application.
14+
15+
.. contents:: On this page
16+
:local:
17+
:backlinks: none
18+
:depth: 2
19+
:class: singlecol
20+
21+
Overview
22+
--------
23+
24+
In this tutorial, you will learn how to create a RESTful API with endpoints that
25+
perform basic create, read, update, and delete (CRUD) operations across MongoDB
26+
Atlas.
27+
28+
Prequisites
29+
-----------
30+
31+
To complete this tutorial, you must have the following:
32+
33+
- An `Atlas account
34+
<https://account.mongodb.com/account/register?tck=docs_atlas>`__ with a
35+
deployed and configured MongoDB Atlas cluster that is M0 or higher.
36+
37+
- .NET 6.0 or higher `installed <https://dotnet.microsoft.com/en-us/download>`__ on your machine.
38+
39+
To learn how to get started with MongoDB Atlas and how to load sample data, see the
40+
:atlas:`Get Started with Atlas Guide </getting-started>`.
41+
42+
This tutorial uses .NET Core 8.0, but you can use any version later than .NET 6.0.
43+
44+
Set Up Your Project
45+
-------------------
46+
47+
You can create a new .NET Core project using the web application template that
48+
Microsoft offers. To do this, run the following commands in your terminal:
49+
50+
.. code-block:: bash
51+
52+
dotnet new webapi -o MongoExample
53+
cd MongoExample
54+
55+
To add the {+driver-short+} to your project as a dependency, run the following command:
56+
57+
.. code-block:: bash
58+
dotnet add package MongoDB.Driver
59+
60+
The preceding commands create a new web application project for .NET core named
61+
``MongoExample`` and install the latest {+driver-short+}. The template project
62+
includes some boilerplate files. During this tutorial, you will add to these
63+
files and remove some of the boilerplate code to create a RESTful API.
64+
65+
Design a Document Model and Database Service
66+
--------------------------------------------
67+
68+
In this section, you will create and configure your MongoDB service and define
69+
the data model for your RESTful API.
70+
71+
.. procedure:: Create a MongoDB Service
72+
:style: connected
73+
74+
.. step:: Create the MongoDBSettings class
75+
76+
Your MongoDB service will be responisble for establishing a connection and
77+
directly working with documents within MongoDB. In your project, create a
78+
folder named ``Models``. In the ``Models`` folder, create a new file named
79+
``MongoDBSettings.cs``. In this file, add the following code:
80+
81+
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBSettingsSetup.cs
82+
:language: csharp
83+
:dedent:
84+
85+
The precedeing code defines a class named ``MongoDBSettings`` that
86+
contains information about your connection, the database name, and the
87+
collection name.
88+
89+
.. step:: Update the appsettings.json file
90+
91+
The data that will be stored in the class fields defined in the
92+
``MongoDBSettings`` class is found in the projects' ``appsettings.json``
93+
file. Open this file and add the following:
94+
95+
.. code-block:: json
96+
:copyable: true
97+
98+
{
99+
"Logging": {
100+
"LogLevel": {
101+
"Default": "Information",
102+
"Microsoft.AspNetCore": "Warning"
103+
}
104+
},
105+
"AllowedHosts": "*",
106+
"MongoDB": {
107+
"ConnectionURI": "ATLAS_URI_HERE",
108+
"DatabaseName": "sample_mflix",
109+
"CollectionName": "playlist"
110+
}
111+
}
112+
113+
Note the ``MongoDB`` field. This tutorial uses the ``sample_mflix``
114+
database and the ``playlist`` collection. Replace the ``ATLAS_URI_HERE``
115+
placeholder with your MongoDB Atlas connection string. For more
116+
information on how to find your connection string, see the
117+
:ref:`csharp-quickstart` guide.
118+
119+
.. step:: Create the service
120+
121+
In your project, create a folder named ``Services``. In the ``Services``
122+
folder, create a new file named ``MongoDBService.cs`` and add the
123+
following code:
124+
125+
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceSetup.cs
126+
:language: csharp
127+
:dedent:
128+
129+
The preceding code defines a class named ``MongoDBService`` that includes
130+
empty asynchronous functions. In this tutorial, you will add code to these
131+
functions as you create your endpoints. The passed settings from the
132+
``appsettings.json`` file are set to veriables.
133+
134+
.. step:: Connect the service to the application
135+
136+
Open the ``Program.cs`` file and add the following code to the top of the file:
137+
138+
.. code-block:: csharp
139+
:copyable: true
140+
141+
using MongoExample.Models;
142+
using MongoExample.Services;
143+
144+
var builder = WebApplication.CreateBuilder(args);
145+
146+
builder.Services.Configure<MongoDBSettings>(builder.Configuration.GetSection("MongoDB"));
147+
builder.Services.AddSingleton<MongoDBService>();
148+
149+
In the preceding code, the ``GetSection`` function pulls your settings
150+
from the ``MongoDB`` field in the ``appsettings.json`` file.
151+
152+
.. tip::
153+
154+
If your boilerplate code already has the ``builder`` variable, don't add it twice.
155+
156+
.. step:: Create the document model
157+
158+
Now that the service is set up, you can create a data model for your collection.
159+
160+
In the ``Models`` folder, create a new file named ``Playlist.cs`` and add
161+
the following code:
162+
163+
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistSetup.cs
164+
:language: csharp
165+
:dedent:
166+
167+
In the preceding code, the ``Id`` field is represented as an ``ObjectId``
168+
in BSON and the ``_id`` fild within MongoDB. When you work with this
169+
locally in your application, it is a string.
170+
171+
The ``movieIds`` field will be known as ``items``. When sending or
172+
receiving JSON, the field will also be known as ``items`` instead of
173+
``movieIds``.
174+
175+
If you plan to have your local class field match the document field
176+
directly, you don't need to define custom mappings. For example, the
177+
``username`` field in the preceding code has no custom mappings. It will
178+
be ``username`` in C#, in JSON, and in MongoDB.
179+
180+
You now have a MongoDB service and document model for your collection to work
181+
with for .NET Core.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using MongoExample.Models;
2+
using Microsoft.Extensions.Options;
3+
using MongoDB.Driver;
4+
using MongoDB.Bson;
5+
6+
namespace MongoExample.Services;
7+
8+
public class MongoDBService {
9+
10+
private readonly IMongoCollection<Playlist> _playlistCollection;
11+
12+
public MongoDBService(IOptions<MongoDBSettings> mongoDBSettings) {
13+
MongoClient client = new MongoClient(mongoDBSettings.Value.ConnectionURI);
14+
IMongoDatabase database = client.GetDatabase(mongoDBSettings.Value.DatabaseName);
15+
_playlistCollection = database.GetCollection<Playlist>(mongoDBSettings.Value.CollectionName);
16+
}
17+
18+
public async Task<List<Playlist>> GetAsync() { }
19+
public async Task CreateAsync(Playlist playlist) { }
20+
public async Task AddToPlaylistAsync(string id, string movieId) {}
21+
public async Task DeleteAsync(string id) { }
22+
23+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
namespace MongoExample.Models;
2+
3+
public class MongoDBSettings {
4+
5+
public string ConnectionURI { get; set; } = null!;
6+
public string DatabaseName { get; set; } = null!;
7+
public string CollectionName { get; set; } = null!;
8+
9+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
using MongoDB.Bson;
2+
using MongoDB.Bson.Serialization.Attributes;
3+
using System.Text.Json.Serialization;
4+
5+
namespace MongoExample.Models;
6+
7+
public class Playlist {
8+
9+
[BsonId]
10+
[BsonRepresentation(BsonType.ObjectId)]
11+
public string? Id { get; set; }
12+
13+
public string username { get; set; } = null!;
14+
15+
[BsonElement("items")]
16+
[JsonPropertyName("items")]
17+
public List<string> movieIds { get; set; } = null!;
18+
19+
}

0 commit comments

Comments
 (0)