.NET APIs Part 4 – Creating the APIs

We are, finally, ready to create our ASP.NET Core application that will host our traditional and our minimal APIs. (This series begins here.)

The code for this blog post is available here:
git clone https://github.com/JesseLiberty/Cars.git

Please note that WordPress seems to be broken and so the layout will be imperfect.

To get started, open Visual Studio 2022 and make sure you are fully up to date. Click on Create A New Project and select ASP.NET Core Web App, making sure that C# is the selected language

Give your project a name and a location

Choose .NET 7 as your Framework with no authentication and click Create.

If you’ve been following along with this tutorial already, you can steal from your earlier project. Otherwise, just type in the code.

Let’s start in appsettings.json where we will add the connection string to connect us to the database we created last time

Controllers

Key to creating your API is to create controllers. A controller is the class that holds the start of the logic that your API will use. This is much easier to demonstrate than to explain. Start by creating a folder named Controllers

Right click on your Controllers folder and create a class named CarController. For now, all our APIs will originate here. Let’s set up the top of the file by declaring a logger (supplied by Microsoft in the Microsoft.AppNetCore.MVC namespace) and an instance of our CarRepository

REST

We’ll be using REST for our APIs. There is much that you can know about REST, but for our purposes all we need to know is that we’ll be using the standard HTTP keywords to Post (Create), Get (Read), Put (Update) and Delete (Delete).

Starting Data

To have data to work with, I downloaded the Car Information Dataset from Kagel (Please read their licensing agreement before using this data elsewhere). I modified the CSV file to add an id column and an is_deleted column.

I then imported this data into a table, following the directions in this excellent tutorial. Finally, I dropped the id column and added it back as the identity column.

alter table car
add car_id_new int identity(1,1)
go

alter table car drop column id
go

exec sp_rename 'car_id_new', 'id'
go

At this point, I have a table with all the columns from the imported data, as well as an identity column.

Go to your car class (that we created in part 3) and modify it as follows (to match the incoming data):

public class Car
{
    public int id { get; set; }
    public string name { get; set; } = null!;
    public string mpg { get; set; } = null!;
    public string cylinders { get; set; } = null!;
    public string displacement { get; set; } = null!;
    public string horsepower { get; set; } = null!;
    public string weight { get; set; } = null!;
    public string acceleration { get; set; } = null!;
    public string model_year { get; set; } = null!;
    public string origin { get; set; } = null!;
    public string? is_deleted { get; set;}
}

Note that for now we are keeping things very simple. We will not declare DTOs, and so we will not deal with mapping. We’ll save that for a later blog post.

Creating Our First API

We are ready to create our first API. Its job will be to get all the cars in the database. We’ll do this by creating the API in a controller class and then invoking a method in our Car repository.

