.NET 5 REST API Tutorial – Build From Scratch With C#

Ecommerce Empire Academy

Learn how to create a REST API end-to-end from scratch using the latest .NET 5 innovations and Visual Studio Code. The API will be written in C#.

💻 Get the code:

✏️ Course developed by Julio Casal. Check out his channel:
🔗 Julio's website:

⭐️ Course Contents ⭐️
Getting Started
0:00:00 Introduction
0:03:02 Creating the project
0:04:01 Exploring the generated project files
0:10:03 Trusting the self-signed certificate
0:11:36 Exploring the default Swagger UI page
0:12:30 Configuring Visual Studio Code settings

Entity, Repository, Controller GET
0:14:33 Introduction
0:15:45 Adding an entity
0:20:39 Ading an in-memory repository
0:26:40 Creating the controller
0:30:42 Implemeting GET all items
0:33:37 Implemeting GET single item
0:37:47 Returning a 404 NotFound status code

Dependency Injection, DTOSs
0:39:57 Introduction
0:41:23 What is dependency injection?
0:46:14 Extracting the repository interface
0:47:44 Injecting the repository into the controller
0:48:53 Registering the repository as a singleton
0:52:32 Adding a Data Transfer Object DTO
0:55:46 Creating the AsDto extension method

POST, PUT, DELETE
0:58:59 Introduction
0:59:45 Implementing POST
1:07:39 Adding validations via data annotations
1:10:00 Implemeting PUT
1:17:33 Implementing DELETE

Persisting Entities with MongoDB
1:20:46 Introduction
1:24:44 Using Postman
1:27:53 Creating a MongoDB repository
1:29:42 Using the MongoDB.Driver NuGet package
1:33:28 Implementing MongoDB Create
1:33:57 Running the MongoDB Docker container
1:38:47 Configuring MongoDB connection settings
1:42:38 Registering the MongoClient singleton
1:48:02 Testing the MongoDB integration
1:50:04 Exploring the created database in VS Code
1:52:45 Implemeting MongoDB Get, Update and Delete

Tasks, Async and Await
2:02:27 Introduction
2:06:46 Using the Async suffix
2:09:04 Using tasks in the repository
2:11:50 Using async and await
2:14:28 Returning completed tasks
2:18:16 Using tasks in the controller
2:21:23 Testing async methods in Postman

Secrets and Health Checks
2:27:02 Introduction
2:30:06 Enabling authentication in MongoDB
2:33:36 Using the .NET Secret Manager
2:36:40 Using the MongoDB credentials in the service
2:40:00 Introduction to Health Checks
2:42:28 Adding an endpoint for health checks
2:44:46 Adding a MongoDB health check
2:48:41 Adding checks for readiness and liveness
2:53:51 Customizing the health check response
2:58:59 Exploring other health check NuGet packages

Docker
3:00:44 Introduction
3:08:28 What is Docker?
3:17:54 Removing https redirection
3:20:39 Generating a Dockerfile in VS Code
3:30:40 Building the Docker image
3:33:00 Adding a Docker network
3:34:07 Running the containers in the Docker network
3:40:36 Running the REST API in Docker
3:42:02 Pushing the container image to Docker Hub
3:46:02 Exploring the image in Docker Hub
3:46:32 Pulling the image back to the local box

Kubernetes
3:49:20 Introduction
3:54:05 What is Kubernetes?
4:04:06 Enabling a Kubernetes cluster in Docker Desktop
4:06:12 Installing the Kubernetes extension for VS Code
4:06:58 Declaring the REST API Kuberentes deployment
4:14:35 Creating a secret in Kubernetes
4:17:28 Declaring health probes
4:19:14 Declaring the REST API Kubernetes service
4:22:56 Creating the REST API resources in Kubernetes
4:26:15 Declaring the MongoDB Kubernetes StatefulSet
4:36:09 Declaring the MongoDB Kubernetes service
4:38:27 Creating the MongoDB resources in Kubernetes
4:40:42 Testing the REST API hosted in Kubernetes
4:42:08 Exploring the Kubernetes self-healing capability
4:46:04 Scaling Kubernetes pods
4:47:38 Adding logs via ILogger
4:52:04 Getting a new image version into Kubernetes
4:53:23 Load balancing requests across pods

