Tech Junkie Blog - Real World Tutorials, Happy Coding!: Hour 18 Asp.Net Core: Create A Web API For NorthwindCafe With Postman

Tuesday, September 17, 2019

Hour 18 Asp.Net Core: Create A Web API For NorthwindCafe With Postman

In the last few posts we have been working with our models and retrieving the data natively in the application, but most of the project you will work with in real life will probably have you call some kind of api with an endpoint.  In this post we are going to substitute the products call what we made with an api.

Here are steps to create our first Api:

1. First we want to set up our application to use postman to test out our api. To do that right-click on the project and click on "Properties", in Properties screen click on "Debug" and uncheck "Launch browser" and make a note of the port number of the App URL.  We will make the api calls with postman initially to make sure that our api works.  Postman has become pretty popular with api development because it allows us to make api calls and see the results.  You can get postman here

https://www.getpostman.com/downloads/ I would get the desktop version because it's more robust.





















2. Now we are ready to create a ProductController to be our api controller, Asp.NET Core has the api control built-in so we don't have to do anything special for a controller to be a web api controller. So create a file call ProductController in the Controllers folder.  The ProductController should have the following code

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NorthwindCafe.Web.Data;
using System;

namespace NorthwindCafe.Web.Controllers
{
    [Route("api/[Controller]")]
    public class ProductController : Controller
    {
        private readonly  IProductRepository _repository;
        private readonly  ILogger _logger;

        public ProductController(IProductRepository repository, ILogger logger)
        {
            _repository = repository;
            _logger = logger;
        }

        [HttpGet]
        public IActionResult Get()
        {
            try
            {
                return Ok(_repository.GetProducts());
            }
            catch (Exception ex)
            {
                _logger.LogError($"Get products failed {ex}");
                return BadRequest("Get products failed");
            }
        }
    }
}

The code above is pretty straightforward.  You have the define private variables _repository and _logger for the repository to hold the injected objects in the constructor. Then you define a method call Get with the decorator [HttpGet] to handle get requests.  The Get() method returns the list of products and retruns Ok = 200 status code if everything is ok and returns a 400 error status code if there's an exception.  The other important thing is the [Route("api/[Controller]")] decorator.  This is what you typed into the browser.  So for this route you would type http://localhost:50051/api/product into Postman.

3. So now we are ready to test our code in Postman, first we need to run our code, press CRTL+F5
Then select "GET" method on Postman call, type in the URL localhost:50051/api/product and you will see the list of products returned in Json, usually the resource in this product should be pluralize, but I forgot the s.  So the URLs should be localhost:<port>/api/products but since it's just development we can let it slide.  However, if you work with other people you might want to pluralize it.


