Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Using Web API to Extend Your Application

Save for later
  • 14 min read
  • 08 Sep 2016

article-image

In this article by Shahed Chowdhuri author of book ASP.Net Core Essentials, we will work through a working sample of a web API project. During this lesson, we will cover the following:

  • Web API
  • Web API configuration
  • Web API routes
  • Consuming Web API applications

(For more resources related to this topic, see here.)

Understanding a web API

Building web applications can be a rewarding experience. The satisfaction of reaching a broad set of potential users can trump the frustrating nights spent fine-tuning an application and fixing bugs. But some mobile users demand a more streamlined experience that only a native mobile app can provide.

Mobile browsers may experience performance issues in low-bandwidth situations, where HTML5 applications can only go so far with a heavy server-side back-end. Enter web API, with its RESTful endpoints, built with mobile-friendly server-side code.

The case for web APIs

In order to create a piece of software, years of wisdom tell us that we should build software with users in mind. Without use cases, its features are literally useless. By designing features around user stories, it makes sense to reveal public endpoints that relate directly to user actions. As a result, you will end up with a leaner web application that works for more users.

If you need more convincing, here's a recap of features and benefits:

  • It lets you build modern lightweight web services, which are a great choice for your application, as long as you don't need SOAP
  • It's easier to work with than any past work you may have done with ASP.NET Windows Communication Foundation (WCF) services
  • It supports RESTful endpoints
  • It's great for a variety of clients, both mobile and web
  • It's unified with ASP.NET MVC and can be included with/without your web application

Creating a new web API project from scratch

Let's build a sample web application named Patient Records. In this application, we will create a web API from scratch to allow the following tasks:

  • Add a new patient
  • Edit an existing patient
  • Delete an existing patient
  • View a specific patient or a list of patients

These four actions make up the so-called CRUD operations of our system: to Create, Read, Update or Delete patient records.

Following the steps below, we will create a new project in Visual Studio 2015:

  1. Create a new web API project.
  2. Add an API controller.
  3. Add methods for CRUD operations.

The preceding steps have been expanded into detailed instructions with the following screenshots:

  1. In Visual Studio 2015, click File | New | Project. You can also press Ctrl+Shift+N on your keyboard.

    using-web-api-extend-your-application-img-0

  2. On the left panel, locate the Web node below Visual C#, then select ASP.NET Core Web Application (.NET Core), as shown in the following screenshot:

    using-web-api-extend-your-application-img-1

  3. With this project template selected, type in a name for your project, for examplePatientRecordsApi, and choose a location on your computer, as shown in the following screenshot:

    using-web-api-extend-your-application-img-2

  4. Optionally, you may select the checkboxes on the lower right to create a directory for your solution file and/or add your new project to source control. Click OK to proceed.

  5. In the dialog that follows, select Empty from the list of the ASP.NET Core Templates, then click OK, as shown in the following screenshot:

    using-web-api-extend-your-application-img-3

  6. Optionally, you can check the checkbox for Microsoft Azure to host your project in the cloud. Click OK to proceed.

Building your web API project

In the Solution Explorer, you may observe that your References are being restored. This occurs every time you create a new project or add new references to your project that have to be restored through NuGet,as shown in the following screenshot:

using-web-api-extend-your-application-img-4

Follow these steps, to fix your references, and build your Web API project:

  1. Rightclickon your project, and click Add | New Folder to add a new folder, as shown in the following screenshot:

    using-web-api-extend-your-application-img-5

  2. Perform the preceding step three times to create new folders for your Controllers, Models, and Views,as shown in the following screenshot:

    using-web-api-extend-your-application-img-6

  3. Rightclick on your Controllers folder, then click Add | New Item to create a new API controller for patient records on your system, as shown in the following screenshot:

    using-web-api-extend-your-application-img-7

  4. In the dialog box that appears, choose Web API Controller Class from the list of options under .NET Core, as shown in the following screenshot:

    using-web-api-extend-your-application-img-8

  5. Name your new API controller, for examplePatientController.cs, then click Add to proceed.

  6. In your new PatientController, you will most likely have several areas highlighted with red squiggly lines due to a lack of necessary dependencies, as shown in the following screenshot. As a result, you won't be able to build your project/solution at this time:

    using-web-api-extend-your-application-img-9

In the next section, we will learn about how to configure your web API so that it has the proper references and dependencies in its configuration files.

Configuring the web API in your web application

How does the web server know what to send to the browser when a specific URL is requested? The answer lies in the configuration of your web API project.

Setting up dependencies