Unit Testing and TDD
4:56:23 Introduction
4:57:04 What is unit testing?
5:01:19 What is test driven development?
5:04:25 Restructuring files and directories
5:08:25 Creating the xUnit test project
5:09:15 Building multiple projects in VS Code
5:13:10 Adding NuGet packages for unit testing
5:14:35 Testing GetItemAsync unexisting item
5:18:35 Using the AAA pattern
5:19:31 Stubbing dependencies via Moq
5:26:52 Running tests in VS Code
5:28:05 Using the .NET Core Test Explorer extension
5:30:55 Testing GetItemAsync existing item
5:38:01 Using FluentAssertions
5:41:46 Testing GetItemsAsync
5:45:41 Testing CreateItemAsync
5:53:13 Testing UpdateItemAsync
5:57:51 Testing DeleteItemAsync
5:59:40 Refactoring and catching regressions
6:10:50 Using TDD to test a yet to be created method
6:19:07 Going back to green by fixing the failing test
6:21:19 Testing the new controller method in Postman

37 thoughts on “.NET 5 REST API Tutorial – Build From Scratch With C#”

  1. Deontay Jefferson

    Thanks, I have been using the Js stack, but recently began playing with C# and Asp.Net MVC. This is literally right on time.

    1. @Deontay Jefferson It’s same here. However majority of the jobs with .NET requires AngularJs or Angular in my area. I do have to learn both now. Since, I already know node, express and react, I hope learning angular will be easier.

    2. @Bibek Khatri Are you from Nepal as well?
      I have seen a lot more posting for React though and Node.js is also in demand.

    3. @Alan Walker Yes, I’m from Nepal. I haven’t seen for Node upto now. In my area the most of the listings are for .NET and AngularJS. I wonder why they still use AngularJs. That was the initial release and it’s going to be out of support soon.

  2. Thanks a lot Beau for sharing the tutorial in this awesome channel. Really hope it helps folks get started with my favorite platform!

    1. Thanks Julio! I learnt a lot of new concepts and will be checking out some of your other courses on your site

    2. after running the rest api docker image, when i try to test, i get an error “Error: write EPROTO 140681090257224:error:100000f7:SSL routines:OPENSSL_internal:WRONG_VERSION_NUMBER:../../third_party/boringssl/src/ssl/tls_record.cc:242:”

      Also tried enabling httpredirection for production but its still the same. Tried reaching the endpoint using http and it does not work also

    3. Thanks Julio, you are absolutley amazing. Never met a better teacher, once im done melting this video i might just head over to your site and subscribe to your coarses. Thanks

    4. Thanks Julio! You are amazing, I genuinely enjoyed this tutorial and I can’t say that about many teachers.

  3. Juan Carlos Hernandez

    Great way of teaching, pretty useful and keeps you interestet. Better than lots of PluralSigth courses. Excellent job!

  4. André Lashley

    Really enjoyed this course, I’m a .NET developer and learned a lot. Great pacing, very few assumptions and solid presentation.

    1. sorta of a noob in .net, (i came from python/R)

      is this different from ASP.NET?
      can I deploy machine learning models here?

    2. André Lashley

      @Arvin Flores Its different from .NET in that its much easier to run cross-platform (Linux, Windows etc), its also a lot more lightweight than .NET in terms of the packages included.

      For deploying machine learning models, I’ve come across this package: https://github.com/SciSharp/TensorFlow.NET but haven’t used it. There are also other ML packages available that are .NET specific or ports of Python libs (I’ve seen a C# version of numpy for example).

  5. great job explaining what to do and why we doing it that way. I love the comparison of before and after instead of just “lets do it this way because its cool” then moved on. Thank you!

  6. This is a lot of information to digest and learn. A big thank you! My only wish is it would have been awesome if you have added a JWT security in your API, thanks!

  7. One of the very very few good courses available on YouTube ! very precise and this tutorial is priceless !

  8. Ricardo Lourenco

    This is absolutely amazing!! It was really a great course in the fundamentals also the Docker and Kubernetes demos were perfect! Thanks again for sharing it …

  9. This tutorial is one step beyond. You look at other tutorials and it’s just a lot of instructions with an occasionaly helpful screenshot. Here you show in real time what you are doing and explain the concepts at the same time. This has been revealing some of the mystery behind some of the code for me.

  10. I’m 2 hours in and I’m loving this tutorial. This is the tutorial that I’ve been looking for amazing stuff ! @Julio Casal Docker is super and this is a great soft useful introduction.

  11. Redants Caribbean

    This is the first tutorial of the many I watched which showed DI and DI containers in such an understandable format. I never understood it as well as I now.

  12. Thanks a lot for this wonderful detailed course that covers all basic building blocks of setting up a working REST API solution.

    This is really a great contribution. Appreciate a lot!

  13. Leonardo Fernandes

    This is some precious content. Never seen a tech instructor/teacher this good. Actually explains things without assuming that you already know it all. Most of the people out there are just so disconnected when trying to teach tech related things… some of them just paste code and read it trying to explain which is honestly an awful way to teach code and some just type code assuming you know it all already (which is understandable, most of them are developers/experts and not actually teachers) I finally understand what dependency injection actually is! THANK YOU so much. Great video.

  14. Michael Paraskakis

    Hi Julio, I purchased your course after watching this introductory video. That said, I am still learning .NET and it would have been nice to have the code at the end of each section so that I could compare the original code to the final refactored code. I don’t suppose you have the code saved by section by chance?

    1. Michael, thanks for your purchase! If you are looking for the code for the .NET Rest API tutorial, section by section, you can find it in my channel. Look for this same tutorial there, where it is actually a playlist, each video having a link to the corresponding source code.

  15. Hey Julio, great comprehensive tutorial! I’m learning a lot. I’m roughly about 2 1/2 hours through and I’m running into some errors when implementing the secret management. Could really use help. I’m receiving this in postman:

    MongoDB.Driver.MongoAuthenticationException: Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1.
    —> MongoDB.Driver.MongoCommandException: Command saslStart failed: Authentication failed..
    at MongoDB.Driver.Core.WireProtocol.CommandUsingQueryMessageWireProtocol`1.ProcessReply(ConnectionId connectionId, ReplyMessage`1 reply)
    at MongoDB.Driver.Core.WireProtocol.CommandUsingQueryMessageWireProtocol`1.ExecuteAsync(IConnection connection, CancellationToken cancellationToken)
    at MongoDB.Driver.Core.Authentication.SaslAuthenticator.AuthenticateAsync(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken)
    — End of inner exception stack trace —
    at MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelperAsync(CancellationToken cancellationToken)
    at MongoDB.Driver.Core.ConnectionPools.ExclusiveConnectionPool.PooledConnection.OpenAsync(CancellationToken cancellationToken)
    at MongoDB.Driver.Core.ConnectionPools.ExclusiveConnectionPool.ConnectionCreator.CreateOpenedInternalAsync(CancellationToken cancellationToken)
    at MongoDB.Driver.Core.ConnectionPools.ExclusiveConnectionPool.ConnectionCreator.CreateOpenedOrReuseAsync(CancellationToken cancellationToken)
    at MongoDB.Driver.Core.ConnectionPools.ExclusiveConnectionPool.AcquireConnectionHelper.AcquireConnectionAsync(CancellationToken cancellationToken)
    at MongoDB.Driver.Core.ConnectionPools.ExclusiveConnectionPool.AcquireConnectionAsync(CancellationToken cancellationToken)
    at MongoDB.Driver.Core.Servers.Server.GetChannelAsync(CancellationToken cancellationToken)
    at MongoDB.Driver.Core.Operations.RetryableReadContext.InitializeAsync(CancellationToken cancellationToken)
    at MongoDB.Driver.Core.Operations.RetryableReadContext.CreateAsync(IReadBinding binding, Boolean retryRequested, CancellationToken cancellationToken)
    at MongoDB.Driver.Core.Operations.FindOperation`1.ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken)
    at MongoDB.Driver.OperationExecutor.ExecuteReadOperationAsync[TResult](IReadBinding binding, IReadOperation`1 operation, CancellationToken cancellationToken)
    at MongoDB.Driver.MongoCollectionImpl`1.ExecuteReadOperationAsync[TResult](IClientSessionHandle session, IReadOperation`1 operation, ReadPreference readPreference, CancellationToken cancellationToken)
    at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)
    at MongoDB.Driver.IAsyncCursorSourceExtensions.ToListAsync[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
    at Catalog.Repositories.MongoDbItemsRepository.GetItemsAsync() in C:UsersThe BergDesktopProjectsCatalogRepositoriesMongoDbItemsRepository.cs:line 39
    at Catalog.Controllers.ItemsController.GetItemsAsync() in C:UsersThe BergDesktopProjectsCatalogControllersItemsController.cs:line 31
    at lambda_method5(Closure , Object )
    at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
    at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
    at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
    at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
    at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
    at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
    at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
    at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
    at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

    HEADERS

    1. This usually means the secret has not been populated in ASP.NET Core’s configuration system, so your MongoDbSettings.Password property is likely empty. Please make sure you are creating the secret with the correct naming structure so it matches exactly the structure of your MongoDbSettings class.

  16. krzysztof mekwinski

    This tutorial is amazing. It covers a lot of different concepts in very friendly way. I am half way . I wish there would be also small section on connecting this to SQL DB. I am doing that on my own , but including this would be like only source of information for RestAPI.

Comments are closed.