-
Notifications
You must be signed in to change notification settings - Fork 25
DOCSP-48859 Add RESTful API tutorial #617
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mcmorisi
merged 15 commits into
mongodb:master
from
stephmarie17:docsp-48859-restfulApiTutorial
Apr 30, 2025
Merged
Changes from 9 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
a4c4c11
part one tutorial
stephmarie17 bf452dd
edits
stephmarie17 47d7f30
add crud section
stephmarie17 0f33792
add test section
stephmarie17 09c2357
edits
stephmarie17 db47c06
add resources
stephmarie17 972030a
cleanup
stephmarie17 0d2521d
edits
stephmarie17 647441b
shorten toc title
stephmarie17 6ee7b2c
RR feedback pt one
stephmarie17 46a2e9e
Merge remote-tracking branch 'origin/master' into docsp-48859-restful…
stephmarie17 e861c2e
edits
stephmarie17 65c065c
vale fixes
stephmarie17 e0bf08b
RR feedback
mcmorisi 85c02da
Fix typo
mcmorisi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,384 @@ | ||
.. _csharp-crud-restful-api-tutorial: | ||
rustagir marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
===================================================================== | ||
Tutorial: Create a RESTful API with the {+driver-short+} Driver | ||
mcmorisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
===================================================================== | ||
rustagir marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
.. facet:: | ||
:name: genre | ||
:values: reference | ||
|
||
.. meta:: | ||
:keywords: crud, code example, tutorial | ||
:description: Learn how to use the .NET/C# Driver to create a RESTful API for your application. | ||
|
||
.. contents:: On this page | ||
:local: | ||
:backlinks: none | ||
:depth: 1 | ||
:class: singlecol | ||
|
||
Overview | ||
-------- | ||
|
||
In this tutorial, you will learn how to create a RESTful API with endpoints that | ||
perform basic create, read, update, and delete (CRUD) operations across MongoDB | ||
Atlas. | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Prequisites | ||
mcmorisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
----------- | ||
|
||
To complete this tutorial, you must have the following: | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
- An `Atlas account | ||
<https://account.mongodb.com/account/register?tck=docs_atlas>`__ with a | ||
deployed and configured MongoDB Atlas cluster that is M0 or higher. | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
- .NET 6.0 or higher `installed <https://dotnet.microsoft.com/en-us/download>`__ on your machine. | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
To learn how to get started with MongoDB Atlas and how to load sample data, see the | ||
:atlas:`Get Started with Atlas Guide </getting-started>`. | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
This tutorial uses .NET Core 8.0, but you can use any version later than .NET 6.0. | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Set Up Your Project | ||
------------------- | ||
|
||
You can create a new .NET Core project using the web application template that | ||
Microsoft offers. To do this, run the following commands in your terminal: | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
.. code-block:: bash | ||
|
||
dotnet new webapi -o MongoExample | ||
cd MongoExample | ||
|
||
To add the {+driver-short+} to your project as a dependency, run the following command: | ||
|
||
.. code-block:: bash | ||
|
||
dotnet add package MongoDB.Driver | ||
|
||
The preceding commands create a new web application project for .NET core named | ||
``MongoExample`` and install the latest {+driver-short+}. The template project | ||
includes some boilerplate files. During this tutorial, you will add to these | ||
files and remove some of the boilerplate code to create a RESTful API. | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Design a Document Model and Database Service | ||
-------------------------------------------- | ||
|
||
In this section, you will create and configure your MongoDB service and define | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
the data model for your RESTful API. | ||
|
||
.. procedure:: Create a MongoDB Service | ||
:style: connected | ||
|
||
.. step:: Create the MongoDBSettings class | ||
|
||
Your MongoDB service will be responisble for establishing a connection and | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
directly working with documents within MongoDB. In your project, create a | ||
folder named ``Models``. In the ``Models`` folder, create a new file named | ||
``MongoDBSettings.cs``. In this file, add the following code: | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBSettingsSetup.cs | ||
:language: csharp | ||
:dedent: | ||
|
||
The preceding code defines a class named ``MongoDBSettings`` that | ||
contains information about your connection, the database name, and the | ||
collection name. | ||
|
||
.. step:: Update the appsettings.json file | ||
|
||
The data that will be stored in the class fields defined in the | ||
``MongoDBSettings`` class is found in the projects' ``appsettings.json`` | ||
file. Open this file and add the following: | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
.. code-block:: json | ||
:copyable: true | ||
|
||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Information", | ||
"Microsoft.AspNetCore": "Warning" | ||
} | ||
}, | ||
"AllowedHosts": "*", | ||
"MongoDB": { | ||
"ConnectionURI": "ATLAS_URI_HERE", | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"DatabaseName": "sample_mflix", | ||
"CollectionName": "playlist" | ||
} | ||
} | ||
|
||
Note the ``MongoDB`` field. This tutorial uses the ``sample_mflix`` | ||
database and the ``playlist`` collection. Replace the ``ATLAS_URI_HERE`` | ||
placeholder with your MongoDB Atlas connection string. For more | ||
information on how to find your connection string, see the | ||
:ref:`csharp-quickstart` guide. | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
.. step:: Create the service | ||
|
||
In your project, create a folder named ``Services``. In the ``Services`` | ||
folder, create a new file named ``MongoDBService.cs`` and add the | ||
following code: | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceSetup.cs | ||
:language: csharp | ||
:dedent: | ||
|
||
The preceding code defines a class named ``MongoDBService`` that includes | ||
empty asynchronous functions. In this tutorial, you will add code to these | ||
functions as you create your endpoints. The passed settings from the | ||
``appsettings.json`` file are set to veriables. | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
.. step:: Connect the service to the application | ||
|
||
Open the ``Program.cs`` file and add the following code to the top of the file: | ||
|
||
.. code-block:: csharp | ||
:copyable: true | ||
|
||
using MongoExample.Models; | ||
using MongoExample.Services; | ||
|
||
var builder = WebApplication.CreateBuilder(args); | ||
|
||
builder.Services.Configure<MongoDBSettings>(builder.Configuration.GetSection("MongoDB")); | ||
builder.Services.AddSingleton<MongoDBService>(); | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
In the preceding code, the ``GetSection`` function pulls your settings | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
from the ``MongoDB`` field in the ``appsettings.json`` file. | ||
|
||
.. tip:: | ||
|
||
If your boilerplate code already has the ``builder`` variable, don't add it twice. | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
.. step:: Create the document model | ||
|
||
Now that the service is set up, you can create a data model for your collection. | ||
|
||
In the ``Models`` folder, create a new file named ``Playlist.cs`` and add | ||
the following code: | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistSetup.cs | ||
:language: csharp | ||
:dedent: | ||
|
||
In the preceding code, the ``Id`` field is represented as an ``ObjectId`` | ||
in BSON and the ``_id`` fild within MongoDB. When you work with this | ||
locally in your application, it is a string. | ||
mcmorisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
The ``movieIds`` field will be known as ``items``. When sending or | ||
receiving JSON, the field will also be known as ``items`` instead of | ||
``movieIds``. | ||
mcmorisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
If you plan to have your local class field match the document field | ||
directly, you don't need to define custom mappings. For example, the | ||
``username`` field in the preceding code has no custom mappings. It will | ||
be ``username`` in C#, in JSON, and in MongoDB. | ||
mcmorisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
You now have a MongoDB service and document model for your collection to work | ||
with for .NET Core. | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Build CRUD Endpoints | ||
-------------------- | ||
|
||
To create the CRUD endpoints for this application, you need to update two | ||
different files within the project. In this section, you can learn how to define | ||
the endpoint within a controller and update the corresponding work within the | ||
service. | ||
|
||
.. note:: | ||
mcmorisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
In this example project, there is no data validation for the HTTP requests. | ||
|
||
.. procedure:: Build endpoints to interact with MongoDB | ||
:style: connected | ||
|
||
.. step:: Create a controller | ||
|
||
In your project, create a folder named ``Controllers``. In the | ||
``Controllers`` folder, create a new file named ``PlaylistController.cs`` | ||
and add the following code: | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerSetup.cs | ||
:language: csharp | ||
:dedent: | ||
|
||
The ``PlaylistController`` class contains a constructor method that gains | ||
access to your singleton service class. Then, there is a series of | ||
endpoints for this controller. | ||
|
||
.. step:: Add data through the POST endpoint | ||
|
||
Go to ``Services/MongoDBService.cs`` and update the ``CreateAsync`` | ||
function to use the following code: | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceComplete.cs | ||
:language: csharp | ||
:start-after: start-create-async | ||
:end-before: end-create-async | ||
:dedent: | ||
|
||
The preceding code sets the ``_playlistCollection`` in the constructor | ||
method of the service. This lets your application use the | ||
``InsertOneAsync`` method, which takes a passed ``Playlist`` variable and | ||
inserts it. | ||
|
||
To complete the creation of the ``POST`` endpoint, go to the | ||
``Controllers/PlaylistController.cs`` file and update the ``Post`` method | ||
to use the following code: | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerComplete.cs | ||
:language: csharp | ||
:start-after: start-post | ||
:end-before: end-post | ||
:dedent: | ||
|
||
When the ``POST`` endpoint executes, the application takes the | ||
``Playlist`` object from the ``request``, which .NET Core parses, and | ||
passes it to the ``CreateAsync`` function in the service. After the | ||
insert, the code returns some information about the interaction. | ||
mcmorisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
.. step:: Read data through the GET endpoint | ||
|
||
Go to ``Services/MongoDBService.cs`` and update the ``GetAsync`` function to | ||
use the following code: | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceComplete.cs | ||
:language: csharp | ||
:start-after: start-get-async | ||
:end-before: end-get-async | ||
:dedent: | ||
|
||
The ``Find`` operation in the preceding code returns all documents that | ||
exist in the collection. | ||
|
||
To complete the creation of the ``GET`` endpoint, go to the | ||
``Controllers/PlaylistController.cs`` file and update the ``Get`` method to | ||
use the following code: | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerComplete.cs | ||
:language: csharp | ||
:start-after: start-get | ||
:end-before: end-get | ||
:dedent: | ||
|
||
.. step:: Update data using the PUT endpoint | ||
|
||
Go to ``Services/MongoDBService.cs`` and update the ``AddToPlaylistAsync`` | ||
function to use the following code: | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceComplete.cs | ||
:language: csharp | ||
:start-after: start-add-to-playlist-async | ||
:end-before: end-add-to-playlist-async | ||
:dedent: | ||
|
||
The preceding code sets up a match filter to determine which document or | ||
documents receive an update, in this case adding an item to your playlist. | ||
The code matches based on the ``Id`` field, which is unique. Then, the | ||
code defines the update critera, which is an ``AddtoSet`` operation that | ||
only adds an item to the array if it doesn't already exist in the array. | ||
|
||
The ``UpdateOneAsync`` methods only updates on document even if the match | ||
filter returns more than one match. | ||
|
||
To complete the creation of the PUT endpoint, go to the | ||
``Controllers/PlaylistController.cs`` file and update the | ||
``AddToPlaylist`` function to use the following code: | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerComplete.cs | ||
:language: csharp | ||
:start-after: start-put | ||
:end-before: end-put | ||
:dedent: | ||
|
||
.. step:: Delete data using the DELETE endpoint | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Go to ``Services/MongoDBService.cs`` and update the ``DeleteAsync`` function to | ||
use the following code: | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBServiceComplete.cs | ||
:language: csharp | ||
:start-after: start-delete-async | ||
:end-before: end-delete-async | ||
:dedent: | ||
|
||
The preceding code deletes a single document based on the filter criteria, | ||
which matches the unique value of the ``Id`` field. | ||
|
||
To complete the creation of the DELETE endpoint, go to the | ||
``Controllers/PlaylistController.cs`` file and update the | ||
``Delete`` function to use the following code: | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/PlaylistControllerComplete.cs | ||
:language: csharp | ||
:start-after: start-delete | ||
:end-before: end-delete | ||
:dedent: | ||
|
||
You now have a complete set of CRUD endpoints for your RESTful API. | ||
mcmorisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Test Your API Endpoints | ||
----------------------- | ||
|
||
With the endpoints created, you can test them using the Swagger UI that is | ||
built-in to the boilerplate .NET Core application. To do this, go to | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
``Program.cs`` file and remove any code from the template project related to | ||
``WeatherForecast`` and similar. Update the file to include the following code: | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/restful-api-tutorial/MongoDBExampleProgram.cs | ||
:language: csharp | ||
:dedent: | ||
:start-after: start-program-example | ||
:end-before: end-program-example | ||
|
||
You can replace any repetitive code in the boilerplate with the preceding code. | ||
|
||
Execute the following command to run your application: | ||
|
||
.. code-block:: bash | ||
|
||
dotnet run | ||
|
||
After the application starts, open your browser and go to your configured | ||
localhost URL to access the Swagger UI, for example | ||
``http://localhost:5000/swagger``. The Swagger UI looks like the following: | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
.. figure:: /includes/figures/restful-api-tutorial-swagger-ui.jpg | ||
:alt: Swagger UI | ||
:align: center | ||
|
||
The Swagger UI for the RESTful API. | ||
|
||
You can test the application by clicking the ``Try it out`` button on each | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
endpoint. To get started, go to the ``/api/playlists`` ``POST`` endpoint | ||
to add some data to the database. Add the following as dummy data: | ||
stephmarie17 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
.. code-block:: json | ||
:copyable: true | ||
|
||
{ | ||
"username": "testuser", | ||
"items": [ | ||
"1234", | ||
"5678" | ||
] | ||
} | ||
|
||
Run this request to insert data into the database. You can then go to the ``GET`` | ||
endpoint to see the data you just inserted. You can also test the ``PUT`` and | ||
``DELETE`` endpoints to update and delete data. | ||
|
||
Next Steps | ||
---------- | ||
|
||
To learn more about the operations discussed in this tutorial, see the following | ||
guides: | ||
|
||
- :ref:`csharp-insert-guide` | ||
- :ref:`csharp-retrieve` | ||
- :ref:`csharp-update-one` | ||
- :ref:`csharp-delete-guide` |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.