In this section, we will learn how to set up your dependencies automatically using the IDE, or manually by editing your project's configuration file.

  1. To pull in the necessary dependencies, you may right-click on the using statement for Microsoft.AspNet.Mvc and select Quick Actions and Refactorings…. This can also be triggered by pressing Ctrl +. (period) on your keyboard or simply by hovering over the underlined term, as shown in the following screenshot:

    using-web-api-extend-your-application-img-10

  2. Visual Studio should offer you several possible options, fromwhich you can select the one that adds the package Microsoft.AspNetCore.Mvc.Corefor the namespace Microsoft.AspNetCore.Mvc. For the Controller class, add a reference for the Microsoft.AspNetCore.Mvc.ViewFeaturespackage, as shown in the following screenshot:

    using-web-api-extend-your-application-img-11Fig12: Adding the Microsoft.AspNetCore.Mvc.Core 1.0.0 package

  3. If you select the latest version that's available, this should update your references and remove the red squiggly lines, as shown in the following screenshot:

    using-web-api-extend-your-application-img-12Fig13:Updating your references and removing the red squiggly lines

  4. The precedingstep should automatically update your project.json file with the correct dependencies for theMicrosoft.AspNetCore.Mvc.Core, and
    Microsoft.AspNetCore.Mvc.ViewFeatures, as shown in the following screenshot:

    using-web-api-extend-your-application-img-13

  5. The "frameworks" section of theproject.json file identifies the type and version of the .NET Framework that your web app is using, for examplenetcoreapp1.0 for the 1.0 version of .NET Core. You will see something similar in your project, as shown in the following screenshot:

    using-web-api-extend-your-application-img-14

    Unlock access to the largest independent learning library in Tech for FREE!
    Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
    Renews at £16.99/month. Cancel anytime
  6. Click the Build Solution button from the top menu/toolbar. Depending on how you have your shortcuts set up, you may press Ctrl+Shift+B or press F6 on your keyboard to build the solution. You should now be able to build your project/solution without errors, as shown in the following screenshot:

    using-web-api-extend-your-application-img-15

Before running the web API project, open the Startup.cs class file, and replace the app.Run() statement/block (along with its contents) with a call to app.UseMvc()in the Configure() method. To add the Mvc to the project, add a call to the services.AddMvcCore() in the ConfigureServices() method. To allow this code to compile, add a reference to Microsoft.AspNetCore.Mvc.

Parts of a web API project

Let's take a closer look at the PatientController class. The auto-generated class has the following methods:

  • public IEnumerable<string> Get()
  • public string Get(int id)
  • public void Post([FromBody]string value)
  • public void Put(int id, [FromBody]string value)
  • public void Delete(int id)

The Get() method simply returns a JSON object as an enumerable string of values, while the Get(int id) method is an overridden variant that gets a particular value for a specified ID.

The Post() and Put() methods can be used for creating and updating entities. Note that the Put() method takes in an ID value as the first parameter so that it knows which entity to update.

Finally, we have the Delete() method, which can be used to delete an entity using the specified ID.

Running the web API project

You may run the web API project in a web browser that can display JSON data.

If you use Google Chrome, I would suggest using the JSONView Extension (or other similar extension) to properly display JSON data.

The aforementioned extension is also available on GitHub at the following URL:

https://github.com/gildas-lormeau/JSONView-for-Chrome

If you use Microsoft Edge, you can view the raw JSON data directly in the browser.Once your browser is ready, you can select your browser of choice from the top toolbar of Visual Studio. Click on the tiny triangle icon next to the Debug button, then select a browser, as shown in the following screenshot:

using-web-api-extend-your-application-img-16

In the preceding screenshot, you can see that multiple installed browsers are available, including Firefox, Google Chrome, Internet Explorer,and Edge. To choose a different browser, simply click on Browse With…, in the menu to select a different one.

Now, click the Debug button (that isthe green play button) to see the web API project in action in your web browser, as shown in the following screenshot. If you don't have a web application set up, you won't be able to browse the site from the root URL:

using-web-api-extend-your-application-img-17

Don’t worry if you see this error, you can update the URL to include a path to your API controller, for an example seehttp://localhost:12345/api/Patient.

Note that your port number may vary. Now, you should be able to see a list of views that are being spat out by your API controller, as shown in the following screenshot:

using-web-api-extend-your-application-img-18

Adding routes to handle anticipated URL paths

Back in the days of classic ASP, application URL paths typically reflected physical file paths. This continued with ASP.NET web forms, even though the concept of custom URL routing was introduced. With ASP.NET MVC, routes were designed to cater to functionality rather than physical paths.

ASP.NET web API continues this newer tradition, with the ability to set up custom routes from within your code. You can create routes for your application using fluent configuration in your startup code or with declarative attributes surrounded by square brackets.

