Deborah's Developer MindScape

         Tips and Techniques for Web and .NET developers.

September 23, 2012

The World’s Simplest Web API/POCO Example

Filed under: ASP.NET,ASP.NET Web API,C#,VB.NET @ 6:28 pm

This post demonstrates how to use the ASP.NET Web API to access plain old custom objects (POCO) and build a service for a line of business application. No Entity Framework (EF).

The Web API is a new easy-to-use framework that allows you to build a service that can send or receive data over HTTP to a range of clients. If this sounds something like Windows Communication Foundation (WCF), you are right. But this new framework is MUCH easier to use and provides content that is much easier to consume by client applications.

A Web API service can provide content to .NET clients, but also JavaScript clients and clients written in other languages such as Ruby or Python. It provides that content in different formats such as XML or JSON (JavaScript Object Notation).

The example in this post is as absolutely simple as possible to help you get up and running with these technologies. To meet this goal, this first post covers how to build a service that only provides data. Later posts will cover building clients to get the data, and updating the service for insert and update operations.

So first, the prerequisites:

Since Visual Studio 2012 is now officially released, the screen shots in this post are all of the Visual Studio 2012 tools.

STEP 1: Create the Web API project.

1) In Visual Studio, select File | New | Project

2) Select the ASP.NET MVC 4 Web Application under the Visual Basic or Visual C# templates and click OK.


3) Select Web API as the project template and click OK.


Visual Studio creates all of the files you need to get started with your Web API service.


The resulting code is complete enough to execute. If you run the application at this point (F5) it appears as follows:


To see the data provided by the default service, add "api/values" to the end of the string in the address bar. The result is something like: http://localhost:2152/api/values. You will then be asked to open or save the data returned by the service. Select to Open and if asked, select to open with Notepad. The result is:


So the default pre-built service returns two values in JSON format called "value1" and "value2". Yes, well it is a start.

The key parts of code required for a Web API service are the Models and the Controllers.

The Models provide the content for your service. They define which data or other content that your service will expose to client applications. For example, for the Acme Customer Management application, the models could include Customer, Purchase, and Invoice. These would expose basic customer information, customer purchasing information, and customer invoice information.

No models are created for you in this case. They are created manually as defined in the next step.

The Controllers basically control your service. They define the actions that your service accepts and performs the response appropriate for the requested action. For example the Acme Customer Management application would provide a Get action that would return the list of all of the customers and a Get action with a key that would provide information for a specific customer.

Two controllers are created in the generated code. The HomeController is a MVC controller which controls the generated sample user interface. The ValueController is the sample Web API controller that provided the two values shown in the screen shot above. You can delete it.

STEP 2: Add your Model

The service is this example provides customer information. That information is defined in the model with a Customer class.

1) Right-click on the Models folder in Solution Explorer and select Add | Class.

2) Add the code for a Customer class.

In C#:

using System.Collections.Generic;

namespace ACMService.Models
    public class Customer
        public int CustomerId { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string EmailAddress { get; set; }

        /// <summary>
        /// Retrieves a list of customers.
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// In a "real" application, this code would
        /// call a data access component that retrieves
        /// the data from a database.
        /// </remarks>
        public static List<Customer> Retrieve()
            List<Customer> custList = new List<Customer>
                    {new Customer()
                          { CustomerId = 1,
                            LastName = "Baggins",
                            EmailAddress = ""},
                    new Customer()
                          { CustomerId = 2,
                            LastName = "Baggins",
                            EmailAddress = ""},
                    new Customer()
                          { CustomerId = 3,
                            LastName = "Gamgee",
                            EmailAddress = ""},
                    new Customer()
                          { CustomerId = 4,
                            LastName = "Cotton",
                            EmailAddress = ""}};
            return custList;

In VB:

”’ <summary>
”’ Manages a customer
”’ </summary>
”’ <remarks></remarks>
”’ <editHistory></editHistory>
Public Class CustomerVB
    Public Property CustomerId As Integer
    Public Property FirstName() As String
    Public Property LastName() As String
    Public Property EmailAddress() As String

    ”’ <summary>
    ”’ Retrieves a list of customers.
    ”’ </summary>
    ”’ <returns></returns>
    ”’ <remarks>
    ”’ In a "real" application, this code would
    ”’ call a data access component that retrieves
    ”’ the data from a database.
    ”’ </remarks>
    Public Shared Function Retrieve() As List(Of CustomerVB)
        Dim custList As New List(Of CustomerVB) From
                    {New CustomerVB() With
                          {.CustomerId = 1,
                            .FirstName = "Bilbo",
                            .LastName = "Baggins",
                            .EmailAddress = ""},
                    New CustomerVB() With
                          {.CustomerId = 2,
                            .FirstName = "Frodo",
                            .LastName = "Baggins",
                            .EmailAddress = ""},
                    New CustomerVB() With
                          {.CustomerId = 3,
                            .FirstName = "Samwise",
                            .LastName = "Gamgee",
                            .EmailAddress = ""},
                    New CustomerVB() With
                          {.CustomerId = 4,
                            .FirstName = "Rosie",
                            .LastName = "Cotton",
                            .EmailAddress = ""}}
        Return custList
    End Function
End Class

NOTE: This code does not use a data access layer at this time. To keep this example as simple as possible, the Retrieve method "mocks" a retrieve that would call your data access component and retrieve the data from the database. This code will be replaced in a later post to actually access a database.

NOTE: Normally I build a Customer class (singular) with the properties and methods that mange a singe customer and a Customers class (plural) that works with a list of those customers. The functionality for both were added to one class to keep this example as simple as possible.

Step 3: Add your Controller

The controller in this example provides two operations: one to get all customers, and one to get one customer by Id.

1) Right-click on the Controllers folder in Solution Explorer and select Add | Controller.

2) Select Empty API Controller

Visual Studio provides several scaffolding options, which define the type of code that it will automatically generate in the controller. To keep this example simple, it will only provide read actions, so select  Empty API Controller.


3) Write the code for the controller.

In C#:

using ACMService.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace ACMService.Controllers
    public class CustomerController : ApiController
        // GET api/customer
        public IEnumerable<Customer> Get()
            return Customer.Retrieve();

        // GET api/customer/2
        public Customer Get(int id)
            List<Customer> customerList = Customer.Retrieve();
            Customer customerInstance = customerList.FirstOrDefault(
                                c => c.CustomerId == id);
            return customerInstance;

In VB:

Imports System.Net
Imports System.Web.Http

Public Class CustomerVBController
    Inherits ApiController

    ‘ GET api/customerVB
    Public Function [Get]() As IEnumerable(Of CustomerVB)
        Return CustomerVB.Retrieve()
    End Function

    ‘ GET api/customerVB/2
    Public Function [Get](id As Integer) As CustomerVB
        Dim customerList = CustomerVB.Retrieve()
        Dim customerInstance = customerList.FirstOrDefault(
                    Function(c) c.CustomerId = id)
        Return customerInstance
    End Function
End Class

The controller class inherits from ApiController. This ensures that the service understands that this is a Web API controller class.

The class is called CustomerController (CustomerVBController in the VB example). The name should define the type of content the controller provides and end with "Controller". The service automatically locates the controller by name. To access the CustomerController, you would add "api/Customer" to the address bar and .NET automatically executes the Get method in the CustomerController class. (Enter api/CustomerVB to call the CustomerVBController.)

Both functions are named "Get". Note that in VB, "Get" is a keyword so it needs brackets around it to use it as a function name. But you could change the name to something more specific like GetCustomer.

The functions contain code to provide the requested data. The Get without any parameters retrieves the entire list. The Get with the id parameter uses LINQ with a Lambda expression to find the requested customer in the list. (For an overview of Lambda expressions, see this link.)

NOTE: This is not the most efficient approach to retrieve one customer. You would instead want to get the one requested customer from the database.

Now when you run the application, the same Welcome page appears because we have not changed the UI. And since we are building a service, we could actually remove the default UI.

To get the customer data, add "api/customer" to the address bar. ("api/customerVB" if you are running the VB example.)


If you open the results in Notepad, you will see the following:


If you instead add "api/customer/2" to the address bar ("api/customerVB/2" in VB), you get this:


Use this basic set of steps as a starting point for building your Web API service.


1 Comment

  1.   Sally — February 20, 2013 @ 12:02 pm    Reply

    Loved this post, just wished I had found it about a month ago. Have you carried this further and included the db calls in the DAL?

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2023 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs