7 min read

REST is an architectural style for implementing communication between the application client and server over HTTP. RESTful APIs use HTTP verbs (POSTGET, PUT, DELETE, and so on) to dictate the operation to be performed (Create, Read, Update, Delete) by the server on the domain entity. The REST style has become the de facto standard for creating services in modern application development. This makes it easy to use and consume services in any technology and on any platform, such as web frontends, desktop applications, or other web services.

This article is an excerpt from a book written by Tamir Dresher, Amir Zuker, and Shay Friedman titled Hands-On Full-Stack Web Development with ASP.NET Core. In this book, you will learn how to build RESTful APIs in C# with ASP.NET Core, web APIs, and Entity Framework.

Overview — REST APIs with ASP.NET Core API

A basic ASP.NET Core MVC application can be broken down into three layers: models, controllers, and views. RESTful APIs in ASP.NET Core work very similarly; the only difference is that, instead of returning responses as visual views, the API response is a payload of data (usually in JSON format). The data returned from the API is later consumed by clients, such as Angular-based applications that can render the data as views, or by headless clients that have no UI and simply process data. For example, consider a background process that periodically sends notifications to a user about their account status:

Before ASP.NET Core, Microsoft created an explicit distinction between ASP.NET MVC and the ASP.NET Web API. The former was used to create web applications with views that are generated by the server, while the former was used to create services that contain only logic and can be consumed by any client. Over time, the distinction between the two frameworks caused duplication of code and added a burden on the developers who needed to learn and master two technologies. ASP.NET Core unified the two frameworks into the ASP.NET Core MVC suite, and made it simpler to create web applications, with or without visual responses.

Let’s start with a simple API that will be the foundation for our application called, say, GiveNTake application.

Creating a simple API

The GiveNTake application allows the user to see a catalog of available products. For this to be possible, our server needs to include a specific API method that the client application can call and get back the collection of available products.

We will treat the product as a simple string in the format of [Product ID] - [Product Name]:

  1. Open the any basic project you may have created, and add a new controller class to the Controllers folder.  Right-click on the newly created Controllers folder and choose Add | Controller.
  2. In the list of available templates, choose API Controller – Empty and click Add:

  1. Set the name to ProductsController and click Add.
  2. Add the following method to the generated controller:
public string[] GetProducts()
{
    return new[]
    {
        "1 - Microwave",
        "2 - Washing Machine",
        "3 - Mirror"
    };
}
  1. Your controller should look like this:
[Route("api/Products")]
[ApiController]
public class ProductsController : Controller
{
    public string[] GetProducts()
    {
        return new[]
        {
            "1 - Microwave",
            "2 - Washing Machine",
            "3 - Mirror"
        };
    }
}

Congratulations! You have completed coding your first API method. The GetProducts method returns the collection of the available products.

To see it in action, build and run your project. This will open a browser with the base address of your ASP.NET application. Add the  /api/Products string to the base address in the browser’s address bar and execute it. You should see the collection of strings appear on the screen like so:

Inspecting your APIs using Fiddler and Postman

Using your browser to execute your APIs is nice enough for simple APIs that retrieve data, but as you go along and extend your APIs, you’ll soon find that you need other powerful tools to test and debug what you develop. There are many tools that let you inspect and debug your APIs, but I have chosen to teach you about Fiddler and Postman because they are both simple and powerful.

Fiddler

Fiddler is a free web debugging tool that works as a proxy, logging all HTTP(S) traffic that is executed by processes in your computer. Fiddler allows you to inspect the traffic to see that exact HTTP request that was sent and the exact HTTP response that was returned. You can also use other advanced features, such as setting breakpoints and overriding the data that is sent or received.

To install Fiddler, navigate to https://www.telerik.com/fiddler and click the Free download button. Save and run the installer:

The Fiddler main screen is built from these main parts:

  • Sessions list: Shows the HTTP(S) requests that were sent from processes in your machine
  • Fiddler tabs: Contains different tools for inspecting and controlling sessions
  • Request inspector: When the Inspectors tab and inner Raw tab are selected, this section shows the request as it was sent over-the-wire
  • Response inspector: When the Inspectors tab and inner Raw tab are selected, this section shows the response as it was sent over-the-wire

Immediately after you run Fiddler, it starts collecting the HTTP sessions that are performed in your machine. If you refresh the browser that you used to navigate to the /api/Products API  you created, you should see this session in Fiddler’s Sessions List, as shown in the preceding screenshot.

If you run a .NET application that sends HTTP requests to an address in your localhost, you won’t see the session appear in Fiddler. Changing the address to localhost.fiddler will force the request to be captured by Fiddler.

Fiddler is a great tool for debugging the requests and responses that are made in your application, but it means that you need to have a client that sends those requests. Many times when debugging and experimenting with APIs, you want to create HTTP requests manually and inspect them. You can accomplish this task with Fiddler’s Composer tab, but I want to teach you about another tool that is much more suitable for these scenarios—Postman.

Postman

Postman is an HTTP client that simplifies the testing of web services and RESTful APIs. Postman allows you to easily construct HTTP requests, send them, and inspect them.

Download Postman from https://www.getpostman.com/, and then install and run it:

  1. On the introduction screen, click on the Request option:

  1. Enter GetProducts in the Request name field, and then type GiveNTake into the collection section and create a new collection. Press Save to create the new request:

  1. Enter the full URL of the GetProducts API (for example, http://localhost:5267/api/products) in the URL field:

  1. Make sure that the HTTP Verb is set to GET and click on the Send button.
  2. After a few moments, you should see the response that was received from your service, and you can now inspect the status code, response body, and headers:

You will find Postman to be an indispensable development tool while you develop your APIs, and we will use it many times as we go deeper into ASP.NET Core in this book.

At this point, you might be wondering, how come the GetProducts method was invoked when we navigated to /api/Products? To answer this question, we need to talk about how ASP.NET Core routes requests into controllers and actions.

ASP.NET Core provides the necessary infrastructure you need to create powerful RESTful APIs.

In this article, you learned how to create controllers and actions that respond to HTTP requests, and return HTTP responses that you control. We’ve introduced two popular tools: Fiddler and Postman, and you’ll find them very useful when you create and debug your API applications. To know more about APIs in ASP.NET Core, check out the book Hands-On Full-Stack Web Development with ASP.NET Core.

Read next

Google announces the general availability of a new API for Google Docs

What to expect in ASP.NET Core 3.0

How to call an Azure function from an ASP.NET Core MVC application

Data science enthusiast. Cycling, music, food, movies. Likes FPS and strategy games.