Create a Controllers folder, if you have not already, and in that folder create a CarController class. Add the following code to the top of the class:

    public class CarController : ControllerBase
    {
        private readonly ILogger<CarController> _logger;
        readonly CarRepository carRepository;

        public CarController(ILogger<CarController> logger,
            CarRepository carRepository)
        {
            _logger = logger;
            this.carRepository = carRepository;
        }

ControllerBase and ILogger are provided by Microsoft (thanks Satya!). Now, let’s create our API, which is a method decorated with the [HttpGet] attribute

 

Deceptively simple. This method returns a list of Car objects by calling GetAll on the carRepository. Let’s go look at that method:

(If you don’t already have a folder Repositories, please create one and add the class CarRepository). Here’s the top of the class:

You will need a using statement for Dapper.

We are now ready to implement the GetAll method:

    

This method will return the list of Car objects that we need, and defaults to not returning deleted records. We begin by creating a SqlBuilder – an object provided by Dapper. We then create our template, ending it with the syntax /**where**/ — this too is for Dapper and allows us to dynamically create our where clause.

You see this in the if statement; we’ll only add the where statement that restricts the results to non-deleted records if the parameter (returnDeletedRecords) is false.

Next we obtain a connection to the DataBase from our databaseConnectionFactory and finally we use that connection to call QueryAsync, identifying the type (Car) and passing in the SQL statement and the parameters to that statement, if any. In this simplified case we do not have any parameters, but we’ll see how to use them in a later blog post.

Testing with Postman

When you run your application Swagger will come up. Minimize that and open Postman, which is much more powerful and easier to work with (especially once we add authorization). Create a folder named Cars (of course, you can actually name it anything you like) and next to that folder click on the three dots that appear when you click on the name of the folder.

Choose Add Request, and rename your new request GetCars. Go to the right hand pane, and make sure the drop down is set to Get. Next to the drop down enter

https://localhost:7025/car

Be sure to substitute the port number (bold) to the one used by Swagger.

That’s all you have to do. Click Send in the upper right hand corner and your API will be called (don’t be afraid to set break points to prove this to yourself) which will call the method in the repository, which will in turn fetch your data from the database and it will all be returned to Postman…

Congratulations! You have your first working API to your back-end data stored in SQL Server!

In this coming blog posts we’ll add the remaining CRUD APIs, examine using services and DTOs and take a look at minimal APIs.


Rodrigo Juarez is a full-stack developer who has specialized in Xamarin in recent years and is now focusing on MAUI. He is also a book author. With over 25 years of experience, Rodrigo has contributed to a diverse array of projects, developing applications for web, desktop, and mobile platforms. Specialized in Microsoft technologies, he has expertise across various sectors, including management, services, insurance, pharmacy, and banking. Rodrigo Juarez can be reached at info@rodrigojuarez.com

Unknown's avatar

About Jesse Liberty

** Note ** Jesse is currently looking for a new position. You can learn more about him at https://jesseliberty.bio Thank you. Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET, is now available wherever you buy your books. Liberty was a Team Lead and Senior Software Engineer for various corporations, a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a 13 year Microsoft MVP.
This entry was posted in API, Essentials. Bookmark the permalink.

658 Responses to .NET APIs Part 4 – Creating the APIs

  1. Hiya very cool web site!! Guy .. Beautiful .. Wonderful .. I will bookmark your website and take the feeds also…I’m happy to seek out a lot of useful info right here within the put up, we want develop extra strategies on this regard, thank you for sharing.

  2. Danatoto's avatar Danatoto says:

    Thank you, I’ve recently been looking for information about this subject for ages and yours is the best I’ve discovered till now. But, what about the bottom line? Are you sure about the source?

  3. Your article helped me a lot, is there any more related content? Thanks!

  4. sexvnvip.lat's avatar sexvnvip.lat says:

    Together with the whole thing that seems to be developing within this particular area, all your points of view are generally very radical. Nonetheless, I appologize, because I do not subscribe to your entire plan, all be it exhilarating none the less. It would seem to us that your remarks are actually not completely rationalized and in reality you are your self not even entirely confident of the assertion. In any case I did enjoy examining it.

  5. nextogel's avatar nextogel says:

    It’s perfect time to make a few plans for the longer term and it’s time to be happy. I’ve read this publish and if I may just I wish to counsel you some attention-grabbing issues or advice. Maybe you could write subsequent articles regarding this article. I desire to learn more things about it!

  6. OnlyFans Accounts With Balance

  7. nextogel's avatar nextogel says:

    An attention-grabbing discussion is value comment. I feel that you need to write extra on this topic, it won’t be a taboo topic however typically individuals are not sufficient to speak on such topics. To the next. Cheers

  8. Zip Sprout's avatar Zip Sprout says:

    Good day! I know this is kinda off topic nevertheless I’d figured I’d ask. Would you be interested in trading links or maybe guest writing a blog article or vice-versa? My blog addresses a lot of the same subjects as yours and I believe we could greatly benefit from each other. If you’re interested feel free to send me an e-mail. I look forward to hearing from you! Terrific blog by the way!

  9. It?s really a great and helpful piece of info. I?m glad that you just shared this helpful info with us. Please stay us up to date like this. Thanks for sharing.

  10. Today, taking into consideration the fast life-style that everyone leads, credit cards get this amazing demand throughout the economy. Persons out of every discipline are using the credit card and people who are not using the credit cards have arranged to apply for even one. Thanks for giving your ideas about credit cards.

  11. lmhdrosbo's avatar lmhdrosbo says:

    Targeting myeloid cell coagulation signaling blocks MAP kinase TGF-beta1 driven fibrotic remodeling in ischemic heart failure. Garlapati, V., Molitor, M., Michna, T., Harms, G. S., Finger, S., Jung, R., Lagrange, J., Efentakis, P., Wild, J., Knorr, M., Karbach, S., Wild, S., Vujacic-Mirski, K., Munzel, T., Daiber, A., Brandt, M., Gori, T., Milting, H., Tenzer, S., Ruf, W. et al. J Clin Invest (2022). ncbi.nlm.nih.gov pubmed 36548062   Der Ausnahmesänger dürfte Vielen ein Begriff sein, sei es durch seine Eigenkomposition, die auf vielen Plattformen zu bewundern sind, wie auch durch sein Gastspiel bei der deutschen Hard Rock Band ‚Mad Max‘. Seine außergewöhnlichen stimmlichen Fähigkeiten garantieren Gänsehautmomente. Die Geschichte dieser Bodega ist ein Paradebeispiel für diejenigen, die sich nicht beirren lassen, konsequent und hartnäckig ihren Weg gehen, die ihren Überzeugungen treu bleiben und dafür den wohlverdienten Erfolg ernten.
    https://prajapath.in/9477/
    Online-Casinos sind immer bestrebt, die das Spiel erlernen möchten. Sie finden den Sportbereich mit allen verfügbaren Sportarten, die Spielern helfen können. Jeden Monat werden Ihre Credits auf 0 zurückgesetzt, ihre Gewinnchancen zu maximieren. Eine ungewöhnliche Art von Hilfe, dass dieses kostenlose Bingogeld den Spielern von einer Website nur einmal gegeben wird. Jokerstar casino de 2025 review er war in der Vergangenheit bei mir zu Hause, dass die Lotterie in all ihrer Pracht ein Glücksspiel ist. Unsere Automatenspiele bieten ein 100% legales, seriöses und verantwortungsvolles Spielerlebnis mit hervorragenden Gewinnmöglichkeiten und Bonusangeboten wie kostenlosen Freispielen. Online Roulette Deutsch Spielen ist eine großartige Möglichkeit, um als neuer Spieler in einem Online Casino durchzustarten. Erlebe den nervenkitzel im casino: glücksspiel in vollen zügen genießen.

  12. I’m usually to running a blog and i actually appreciate your content. The article has really peaks my interest. I am going to bookmark your website and hold checking for brand spanking new information.

  13. slot888's avatar slot888 says:

    เล่นสล็อตฟรี ผู้เล่นมือใหม่หรือแม้แต่เซียนที่อยากทดลองเกมใหม่ สามารถใช้ระบบทดลองเล่นได้ฟรีโดยไม่ต้องสมัครสมาชิก คุณจะได้เรียนรู้ระบบเกม สัญลักษณ์ ฟีเจอร์ต่าง ๆ รวมถึงทดสอบความถี่ของโบนัสว่าคุ้มค่า สล็อตทดลองเล่น pg ล่าสุด

  14. binance's avatar binance says:

    Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  15. you’re actually a good webmaster. The site loading speed is amazing. It kind of feels that you’re doing any distinctive trick. Moreover, The contents are masterpiece. you have done a great job on this matter!

  16. The next time I read a weblog, I hope that it doesnt disappoint me as a lot as this one. I mean, I know it was my option to read, however I really thought youd have something attention-grabbing to say. All I hear is a bunch of whining about something that you possibly can repair in case you werent too busy in search of attention.

  17. One thing I’d really like to say is the fact that car insurance cancellation is a terrifying experience and if you are doing the appropriate things as being a driver you will not get one. A lot of people do obtain notice that they are officially dumped by their own insurance company they have to struggle to get additional insurance after having a cancellation. Affordable auto insurance rates are usually hard to get from a cancellation. Knowing the main reasons regarding auto insurance cancellations can help car owners prevent getting rid of in one of the most important privileges available. Thanks for the concepts shared by your blog.

  18. We are a group of volunteers and starting a new scheme in our community. Your website provided us with helpful information to paintings on. You have done a formidable activity and our whole neighborhood might be grateful to you.

  19. hey there and thank you for your information ? I have definitely picked up anything new from right here. I did however expertise some technical issues using this website, as I experienced to reload the web site lots of times previous to I could get it to load correctly. I had been wondering if your web host is OK? Not that I am complaining, but slow loading instances times will very frequently affect your placement in google and could damage your high-quality score if advertising and marketing with Adwords. Anyway I am adding this RSS to my e-mail and can look out for much more of your respective intriguing content. Make sure you update this again very soon..

  20. One more thing I would like to state is that instead of trying to accommodate all your online degree tutorials on days of the week that you finish off work (since most people are fatigued when they get back), try to get most of your instructional classes on the weekends and only a couple of courses for weekdays, even if it means a little time off your weekend. This is really good because on the week-ends, you will be extra rested in addition to concentrated on school work. Thanks a lot for the different points I have figured out from your blog.

  21. Hello.This post was really motivating, particularly since I was looking for thoughts on this matter last week.

  22. Do you have a spam issue on this blog; I also am a blogger, and I was wondering your situation; many of us have developed some nice procedures and we are looking to trade strategies with others, be sure to shoot me an email if interested.

  23. I would like to thank you for the efforts you have put in writing this blog. I am hoping the same high-grade web site post from you in the upcoming also. In fact your creative writing skills has inspired me to get my own website now. Actually the blogging is spreading its wings quickly. Your write up is a good example of it.

  24. Definitely believe that which you said. Your favorite reason seemed to be on the web the simplest thing to be aware of. I say to you, I certainly get annoyed while people think about worries that they just don’t know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side-effects , people could take a signal. Will probably be back to get more. Thanks

  25. visit site's avatar visit site says:

    Fantastic beat ! I wish to apprentice while you amend your site, how could i subscribe for a blog site? The account helped me a acceptable deal. I had been tiny bit acquainted of this your broadcast offered bright clear concept

  26. I just could not depart your web site prior to suggesting that I really enjoyed the standard information a person provide for your visitors? Is gonna be back often to check up on new posts

  27. binance's avatar binance says:

    Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  28. I have observed that over the course of developing a relationship with real estate homeowners, you’ll be able to come to understand that, in every single real estate contract, a payment is paid. Eventually, FSBO sellers never “save” the payment. Rather, they struggle to earn the commission simply by doing a strong agent’s occupation. In doing this, they commit their money and also time to execute, as best they can, the obligations of an real estate agent. Those jobs include exposing the home by way of marketing, presenting the home to buyers, developing a sense of buyer emergency in order to prompt an offer, arranging home inspections, taking on qualification check ups with the loan company, supervising fixes, and facilitating the closing of the deal.

  29. Heya i?m for the primary time here. I came across this board and I to find It truly useful & it helped me out a lot. I hope to give one thing back and aid others such as you helped me.

  30. visit's avatar visit says:

    A different issue is really that video gaming has become one of the all-time biggest forms of fun for people of various age groups. Kids participate in video games, and also adults do, too. The actual XBox 360 is among the favorite games systems for individuals that love to have hundreds of video games available to them, in addition to who like to relax and play live with other people all over the world. Thanks for sharing your thinking.

  31. Greetings! This is my first visit to your blog! We are a collection of volunteers and starting a new initiative in a community in the same niche. Your blog provided us beneficial information to work on. You have done a wonderful job!

  32. Hi! I know this is kind of off topic but I was wondering if you knew where I could find a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one? Thanks a lot!

  33. Jani Scanlon's avatar Jani Scanlon says:

    With havin so much content do you ever run into any issues of plagorism or copyright violation? My blog has a lot of exclusive content I’ve either written myself or outsourced but it appears a lot of it is popping it up all over the web without my permission. Do you know any techniques to help reduce content from being ripped off? I’d certainly appreciate it.

  34. SEO Services's avatar SEO Services says:

    A lot of thanks for your entire hard work on this site. Ellie loves getting into internet research and it’s really obvious why. Most of us learn all about the dynamic form you provide worthwhile guidance on your website and cause participation from visitors on this concern then my simple princess is certainly discovering a lot of things. Enjoy the rest of the year. You’re conducting a useful job.

  35. What i do not realize is if truth be told how you’re no longer really much more neatly-favored than you may be right now. You are so intelligent. You know thus considerably in relation to this topic, produced me personally imagine it from a lot of various angles. Its like men and women don’t seem to be fascinated until it?s something to do with Woman gaga! Your individual stuffs great. All the time care for it up!

  36. 100 USDT's avatar 100 USDT says:

    I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

Leave a Reply

Your email address will not be published. Required fields are marked *