The minimal API with . NET 6 using C# | Kenji Elzerman | Skillshare

Playback Speed


1.0x


  • 0.5x
  • 0.75x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 1.75x
  • 2x

The minimal API with . NET 6 using C#

teacher avatar Kenji Elzerman

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

    • 1.

      1. Introduction

      1:21

    • 2.

      2. Requirements

      0:50

    • 3.

      3. .NET 5 API

      2:24

    • 4.

      4. Create the new API

      3:34

    • 5.

      5. Files and folders

      2:22

    • 6.

      6. Mappings - Preparations

      3:04

    • 7.

      7. Map GET

      2:45

    • 8.

      8. Map GET with parameter

      1:40

    • 9.

      9. Map POST

      3:00

    • 10.

      10. Map DELETE

      2:41

    • 11.

      11. Map PUT

      2:08

    • 12.

      12. Adding dependency Injection

      6:28

    • 13.

      13. Making it ASYNC

      3:08

    • 14.

      14. Conclusion

      0:56

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.

38

Students

1

Projects

About This Class

In this class, I will show you how to create a minimal API with .NET 6. After this class, you will be able to understand mappings for different HTTP requests, add dependency injection to the minimal API, and make the minimal API async. With one project, I will take you from the creation of the minimal API to the end, explaining what I am doing and why.

What we will do in this class:

  • Look back at how we used to make APIs with .NET 5.
  • Create a new minimal API with .NET 6 using C#.
  • A step-by-step guide on how to create a new minimal API in Visual Studio.
  • Add mappings (endpoints for the API). I will cover GET, POST, DELETE, and PUT.
  • Adding dependency injection.
  • Making the API async for better performance.

Please note that this is a beginner's class, and it is advisable to know some C# and have some understanding of what APIs are. Some experience with creating APIs with .NET 5 or older is needed to follow this class. I will not be explaining what APIs are, as there are plenty of courses on that topic. This class is only for creating a minimal API.

Meet Your Teacher

I am a C# developer for over 20 years. I worked on many different projects, different companies, and different techniques. I was a C# teacher for people diagnosed with ADHD and/or autism. Here I have set up complete training for them to learn programming with C#, basic cloud actions, and architecture. The goal was to help them to learn to develop software with C#. But the mission was to help them find a job suitable to their needs.

Now I am enjoying the freedom of traveling the world. Learning new ways to teach and bring information to people through the internet.

See full profile

Level: Beginner

Class Ratings

Expectations Met?
    Exceeded!
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.

Transcripts

