|
| 1 | +.. _csharp-crud-restful-api-tutorial: |
| 2 | + |
| 3 | +============================================================ |
| 4 | +Tutorial: Create a RESTful API by Using the {+driver-short+} |
| 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: 1 |
| 19 | + :class: singlecol |
| 20 | + |
| 21 | +Overview |
| 22 | +-------- |
| 23 | + |
| 24 | +In this tutorial, you can learn how to create a RESTful API with endpoints that |
| 25 | +perform basic create, read, update, and delete (CRUD) operations across |
| 26 | +collections in a MongoDB Atlas cluster. |
| 27 | + |
| 28 | +Prerequisites |
| 29 | +------------- |
| 30 | + |
| 31 | +Before you start this tutorial, perform the following actions: |
| 32 | + |
| 33 | +- Set up a MongoDB Atlas account and deploy and configure a cluster that is M0 |
| 34 | + or higher. To view instructions, see the :atlas:`Get Started with Atlas </getting-started>` guide. |
| 35 | + |
| 36 | +- Install .NET 6.0 or later on your machine. To install .NET, visit the |
| 37 | + `Microsoft .NET download page <https://dotnet.microsoft.com/en-us/download>`__. |
| 38 | + |
| 39 | +.. note:: Language Compatibility |
| 40 | + |
| 41 | + This tutorial uses .NET Core 8.0, but you can use any version later than .NET 6.0. |
| 42 | + |
| 43 | +Set Up Your Project |
| 44 | +------------------- |
| 45 | + |
| 46 | +Run the following commands in your terminal to create a new .NET Core project |
| 47 | +that uses a web application template: |
| 48 | + |
| 49 | +.. code-block:: bash |
| 50 | + |
| 51 | + dotnet new webapi -o MongoExample |
| 52 | + cd MongoExample |
| 53 | + |
| 54 | +To add the {+driver-short+} to your project as a dependency, run the following command: |
| 55 | + |
| 56 | +.. code-block:: bash |
| 57 | + |
| 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 that you modify to implement a RESTful API. |
| 63 | + |
| 64 | +Design a Document Model and Database Service |
| 65 | +-------------------------------------------- |
| 66 | + |
| 67 | +In this section, you can create and configure your MongoDB service and define |
| 68 | +the data model for your RESTful API. |
| 69 | + |
| 70 | +.. procedure:: Create a MongoDB Service |
| 71 | + :style: connected |
| 72 | + |
| 73 | + .. step:: Create the MongoDBSettings class |
| 74 | + |
| 75 | + Your MongoDB service is responsible for establishing a connection and |
| 76 | + directly working with documents within MongoDB. In your project, create a |
| 77 | + folder named ``Models``. In the ``Models`` folder, create a new file named |
| 78 | + ``MongoDBSettings.cs``. In this file, add the following code: |
| 79 | + |
| 80 | + .. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBSettingsSetup.cs |
| 81 | + :language: csharp |
| 82 | + :dedent: |
| 83 | + |
| 84 | + The preceding code defines a class named ``MongoDBSettings`` that |
| 85 | + contains information about your connection, the database name, and the |
| 86 | + collection name. |
| 87 | + |
| 88 | + .. step:: Update the appsettings.json file |
| 89 | + |
| 90 | + You can find the data that is stored in the class fields defined in the |
| 91 | + ``MongoDBSettings`` class in the projects' ``appsettings.json`` |
| 92 | + file. Open this file and add the following configuration: |
| 93 | + |
| 94 | + .. code-block:: json |
| 95 | + :copyable: true |
| 96 | + |
| 97 | + { |
| 98 | + "Logging": { |
| 99 | + "LogLevel": { |
| 100 | + "Default": "Information", |
| 101 | + "Microsoft.AspNetCore": "Warning" |
| 102 | + } |
| 103 | + }, |
| 104 | + "AllowedHosts": "*", |
| 105 | + "MongoDB": { |
| 106 | + "ConnectionURI": "<Atlas connection string>", |
| 107 | + "DatabaseName": "sample_mflix", |
| 108 | + "CollectionName": "playlist" |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + This tutorial uses the ``sample_mflix`` database and the ``playlist`` |
| 113 | + collection. Replace the ``<Atlas connection string>`` placeholder with |
| 114 | + your MongoDB Atlas connection string. For more information on how to find |
| 115 | + your connection string, see the :atlas:`Connect to Your Cluster </tutorial/connect-to-your-cluster>` |
| 116 | + tutorial in the Atlas documentation. |
| 117 | + |
| 118 | + .. step:: Create the service |
| 119 | + |
| 120 | + In your project, create a folder named ``Services``. In the ``Services`` |
| 121 | + folder, create a new file named ``MongoDBService.cs`` and add the |
| 122 | + following code: |
| 123 | + |
| 124 | + .. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceSetup.cs |
| 125 | + :language: csharp |
| 126 | + :dedent: |
| 127 | + |
| 128 | + The preceding code defines a class named ``MongoDBService`` that includes |
| 129 | + empty asynchronous functions. Throughout this tutorial, you add code to these |
| 130 | + functions as you create your endpoints. The settings you configured in the |
| 131 | + ``appsettings.json`` file are set to variables. |
| 132 | + |
| 133 | + .. step:: Connect the service to the application |
| 134 | + |
| 135 | + Open the ``Program.cs`` file and add the following code to the top of the file: |
| 136 | + |
| 137 | + .. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBExampleProgram.cs |
| 138 | + :language: csharp |
| 139 | + :dedent: |
| 140 | + :start-after: start-program-setup |
| 141 | + :end-before: end-program-setup |
| 142 | + |
| 143 | + In the preceding code, the ``GetSection()`` function pulls your settings |
| 144 | + from the ``MongoDB`` field in the ``appsettings.json`` file. |
| 145 | + |
| 146 | + .. tip:: |
| 147 | + |
| 148 | + If the template code already has the ``builder`` variable, don't add it twice. |
| 149 | + |
| 150 | + .. step:: Create the document model |
| 151 | + |
| 152 | + Now that the service is set up, you can create a data model for your collection. |
| 153 | + |
| 154 | + In the ``Models`` folder, create a new file named ``Playlist.cs`` and add |
| 155 | + the following code: |
| 156 | + |
| 157 | + .. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistSetup.cs |
| 158 | + :language: csharp |
| 159 | + :dedent: |
| 160 | + |
| 161 | + In the preceding code, the ``Id`` field is serialized as an ``ObjectId`` |
| 162 | + in the ``_id`` field. The field is represented as a string in your application. |
| 163 | + |
| 164 | + The ``movieIds`` field is serialized as ``items``. When you send or |
| 165 | + receive JSON values, the field is also named ``items`` instead of |
| 166 | + ``movieIds``. |
| 167 | + |
| 168 | + If you plan to have your local class field match the document field |
| 169 | + directly, it isn't necessary to define custom mappings. For example, the |
| 170 | + ``username`` field in the preceding code has no custom mappings. It is called |
| 171 | + be ``username`` in C#, in JSON, and in MongoDB. |
| 172 | + |
| 173 | +After this step, you have a MongoDB service and document model for your collection to work |
| 174 | +with .NET Core. |
| 175 | + |
| 176 | +Build CRUD Endpoints |
| 177 | +-------------------- |
| 178 | + |
| 179 | +To create the CRUD endpoints for this application, you must update two |
| 180 | +different files within the project. In this section, you can learn how to define |
| 181 | +the endpoint within a controller and update the corresponding work within the |
| 182 | +service. |
| 183 | + |
| 184 | +.. note:: Data Validation |
| 185 | + |
| 186 | + In this example project, there is no data validation for the HTTP requests. |
| 187 | + |
| 188 | +.. procedure:: Build endpoints to interact with MongoDB |
| 189 | + :style: connected |
| 190 | + |
| 191 | + .. step:: Create a controller |
| 192 | + |
| 193 | + In your project, create a folder named ``Controllers``. In the |
| 194 | + ``Controllers`` folder, create a new file named ``PlaylistController.cs`` |
| 195 | + and add the following code: |
| 196 | + |
| 197 | + .. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerSetup.cs |
| 198 | + :language: csharp |
| 199 | + :dedent: |
| 200 | + |
| 201 | + The ``PlaylistController`` class contains a constructor method that gains |
| 202 | + access to your singleton service class. Then, there is a series of |
| 203 | + endpoints for this controller. |
| 204 | + |
| 205 | + .. step:: Add data through the POST endpoint |
| 206 | + |
| 207 | + Go to ``Services/MongoDBService.cs`` and update the ``CreateAsync`` |
| 208 | + function to use the following code: |
| 209 | + |
| 210 | + .. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceComplete.cs |
| 211 | + :language: csharp |
| 212 | + :start-after: start-create-async |
| 213 | + :end-before: end-create-async |
| 214 | + :dedent: |
| 215 | + |
| 216 | + The preceding code sets the ``_playlistCollection`` in the constructor |
| 217 | + method of the service. This lets your application use the |
| 218 | + ``InsertOneAsync`` method, which takes a passed ``Playlist`` variable and |
| 219 | + inserts it. |
| 220 | + |
| 221 | + To complete the creation of the ``POST`` endpoint, go to the |
| 222 | + ``Controllers/PlaylistController.cs`` file and update the ``Post`` method |
| 223 | + to use the following code: |
| 224 | + |
| 225 | + .. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerComplete.cs |
| 226 | + :language: csharp |
| 227 | + :start-after: start-post |
| 228 | + :end-before: end-post |
| 229 | + :dedent: |
| 230 | + |
| 231 | + When the ``POST`` endpoint executes, the application takes the |
| 232 | + ``Playlist`` object from the ``request``, which .NET Core parses, and |
| 233 | + passes it to the ``CreateAsync`` function in the service. After the |
| 234 | + insert, the code returns information about the interaction. |
| 235 | + |
| 236 | + .. step:: Read data through the GET endpoint |
| 237 | + |
| 238 | + Go to ``Services/MongoDBService.cs`` and update the ``GetAsync`` function to |
| 239 | + use the following code: |
| 240 | + |
| 241 | + .. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceComplete.cs |
| 242 | + :language: csharp |
| 243 | + :start-after: start-get-async |
| 244 | + :end-before: end-get-async |
| 245 | + :dedent: |
| 246 | + |
| 247 | + The ``Find`` operation in the preceding code returns all documents that |
| 248 | + exist in the collection. |
| 249 | + |
| 250 | + To complete the creation of the ``GET`` endpoint, go to the |
| 251 | + ``Controllers/PlaylistController.cs`` file and update the ``Get`` method to |
| 252 | + use the following code: |
| 253 | + |
| 254 | + .. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerComplete.cs |
| 255 | + :language: csharp |
| 256 | + :start-after: start-get |
| 257 | + :end-before: end-get |
| 258 | + :dedent: |
| 259 | + |
| 260 | + .. step:: Update data using the PUT endpoint |
| 261 | + |
| 262 | + Go to ``Services/MongoDBService.cs`` and update the ``AddToPlaylistAsync`` |
| 263 | + function to use the following code: |
| 264 | + |
| 265 | + .. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceComplete.cs |
| 266 | + :language: csharp |
| 267 | + :start-after: start-add-to-playlist-async |
| 268 | + :end-before: end-add-to-playlist-async |
| 269 | + :dedent: |
| 270 | + |
| 271 | + The preceding code sets up a match filter to determine which document or |
| 272 | + documents receive an update, in this case adding an item to your playlist. |
| 273 | + The code matches based on the ``Id`` field, which is unique. Then, the |
| 274 | + code defines the update critera, which is an ``AddtoSet`` operation that |
| 275 | + only adds an item to the array if it doesn't already exist in the array. |
| 276 | + |
| 277 | + The ``UpdateOneAsync`` methods only updates on document even if the match |
| 278 | + filter returns more than one match. |
| 279 | + |
| 280 | + To complete the creation of the PUT endpoint, go to the |
| 281 | + ``Controllers/PlaylistController.cs`` file and update the |
| 282 | + ``AddToPlaylist`` function to use the following code: |
| 283 | + |
| 284 | + .. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerComplete.cs |
| 285 | + :language: csharp |
| 286 | + :start-after: start-put |
| 287 | + :end-before: end-put |
| 288 | + :dedent: |
| 289 | + |
| 290 | + .. step:: Delete data by using the DELETE endpoint |
| 291 | + |
| 292 | + Go to ``Services/MongoDBService.cs`` and update the ``DeleteAsync`` function to |
| 293 | + use the following code: |
| 294 | + |
| 295 | + .. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceComplete.cs |
| 296 | + :language: csharp |
| 297 | + :start-after: start-delete-async |
| 298 | + :end-before: end-delete-async |
| 299 | + :dedent: |
| 300 | + |
| 301 | + The preceding code deletes a single document based on the filter criteria, |
| 302 | + which matches the unique value of the ``Id`` field. |
| 303 | + |
| 304 | + To complete the creation of the DELETE endpoint, go to the |
| 305 | + ``Controllers/PlaylistController.cs`` file and update the |
| 306 | + ``Delete`` function to use the following code: |
| 307 | + |
| 308 | + .. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerComplete.cs |
| 309 | + :language: csharp |
| 310 | + :start-after: start-delete |
| 311 | + :end-before: end-delete |
| 312 | + :dedent: |
| 313 | + |
| 314 | +After this step, you have a complete set of CRUD endpoints for your RESTful API. |
| 315 | + |
| 316 | +Test Your API Endpoints |
| 317 | +----------------------- |
| 318 | + |
| 319 | +With the endpoints created, you can test them using the Swagger UI that is |
| 320 | +included with the template .NET Core application. To do this, go to the |
| 321 | +``Program.cs`` file and remove any code from the template project related to the |
| 322 | +``WeatherForecast`` class. Update the file to include the following code: |
| 323 | + |
| 324 | +.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBExampleProgram.cs |
| 325 | + :language: csharp |
| 326 | + :dedent: |
| 327 | + :start-after: start-program-example |
| 328 | + :end-before: end-program-example |
| 329 | + |
| 330 | +You can replace any repetitive code from the project template with the preceding code. |
| 331 | + |
| 332 | +Execute the following command to run your application: |
| 333 | + |
| 334 | +.. code-block:: bash |
| 335 | + |
| 336 | + dotnet run |
| 337 | + |
| 338 | +After the application starts, open your browser and go to your configured |
| 339 | +localhost URL to access the Swagger UI, for example |
| 340 | +``http://localhost:5000/swagger``. The following image shows how the Swagger UI |
| 341 | +appears: |
| 342 | + |
| 343 | +.. figure:: /includes/figures/restful-api-tutorial-swagger-ui.jpg |
| 344 | + :alt: Swagger UI |
| 345 | + :align: center |
| 346 | + |
| 347 | + The Swagger UI for the RESTful API. |
| 348 | + |
| 349 | +You can test the application by clicking the :guilabel:`Try it out` button on each |
| 350 | +endpoint. To get started, go to the ``/api/playlists`` ``POST`` endpoint |
| 351 | +to add some data to the database. Add the following sample data: |
| 352 | + |
| 353 | +.. code-block:: json |
| 354 | + :copyable: true |
| 355 | + |
| 356 | + { |
| 357 | + "username": "testuser", |
| 358 | + "items": [ |
| 359 | + "1234", |
| 360 | + "5678" |
| 361 | + ] |
| 362 | + } |
| 363 | + |
| 364 | +Run this request to insert data into the database. You can then go to the ``GET`` |
| 365 | +endpoint to see the data you just inserted. You can also test the ``PUT`` and |
| 366 | +``DELETE`` endpoints to update and delete data. |
| 367 | + |
| 368 | +Next Steps |
| 369 | +---------- |
| 370 | + |
| 371 | +To learn more about the operations discussed in this tutorial, see the following |
| 372 | +guides: |
| 373 | + |
| 374 | +- :ref:`csharp-insert-guide` |
| 375 | +- :ref:`csharp-retrieve` |
| 376 | +- :ref:`csharp-update-one` |
| 377 | +- :ref:`csharp-delete-guide` |
0 commit comments