21 comments:

  1. It is safe to say that you are looking for the Largest Android Tablet in 2020? The correct method to buy tablets is through the online sites. There are various sites that include enormous measure of biggest screen tablets.

    ReplyDelete
  2. Next time I read a blog, Hopefully it does not fail me just as much as this one. After all, I know it was my choice to read, however I actually believed you would probably have something useful to talk about. All I hear is a bunch of complaining about something you could possibly fix if you weren't too busy searching for attention.disinfecting san antonio

    ReplyDelete
  3. Nice post. I learn something new and challenging on sites I stumbleupon on a daily basis. It will always be exciting to read through articles from other writers and use something from their web sites.
    cryptocurrency

    ReplyDelete
  4. I must thank you for the efforts you've put in penning this blog. I am hoping to check out the same high-grade content from you in the future as well. In fact, your creative writing abilities has motivated me to get my own website now ;)
    I'm more than happy to find this page. I wanted to thank you for your time for this wonderful read!! I definitely enjoyed every bit of it and I have you bookmarked to check out new things in your web site.
    Gran Canaria gay clubs

    ReplyDelete
  5. Hi there! This blog post could not be written much better! Going through this post reminds me of my previous roommate! He constantly kept preaching about this. I am going to forward this article to him. Fairly certain he's going to have a great read. Thanks for sharing!
    Shingles

    ReplyDelete
  6. ISO 17100 zertifiziert, Fachübersetzungen inkl. Lektorat. Erfahrung und Präzision. High Qualität, Übersetzungsagentur: Fachübersetzungen für Übersetzungsbüra für Banken und Versicherungen Dortmund-Essen-Duisburg, Lokalisierung,
    Übersetzung mit Beglaubigung und Apostille, Fachübersetzung für Bundesanzeiger, Dolmetscher, juristische und technische Übersetzung, Banken+Versicherung

    ReplyDelete
  7. Eco living life team is passionate about making it easier for you to shop online. We care about your time so we try our best to make your shopping experience pleasant, seamless and hassle-free.

    ReplyDelete
  8. Aw, this was a very nice post. Taking the time and actual effort to produce a superb article… but what can I say… I procrastinate a whole lot and never manage to get anything done.

    At BrokeScholar we work around the clock to update this page with active promo codes, coupons and discounts for Total Wine . Our editors monitor newsletters, social media posts, deal forums, and third party sellers to find the best Total Wine deals. For students, we also track totalwine student discounts for exclusive savings. We've done the research so you don't have to. Bookmark this page and never miss a Total Wine promotion again.

    ReplyDelete
  9. Stretch your dollar even further at harbor freight coupons with our 25% off coupons. These coupons will help you save 20% (or more!) on qualifying items throughout the store. We also have discounts just for members of our Inside Track Club.

    ReplyDelete
  10. This online journal site is really cool! How was it made !

    Kilts for Sale

    ReplyDelete
  11. i was simply perusing along and happened upon your online journal. simply needed to say great website and this article truly helped me.

    Smart Automation Solutions

    ReplyDelete
  12. Thankyou for this wondrous post, I am happy I watched this site on hurray.
    Graphic designing services in Lahore

    ReplyDelete
  13. Professionelles Übersetzungsbüro ✓ Übersetzungen ✓ Dolmetschen ✓ mehr als 35 Jahre Erfahrung ✓ alle Sprachen ✓ Qualitätsstandard ISO 17100 ✓ Rechtssichere Übersetzung ✓ Juristische Fachübersetzung ✓ Übersetzungsbüro ✓ Übersetzungsdienst ✓Übersetzungsagentur ✓Übersetzungsservice ✓ Übersetzungen ✓ beglaubigte ✓ Übersetzung, Übersetzen ✓individuelle Beratung.✓✓ Alle Sprachen. Alle Fachrichtungen,✓ 35 Jahre Erfahrung ✓ Express Übersetzungsbüro ✓ juristische und technische Übersetzung ✓ Profi Fachübersetzungen ✓ Deutsch Englisch
    Visit our site: profischnell.com

    ReplyDelete
  14. On this website, You’ll get over 200+ real working dark web links and If you’re a regular dark web user so you can start using these dark web links and If you’re a new user or If you don’t know anything about the dark web So you can read the content below and you’ll understand everything about the dark web.
    https://darkweb.link/

    ReplyDelete
  15. Really decent post. I just unearthed your weblog and needed to say that I have truly delighted in scanning your blog entries. After all I'll be subscribing to your food and I trust you compose again soon!
    What Are the Best Hair Straighteners Available Today?

    ReplyDelete
  16. I was more than happy to uncover this great site. I need to thank you for your time due to this fantastic read!!
    I definitely enjoyed every bit of it and I have you bookmarked to see new information on your blog.
    Classified Ads WordPress Theme

    ReplyDelete
  17. ΣΚΑΛΑ ΣΤΟ ΜΠΕΤΟ

    Η Nova Tecnica δραστηριοποιείται 20 και πλέον χρόνια στο χώρο των συστημάτων συνδεσμολογίας ξύλου με τα συστήματα σύνδεσης της ΚΝΑΡΡ ® προσφέροντας πρωτοποριακές λύσεις για τις δικές σας δημιουργικές εμπνεύσεις. Η παλέτα των προϊόντων μας περιλαμβάνει μη ορατά, αποσυναρμολογούμενα καθώς και αυτοτανυόμενα εξαρτήματα σύνδεσης για ευρύτατο φάσμα εφαρμογών, από τη επιπλοποιία και την κατασκευή υαλοστασίων και προσόψεων έως και την ξύλινη δόμηση.

    ReplyDelete
  18. digital marketing agency london
    Moving on to the best and most suitable campaign(s) for your business after spotting your position in the market along with your competitors. Creation of strategies as well as optimization process setup is an essential part of this phase including targets which could be ROAS, ROI or CPA.

    ReplyDelete
  19. Hi I am so pleased I found your online journal, I truly found you by misstep, while I was watching on google for something else, Anyways I am here now and could simply get a kick out of the chance to say thank for a colossal post and an inside and out stimulating site. Kindly do keep up the immense work.

    freetress suzie

    ReplyDelete
  20. This software typeform wordpress application enables you to check out all the form entries in one area. Better, you can respond as well as inspect messages to leads quickly by utilizing this software application. Kinds produced utilizing Form can be made use of for list building, membership and even you can utilize it for repayments, as well as items offering.

    ReplyDelete

Search This Blog