Skip to content

Commit 47d7f30

Browse files
committed
add crud section
1 parent bf452dd commit 47d7f30

File tree

3 files changed

+208
-2
lines changed

3 files changed

+208
-2
lines changed

source/fundamentals/crud/restful-api-tutorial.txt

Lines changed: 111 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,10 @@ different files within the project. In this section, you can learn how to define
189189
the endpoint within a controller and update the corresponding work within the
190190
service.
191191

192+
.. note::
193+
194+
In this example project, there is no data validation for the HTTP requests.
195+
192196
.. procedure:: Build endpoints to interact with MongoDB
193197
:style: connected
194198

@@ -206,6 +210,111 @@ service.
206210
access to your singleton service class. Then, there is a series of
207211
endpoints for this controller.
208212

209-
.. step:: Add data through the POST endpoing
213+
.. step:: Add data through the POST endpoint
214+
215+
Go to ``Services/MongoDBService.cs`` and update the ``CreateAsync``
216+
function to use the following code:
217+
218+
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceComplete.cs
219+
:language: csharp
220+
:start-after: start-create-async
221+
:end-before: end-create-async
222+
:dedent:
223+
224+
The preceding code sets the ``_playlistCollection`` in the constructor
225+
method of the service. This lets your application use the
226+
``InsertOneAsync`` method, which takes a passed ``Playlist`` variable and
227+
inserts it.
228+
229+
To complete the creation of the POST endpoint, go to the
230+
``Controllers/PlaylistController.cs`` file and update the ``Post`` method
231+
to use the following code:
232+
233+
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerComplete.cs
234+
:language: csharp
235+
:start-after: start-post
236+
:end-before: end-post
237+
:dedent:
238+
239+
When the ``POST`` endpoint executes, the application takes the
240+
``Playlist`` object from the ``request``, which .NET Core parses, and
241+
passes it to the ``CreateAsync`` function in the service. After the
242+
insert, the code returns some information about the interaction.
243+
244+
.. step:: Read data through the GET endpoint
245+
246+
Go to ``Services/MongoDBService.cs`` and update the ``GetAsync`` function to
247+
use the following code:
248+
249+
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceComplete.cs
250+
:language: csharp
251+
:start-after: start-get-async
252+
:end-before: end-get-async
253+
:dedent:
254+
255+
The ``Find`` operation in the preceding code returns all documents that
256+
exist in the collection.
257+
258+
To complete the creation of the GET endpoint, go to the
259+
``Controllers/PlaylistController.cs`` file and update the ``Get`` method to
260+
use the following code:
261+
262+
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerComplete.cs
263+
:language: csharp
264+
:start-after: start-get
265+
:end-before: end-get
266+
:dedent:
267+
268+
.. step:: Update data using the PUT endpoint
269+
270+
Go to ``Services/MongoDBService.cs`` and update the ``AddToPlaylistAsync``
271+
function to use the following code:
272+
273+
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceComplete.cs
274+
:language: csharp
275+
:start-after: start-add-to-playlist-async
276+
:end-before: end-add-to-playlist-async
277+
:dedent:
278+
279+
The preceding code sets up a match filter to determine which document or
280+
documents receive an update, in this case adding an item to your playlist.
281+
The code matches based on the ``Id`` field, which is unique. Then, the
282+
code defines the update critera, which is an ``AddtoSet`` operation that
283+
only adds an item to the array if it doesn't already exist in the array.
284+
285+
The ``UpdateOneAsync`` methods only updates on document even if the match
286+
filter returns more than one match.
287+
288+
To complete the creation of the PUT endpoint, go to the
289+
``Controllers/PlaylistController.cs`` file and update the
290+
``AddToPlaylist`` function to use the following code:
210291

211-
Navigate to ``Services/MongoDBService.cs`` and add the following code:
292+
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerComplete.cs
293+
:language: csharp
294+
:start-after: start-put
295+
:end-before: end-put
296+
:dedent:
297+
298+
.. step:: Delete data using the DELETE endpoint
299+
300+
Go to ``Services/MongoDBService.cs`` and update the ``DeleteAsync`` function to
301+
use the following code:
302+
303+
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceComplete.cs
304+
:language: csharp
305+
:start-after: start-delete-async
306+
:end-before: end-delete-async
307+
:dedent:
308+
309+
The preceding code deletes a single document based on the filter criteria,
310+
which matches the unique value of the ``Id`` field.
311+
312+
To complete the creation of the DELETE endpoint, go to the
313+
``Controllers/PlaylistController.cs`` file and update the
314+
``Delete`` function to use the following code:
315+
316+
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerComplete.cs
317+
:language: csharp
318+
:start-after: start-delete
319+
:end-before: end-delete
320+
:dedent:
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
// start-get-async
19+
public async Task<List<Playlist>> GetAsync() {
20+
return await _playlistCollection.Find(new BsonDocument()).ToListAsync();
21+
}
22+
// end-get-async
23+
24+
//start-create-async
25+
public async Task CreateAsync(Playlist playlist) {
26+
await _playlistCollection.InsertOneAsync(playlist);
27+
return;
28+
}
29+
//end-create-async
30+
31+
//start-add-to-playlist-async
32+
public async Task AddToPlaylistAsync(string id, string movieId) {
33+
FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("Id", id);
34+
UpdateDefinition<Playlist> update = Builders<Playlist>.Update.AddToSet<string>("movieIds", movieId);
35+
await _playlistCollection.UpdateOneAsync(filter, update);
36+
return;
37+
}
38+
//end-add-to-playlist-async
39+
40+
//start-delete-async
41+
public async Task DeleteAsync(string id) {
42+
FilterDefinition<Playlist> filter = Builders<Playlist>.Filter.Eq("Id", id);
43+
await _playlistCollection.DeleteOneAsync(filter);
44+
return;
45+
}
46+
//end-delete-async
47+
48+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
using System;
2+
using Microsoft.AspNetCore.Mvc;
3+
using MongoExample.Services;
4+
using MongoExample.Models;
5+
6+
namespace MongoExample.Controllers;
7+
8+
[Controller]
9+
[Route("api/[controller]")]
10+
public class PlaylistController: Controller {
11+
12+
private readonly MongoDBService _mongoDBService;
13+
14+
public PlaylistController(MongoDBService mongoDBService) {
15+
_mongoDBService = mongoDBService;
16+
}
17+
18+
//start-get
19+
[HttpGet]
20+
public async Task<List<Playlist>> Get() {
21+
return await _mongoDBService.GetAsync();
22+
}
23+
//end-get
24+
25+
//start-post
26+
[HttpPost]
27+
public async Task<IActionResult> Post([FromBody] Playlist playlist) {
28+
await _mongoDBService.CreateAsync(playlist);
29+
return CreatedAtAction(nameof(Get), new { id = playlist.Id }, playlist);
30+
}
31+
//end-post
32+
33+
//start-put
34+
[HttpPut("{id}")]
35+
public async Task<IActionResult> AddToPlaylist(string id, [FromBody] string movieId) {
36+
await _mongoDBService.AddToPlaylistAsync(id, movieId);
37+
return NoContent();
38+
}
39+
//end-put
40+
41+
//start-delete
42+
[HttpDelete("{id}")]
43+
public async Task<IActionResult> Delete(string id) {
44+
await _mongoDBService.DeleteAsync(id);
45+
return NoContent();
46+
}
47+
//end-delete
48+
49+
}

0 commit comments

Comments
 (0)