1. 1. Introduction: Hi everyone. This is a tutorial about the minimal API in dotnet six. Now, before I start this tutorial, I'm going to explain a little bit of what you can expect and what not they expect in this tutorial. So what you can expect is that I'll be showing you how we are created APIs in dotnet. Fine, It's your way. After-death, I'll show you how you create, can create a minimal API in dotnet six. For this, I will be creating a new project, so we'll be starting off from scratch. So you can see everything that is needed to create a minimal API, which is not much, hence the name minimum. I will be showing you a little bit about the dependency injection and the minimal API. Also, I will be showing you how you can create an async minimal API. So what not to expect is an in-depth explanation about API and APIs in general. I hope you have some knowledge about that because I'm not going to tell you. Also, this is not a tutorial for C Sharp for beginners. If you have not enough knowledge about C-Sharp, I highly recommend you follow a basic course first before starting this tutorial. So with that, let's start. 2. 2. Requirements: Before I started tutorial or course, I usually tell people what kind of requirements that are to follow the tutorial or course. In this case, I'll be using Visual Studio 2022 community version, which is free and easy download from the Internet. Another requirement is basic knowledge of C Sharp. If you are a beginner or C-Sharp, or you have never programmed in C Sharp before, it's not advisable to follow their scores. Another thing you should be aware of is dependency injection. You should know the basic idea of dependency injection, how it works, how to configure it in your programs, how to use it. And the last requirement is async. At least it didn't hurt the term. And you know a little bit about what it does and why it's used for. So if you meet these requirements that start. 3. 3. .NET 5 API: As I said before, let's take a look at that five API before we start with adult Netflix minimal API. So on my screen I have adult net five API opens. This is the project. It has a solution. It has a project like every dotnet application you create. The most thing that stands out is the folder controllers. Within the controllers, there are classes, in this case one, which is the actual controller. When we open a controller, you can see certain methods, attributes, and properties. When you open a controller, you will see the public class, the name of the controller, which inherits of the controller. This is scaffolded code, so this is what Microsoft gives you when you create a new API and that it's fine. I'm not going to create a whole new dotnet find application for small piece of information. There isn't a constructor and there is also a method which is called an action. Now this is typically dotnet five API. It has a folder controllers, which contains the classes, which are the controllers within the controller's actions. And every action has certain return types or not. Furthermore, we have to upset things, program.cs and then startups. Yes. The Epstein things are for the configuration of your Program, which is also in dotnet six. So this is not something we'll say goodbye to. What we do say goodbye to is the startup to startup dot cs is basically the configuration of your project. Here you can configure if you want to use swagger or dependency injection or some kind of logging or whatever, you can configure your DB context if you have one with Entity Framework and much more, this will be moved to the program.cs. And the program.cs is like, you know, every dotnet application has a program dot cs file. This is where the application actually starts. If I should run this, it just works like a normal API. It built, it starts your default browser and you have API and you can try it out if you want. Well, that's all cool and stuff. But this is not what we're going to create. We're going to create adult net CICS API. That's the old way. Maybe this is familiar. I just wanted to show you just in case. Now we're going to create adult Netflix API. 4. 4. Create the new API: Now we know how the dotnet five old way works. Let's create a new API in dotnet six. First thing you need to do, of course, is startup Visual Studio. Usually you will have some recent projects or remove them all for this demonstration. But to create the API, you go to create a new project. When you click on that, it will load all the templates and you can select the template you want. On the left side, I have some recent project templates which already contains the project type I want to create. But for the fun of it, let's search for it. I want to create an API. So in the search box, I type API. There are a few results showing up. The first two are the asp.net Core Web API, and the third one as well. There is just a really big difference. The big difference is, are the languages. The first one is C sharp, the second one is F sharp, and third one is actually not the API. It's the asp.net Core Web App. I want to create an API, so I'll select the first one because I want to create it in C-Sharp and not in F sharp. Also, in the text you see Linux, macOS, windows, cloud, servers, web, web API. So this basically means you can also run this API on a Linux and macOS if you want. Click Next. Now I need to give it a project name. I will just use a demo name, but always think about the name you want to give because it wants to be something that reminds you of what you are creating. I will name this the minimal API demo. I will keep the location isn't the default, which is the repository somewhere? Well, fisher studio stores your projects by default. And the solution name will also be the same as the project name. I click Next. Every project has its own additional information. In this case, the API need some extras. If you create a console application, you will just need to select the framework. In this case, I need to select some more options. In this case, I will be using the doughnut six framework. If I open it, I can select dotnet five, which also says out of support, if I click the dog net five, you will see some options will disappear below. These options are all about the minimal API. So let five does not support minimal API, and therefore I need to select dotnet six or higher. I want to configure it for HTPS, of course, enabled darker. I do have Docker installed on this machine, but I will not enable it at this time. Then it's has a checkbox that says use controllers and check, use minimal APIs. If you start with this the first time, this will be checked. If you keep it checked, you will get the fall of width to control this, which is not something we wanted this time because we want to create a minimal API. So we want to get rid of the controllers. So I'll keep this uncheck Enable OpenAPI support. It's a fancy name for swagger. Keep it at enabled. Because this way we can test our API when we run it. Do not use the top-level statements. This is also something for dotnet six and higher. You can select it or not. I'll just keep it unchecked for this tutorial. If you're happy with your settings, select Create. 5. 5. Files and folders: Now we have to dump that CICS API created and we have Visual Studio open. And let's take a look close look at the folder structure of these new projects. Let's zoom in on this solution explorer. Again, we have our solution and our projects, and these are the scaffold files and folders. I'm not going to talk about them all in depth. I just want to show you that the things that Jason is still available and there is only one class file, the program.cs, the folder controllers is gone, and the startup.js is not available as well. So if you open the program.cs, you will see that everything is configured in this file. You have now a builder where it's creates the web application and way to build or you can add services to your application. This also means for the pension worksheet and your database context and logging and other stuff you will need throughout building your API. You will also see that the whole scaffolding about the weather forecast is also placed in this program dot c. Yes. Everything that was in different classes and in a controller is now placed in this particular file. Here can see the summary of the type of weather types. Below. It is a map gets, which actually is a mapping to a particular endpoint of your API. This code was actually in the controller in dotnet five. This is now in one file. It has a lambda expression body that is actually the function that will return the forecast, which is just not the real forecast. So this is your first example of the minimal API that everything is in one file. And with mappings, you can create the different endpoints of your API. Start this application. We can see what it does. Start off the default browser and you'll see swinger. And this looks exactly the same as with the dotnet application because here I have my endpoint for the weather forecast. I can try it out. I can execute. On the outside. Nothing has changed, but on the inside a lot has changed because now I don't have controllers anymore. I have just one file bank and configure, create, and manage my whole API. 6. 6. Mappings - Preparations: So this is the basic scaffold that information and code for the API in dotnet six. Next step is to create more mappings. We have a mapping for different HTTP requests methods. In this case, I want to use the get the post to delete this for update. So before I do that, I will create some extra coats and preparations before go into the other metrics. So first I will create a new class for a movie. Dish will create an ID, which is an int. I want to create a title. So I can actually name the movie. And I want to give it a rating, which is also an integer, rating 1-5. Next, I want to create a list off the dark movie I just created. And I want to use the movie. Id is one. Rating is, let's give it a five. And the title is Trek. Not a movie. Id2 rating. One. Title is deception. New. Idea. Three. Rating is three. Title is, you ask just because it's really old. And again, new ID is for rating is one and the title is The Green Lantern. And last but not least, id is five. Rating is five. Title is the matrix. Now it gives me a red line and it says top-level statements must proceed. Namespace declarations. Let's move this. Let's move this a little bit to the top, and the error is gone. Alright, so now also let's delete the map gets and the internal records. Keep the app dot run. If you remove that one, the application will not run. And it's really important, I really don't get wider abduct John is not late the last line integrals, but also removed the summaries because we won't be using it anymore and we have a really clear application. So that's the preparation. And now we're going to create the mappings by starting by to get, which is the simplest one. 7. 7. Map GET: Alright, so the first mapping we're going to create is the Get, which is also the request methods, HTTP GET. This is the most simplest one because the API will receive a request from the outside to return some data. And this data is just whatever we want to return. The first thing we need to do is create app dot map gets. This means that we want to create an HTTP get request. In dotnet five, we had to add some attributes to tell the API it's a GET or post or whatever. We don't have to do it anymore. We can just create app dot map, get. Be sure to create the new mappings and all the other types of mappings above the app dot run. Don't create them below them. Map. Get. The first parameter is the pattern. The pattern is actually the endpoint of the API in other applications can point to, to get the data. In this case, I want to call it movies, but it's an API. So I'll put API in front so we know it's data. We get from an API. Let's add another slash in front. The second parameter is the delegate learn, or in this case the lambda expression body, which executes because to return this case movies. So I'll be starting by an anonymous function, create records and say return results. Okay, so the caller knows it will get a status code of 200, which means it's okay. Excuse me. 204 means it's okay. It has been executed but you have not returned data. In this case, it will be 200 because I'll be returning the movies. And don't forget the semicolon at the end. This is basically the most simplest API mapping. You will get. Dot map gets, this is the endpoint API slash movies. The body returns results, okay? And the perimeter is movies, which is the list of movies. I can start is now the API and we'll build and starts the default browser. The weather forecast is gone. We now see the API slash movies. I can click it open, try it out, executes. And I have it. These are my movies. So this is the map. Get the most simplest one. And let's move on to something different. Let's get a movie by ID, which is also a GET request. By the way, a parameter in the URL. 8. 8. Map GET with parameter: So the next one is the map get about with a perimeter, in this case the ID of a movie. What I want to create is the, you can get a single movie from the API by given an ID in the end point, it's pretty similar than the previous map gets. So I can actually copy paste this. And the only thing I will change is adding a curly brackets ID in the end point of the movies, and there needs to be a slash in front of it. I now create an endpoint that says API movies and the ID of a movie. And the next part is that in an anonymous function, I'll include the perimeter in this case id. The API will notice there is an extra parameter and then point, he will try to parse that perimeter to an integer, and then I can use it in my methods. In this case, return results, okay? Movies burnt, single ID equals to give an ID. That's basically it. I can start the API now. I see a second endpoint API, movies, curly bracket ID and curly brackets. I can open it, try it out for ID, I'll choose to execute. And there we have our movie with ID to. I can change the ID to four, execute, and I'll see the movie with an ID for this case, typically, the Green Lantern. 9. 9. Map POST: So the next part is about the posting. In some cases you want to post data from the clients to the API. And to prepare the API for a post request, we are going to map the post. To create this, we simply create a new dot map, map boast. And it has the same end point. Or to start movies. And that's it because I wanted to send a movie to the endpoint API movies. In a brief just mapping in the ID, we had to create parameter in the URL. In this case relieved the endpoint as S, in this case, API movies. But I'm going to add the Movie class type with a name in the parameter list of my body. In this case, the API knows that when the API movies endpoint with the post request methods is called, there should be an object in the body that represents the Movie class. I went to dots. I can continue in this case, I can say movies, print, ad movie. And that's it. Normally with a boss, you don't return data and maybe just created object. For demo purposes, I will use a return and return all the movies. So you can see that the movie has been added to the list of movies. So return results. Okay. Don't forget the semicolon at the end of the row. And let's start it up. So now I have three endpoints to get. One post and the posttest, the one we just created. I can open it. I can say try it out. And request body is basically adjacent. Well, IDs are usually created on its own. In my case it doesn't. So I'll be adding my own ID and I will be using ICD-9. The title is the Muppets and the rating is five. That's it. This is what will be posted to my API. I do execute. And the code is 200, which is the results, but okay. And at the end is ICD-9, the Muppets ratings five. So now I have posted data to the API. If I returned to the API movies endpoint, but for the GET requests methods, I execute that one. I will see again the Muppets because I didn't not to shut down my API. So it's still in memory in the list when I shut down the API and they started restarted ICD-9, the Muppets will be gone. 10. 10. Map DELETE: Now we have created three endpoints for a gas, get my ID and a boast. The next moment will be the delete. This one will send a delete request to the API so the API knows something will be deleted. The map delete, which is the mapping for the endpoint for deletion, is fairly similar than the previous one. I will create an app map, delete. And the end point will be the same as the post and the first GET we created. And behind it, I will create the perimeter for ID, and I will cause it to an integer which is the same as the gate by ID. There's no conflict between these two end points because they are separated by the get and delete requests methods. So if I sent a GET request method with an id in the end point, I will receive and see the movie with a given ID. If I use the same URL or endpoints and send it with a delete request method to the API, that particular movie will be deleted. I'll add the ID in the parameter list as well. So I can use it in my body. And this is basically common knowledge. If you're working with C-Sharp, movies, remove movies, single, and find the ID. And that's it. This is normal way of deleting an item through an API. You don't return anything. The client will receive a 200 girls which is okay or 204 or errors like 400's, 500's. That's all you need to know on the client side. But in our case, we want to see if it really works. So I'll be returning the results. Okay. Movies. All right. That's it. Let's test it out. I'll start up the API. The default browser is opening again. And you'll see for endpoints now to get the, get the post and delete. To get, I'll expand the leads, I'll try it out. And let's delete movie with ID two. I have no idea what movie this but okay, executes. And in this case, I see the first one is Shrek with id one, and the second one is jaws with ID three, and the ID two has been deleted. That's how I delete work. 11. 11. Map PUT: The last mapping we're going to create is the update. Or rather the foot is being used to indicate you want to change an existing object or value. The output is actually the same as boasting except you change my poster map. So in this case, map both endpoints. Just API movies and I'll add movie over in the parameter list. If you want to update an existing object, you need to know where to find it. So I'm assuming the ID has been filled off the movie. In this case, I have to get the existing object from the list. Found. Movie is movies single dot ID. And now I can change the contents of the file moving. So e.g. movement rating equals the movie rating that is being boasted throughput to the API. And that's it. Usually you have Entity Framework to handle the changes and staff, but in this case, Justin list, I can now say return results. Okay, movies. Alright, and let's start it up. Let's see if it works. I hear my boots and expanded one. Try it out. Let's change the second movie title. I can leave an empty because I'm not updating that. And the rating is set to five. Let's execute it. Returning all the movies. And here we go. Id2 is the title, inception. I've set that to a random one and now it's five. And that concludes the update order. 12. 12. Adding dependency Injection: So now we have discussed the basic needs of the API in dotnet six. We have to talk about the general setup and how we can create endpoints through mappings. Next item on the list is dependency injection, something we as developers use a lot in our code. And an amino API does accept the dependency injection pattern as well. And how we can do this is by almost the same as in dotnet. Fine. Just don't do it in a startup because it's not there. We now have to configure it in the program.cs. So first of all, I did make some changes in my application. Let's walk through that first before I'm going to explain how you can use dependency injection. So this is my application and I create a new folder logic. And within the folder there are two files, movie dossier and movie surface dot. So there's the movie does say yes. Actually object movie which was previously in the program.cs, But I moved it to this file. And the movie servers is a class that handles everything for movies. When I opened that, there's a private list of movies which contains the same movies and the program.cs. And there are a few methods in this case, delete, get all, get by ID and insert. I removed the update because I just want to keep it short and simple. The program.cs has been cleaned up. Here I initialize the movie service into a variable. Let's rename that for obvious purposes. Renamed it to movie service when a small m. And I changed all the bodies of the endpoints with movie service instead of a list of movies because that's not here anymore. So I removed the Movie class and the list of movies from this file and move them to the folder logic. Okay, Cool. To create the penance injection, we need an interface. In this case, I want to create an interface of the movie service. There are fewer public methods which needs to be in the interface are first, I'll create a new interface in the file logic, and I call it movie service. And I'll just copy, delete, and then at least moving. And then move it. Good, bad idea and inserts. Alright, and these are voids. Alright? They have interface. Now I'm going to connect the interface with the class Movie Service. And they added it. So now I have an interface connected to the movie service class. I go back to the program.cs and I'm going to start looking for the builder dot service, especially because that's where we configure our dependency injection. So what I usually do is I look for the ad swagger gin and below that, I'll type filler services scoped. All right, Moving service and connect it to the movie service class. That's it. Now we have configured our dependency injection for movie service. But how are we going to use it in our endpoints? You basically, you put it in the parameter list of the function. Let's start with the simplest one, the map.get or map get rich has an endpoint of API movies, an empty parameter list, and return which also came over. Servicemen, get all buddy. These will be very simple because I will be injecting the interface into the parameter list of the body. So in this case, I Movie Service, I'll give it a name, Movie Service. It gives an error. Now, I can leave this the same because they are one-on-one. I have injected the iMovie service into my method. How does it work with the second one, which is the midgut, and I can get one movie by ID, very simple, int id comma i movie service. And it works. You can just put the penance injection behind the parameter list of the end point queries or other parts of the action. Same goes for the post. I have here a movie which is being posted by a client to the API coma movie service, movie service, and delete. The same as the gate by ID. It already gives the hint, maybe you want the iMovie serves. I want. And now it's done. I can remove the realization of the movie service. And it still works if I just press F5 now, it will start the API. And you can see if it actually worked. I still see all my endpoint here. And let's try the gets dried out, executes. And I still see all my movies. Let's try to boast, try it out. Id nine Muppets, and the rating is five. Executes. As you can see, the Muppets has been added to that list. Of course, this is not the best example for dependency injection because I'm using, I'm configuring the dependency injection and directly using it. Usually it's all over the place and that's okay. But as dependency injection in a nutshell. 13. 13. Making it ASYNC: Last chapter of this course is about making API a sink with means that the API can handle multiple requests at the same time. And that makes the API a little bit faster to make your actions and methods async, we have to change a little bit of the goals and it's really easy. It's not really that much of work. First thing I want to do is go to the interface and make everything prepared for a sings. So I'll be adding task to all the methods. In this case task list moving. I'm moving. And change the voice to dusk. Alright, that's easy. Now go to the surface and you will see that it breaks because the implementation of the service is not the same as the interface anymore. So let's change this one as well quickly. Again, this is something you should know before you started this course, and I need to make it all async, otherwise it doesn't work. So that's just a copy paste action. Because this is a demo about making something async. Usually something within the method should be available. Well, this is not the case, but I make all the methods async await them in the API, which is the whole point of this demonstration. Alright, so everything is now prepared for async tasks. I go back to the program.cs. Here you can see nothing changed. There are no warnings, no errors. But if I hover over, simple get all, you will see that it's available. So I can just type here and wait. About debt doesn't work because in a way it always needs to be used inside an async method and this method or the body is not async. So to make it async, simply type async here, and then it works. So now I see that the movie service dot insert is available as well. So we did this one too. So I can make everything async by just adding async to all the lambda expressions and make the movie service methods. I'll wait. That's it. So now I start the API and it's still the same. There's nothing changed. Let's execute the get to try it out, executes. And I have it. I can do this the same for the other endpoint as well. But I think you get the point. This is how you make the minimal API async. 14. 14. Conclusion: Well, that concludes our minimal API in dotnet six. It's a great way to create smaller APIs with less girls. And hasn't he fell apart? I like less code. Downside is if you have a really big API, you have one big file with all the endpoints. So what happens is that people are going to spread out the different end points throughout different files. And then basically creating controllers again, doesn't really work. I think so if you have small APIs and microservices, but not for the bigger projects where you have a really big API that handles a lot of requests. Thank you for watching. I hope you have learned something. If you have any questions, just let me know in the comments or send me a message. Don't forget to follow me for more tutorial coming in the near future. Thank you and goodbye.