Understanding routes

To understand the purpose of having routes, let's focus on the features and benefits of routes in your application. This applies to both ASP.NET MVC and ASP.NET web API:

  • By defining routes, you can introduce predictable patterns for URL access
  • This gives you more control over how URLs are mapped to your controllers
  • Human-readable route paths are also SEO-friendly, which is great for Search Engine Optimization
  • It provides some level of obscurity when it comes to revealing the underlying web technology and physical file names in your system

Setting up routes

Let's start with this simple class-level attribute that specifies a route for your API controller, as follows:

[Route("api/[controller]")]

public class PatientController : Controller

{

// ...

}

Here, we can dissect the attribute (seen in square brackets, used to affect the class below it) and its parameter to understand what's going on:

  • The Route attribute indicates that we are going to define a route for this controller.
  • Within the parentheses that follow, the route path is defined in double quotes.
  • The first part of this path is thestring literal api/, which declares that the path to an API method call will begin with the term api followed by a forward slash.
  • The rest of the path is the word controller in square brackets, which refers to the controller name. By convention, the controller's name is part of the controller's class name that precedes the term Controller. For a class PatientController, the controller name is just the word Patient.
  • This means that all API methods for this controller can be accessed using the following syntax, where MyApplicationServer should be replaced with your own server or domain name:http://MyApplicationServer/api/Patient

For method calls, you can define a route with or without parameters. The following two examples illustrate both types of route definitions:

[HttpGet]

public IEnumerable<string> Get()

{

    return new string[] { "value1", "value2" };

}

In this example, the Get() method performs an action related to the HTTP verb HttpGet, which is declared in the attribute directly above the method. This identifies the default method for accessing the controller through a browser without any parameters, which means that this API method can be accessed using the following syntax:

http://MyApplicationServer/api/Patient

To include parameters, we can use the following syntax:

[HttpGet("{id}")]

public string Get(int id)

{

    return "value";

}

Here, the HttpGet attribute is coupled with an "{id}" parameter, enclosed in curly braces within double quotes. The overridden version of the Get() method also includes an integer value named id to correspond with the expected parameter.

If no parameter is specified, the value of id is equal to default(int) which is zero. This can be called without any parameters with the following syntax:

http://MyApplicationServer/api/Patient/Get

In order to pass parameters, you can add any integer value right after the controller name, with the following syntax:

http://MyApplicationServer/api/Patient/1

This will assign the number 1 to the integer variable id.

Testing routes

To test the aforementioned routes, simply run the application from Visual Studio and access the specified URLs without parameters.

using-web-api-extend-your-application-img-19

The preceding screenshot show the results of accessing the following path:

http://MyApplicationServer/api/Patient/1

Consuming a web API from a client application

If a web API exposes public endpoints, but there is no client application there to consume it, does it really exist? Without getting too philosophical, let's go over the possible ways you can consume a client application.

You can do any of the following:

  • Consume the Web API using external tools
  • Consume the Web API with a mobile app
  • Consume the Web API with a web client

Testing with external tools

If you don't have a client application set up, you can use an external tool such as Fiddler. Fiddler is a free tool that is now available from Telerik, available at http://www.telerik.com/download/fiddler, as shown in the following screenshot:

using-web-api-extend-your-application-img-20

You can use Fiddler to inspect URLs that are being retrieved and submitted on your machine. You can also use it to trigger any URL, and change the request type (Get, Post, and others).

Consuming a web API from a mobile app

Since this article is primarily about the ASP.NET core web API, we won't go into detail about mobile application development. However, it's important to note that a web API can provide a backend for your mobile app projects.

Mobile apps may include Windows Mobile apps, iOS apps, Android apps, and any modern app that you can build for today's smartphones and tablets. You may consult the documentation for your particular platform of choice, to determine what is needed to call a RESTful API.

Consuming a web API from a web client

A web client, in this case, refers to any HTML/JavaScript application that has the ability to call a RESTful API. At the least, you can build a complete client-side solution with straight JavaScript to perform the necessary actions. For a better experience, you may use jQuery and also one of many popular JavaScript frameworks.

A web client can also be a part of a larger ASP.NET MVC application or a Single-Page Application (SPA). As long as your application is spitting out JavaScript that is contained in HTML pages, you can build a frontend that works with your backend web API.

Summary

In this article, we've taken a look at the basic structure of an ASP.NET web API project, and observed the unification of web API with MVC in an ASP.NET core. We also learned how to use a web API as our backend to provide support for various frontend applications.

Resources for Article:

 


Further resources on this subject: