A web API

A web API is a framework to develop HTTP services used by clients or a web browser. A web API collects definitions, procedures, and protocols in order to communicate with different computer software. For example, HTTP services are created by ASP.NET Web API to communicate with different clients, such as web browsers, smartphones, and tablets. Developing a web API using a .NET framework is an ideal platform to build RESTful applications, which is the type of an architecture. A web API is an interface, which defines a request and response message system. In most cases, a web API expresses JavaScript Object Notation (JSON) or XML and can be exposed on the client-side using the most common communication mechanism for the Web, which is the HTTP request and response. The client web API extends the functionality of a web browser or other HTTP clients. An ASP.NET Web API is a part of the ASP.NET platform and can be used with ASP.NET web forms and MVC. It can also be used as a standalone Windows service.

Why a web API?

Today, the use of mobile devices has increased, and therefore, a web API exposes data to web browsers as well as to all smart devices. Thus, we are moving toward an application-based world where data and information can be shared between the user and the server using a native mobile application. So, we need the web API to communicate with both—web browsers and mobile devices.

ASP.NET Web APIs have the following characteristics:

  • Routing: An ASP.NET Web API fully supports routing, which includes routing parameters and constraints.
  • Content conciliation: The client and server conclude the format of data returned by the web API. By default, the ASP.NET Web API supports XML and JSON but it can be extended by adding custom formats using URL-encoded formats.
  • Binding: In an ASP.NET Web API, data can be extracted from HTTP using model binding, which can convert the data into .NET objects.
  • Hosting: A web API is hosted in Internet Information Services (IIS), but you can still use routing and other features.
  • CRUD operations: In ASP.NET, the web API supports Create, Read, Update, and Delete (CRUD) operations, which will be discussed in Chapter 6, Using AngularJS and ASP.NET Web API for CRUD Operations in detail, because it works with HTTP verbs, such as GET, POST, PUT, and DELETE.
  • OData: The ASP.NET Web API automatically supports OData and returns it in the IQueryable format.
  • Light weight: The ASP.NET Web API is good for mobile devices which have very limited bandwidth.

This figure shows the communication between different environments:

Why a web API?

Different API types

There are different types of APIs, such as web service APIs, library-based APIs, object-remoting APIs, and hardware APIs.

Web service APIs

Web service APIs can be accessed using a URL, and HTTP will be used to exchange information between a client and a web service. Web service APIs have Simple Object Access Protocol (SOAP), XML-RPC, JSON-RPC, and Representational State Transfer (REST):

  • SOAP: This defines the communication and the structure of sending and receiving messages.
  • XML-RPC: Remote Procedure Call (RPC) protocol is an Internet protocol, which uses XML to encode calls and also uses HTTP to transfer data.
  • JSON-RPC: This is the same as XML-RPC, but uses JSON to encode a call instead of XML.
  • REST: This is a set of architectural doctrines rather than a protocol. Its architecture differentiates REST from other web services. REST uses JSON and XML data format. In REST, there is no coupling between a REST interface and the underlying architecture of the service, which is the main advantage of REST over RPC. It uses HTTP verbs to differentiate the action to execute, based on the same URL or route.

Library-based APIs

To use library-based APIs, a client or application will import the library and use its functions to perform actions. For example, Google Map APIs, which use a JavaScript API to display Google Maps in an application.

Class-based APIs

Class-based APIs are organized in object-oriented classes. Each class in class-based APIs is a set of information and related behaviors. For example, a Java API, Android API, and so on.

Object-remoting APIs

Object-remoting APIs use a remote protocol, such as Common Object Request Broker (COBRA). Object-remoting APIs employ local proxy objects to epitomize remote objects. For example, .NET remoting can be used to build applications even on a remote computer.

Hardware APIs

Hardware APIs are used to manipulate addressable pieces of hardware on a device. For example, video acceleration, camera, and so on.

Creating a web API using Visual Studio

In order to create a web API using Visual Studio, we will use the project which we created in the previous Creating a data model from an existing database section of this chapter. We use the Northwind database to retrieve the data and show it on the frontend (client) using AngularJS.

In Chapter 6, Using AngularJS and ASP.NET Web API for CRUD Operations, we will implement the CRUD operation using AngularJS to the Northwind database as follows:

  1. Open the project in Visual Studio .NET. In the solution explorer, we will see that the organization of the project is similar to an MVC project. When we create a project, it creates WebApiConfig.cs in the App_Start folder and the Models and Controllers folders are automatically created for us as shown in here:
    Creating a web API using Visual Studio

    Routing is handled in the WebApiConfig.cs of the project. In the web API, routing sends the incoming requests to specific controllers and by default, the web API framework will map the incoming request to the applicable action of the controller, based on the HTTP verb of the demand.

  2. Right-click on the Controller folder in the solution explorer; select Add and then Controller as shown:
    Creating a web API using Visual Studio
  3. Select Web API 2 Controller-Empty and click on Add:
    Creating a web API using Visual Studio
  4. Give a name to the controller. For example, Customer. It is important that the Controller suffix be retained:
    Creating a web API using Visual Studio
  5. Create functions/methods in the preceding CustomerController controller as listed next:
    • First, we created the instance of the data model earlier using Entity Framework as shown in this line of code:
                 NorthwindEntities _db = new NorthwindEntities();
    • Second, we created a public getAllCustomers function, which will return all the customers in the Customer table of the Northwind database. The code snippet to create a function is:
              NorthwindEntities _db = new NorthwindEntities();
      
              public IEnumerable<Customer> getAllCustomers()
              {
                  _db.Configuration.ProxyCreationEnabled = false;
                  return _db.Customers;
              }
  6. Let's create another function which will return specific customer information based on the CustomerID, which is the primary key of the Customer table in the Northwind database, as shown in the following code. We used Language Integrated Query (LINQ) to query against the Northwind virtual schema, which we created using the Entity Framework earlier in this chapter.
    public IHttpActionResult getCustomerByCustomerID(string customerID)
       
    {
          _db.Configuration.ProxyCreationEnabled = false;
    
           var customer = _db.Customers.FirstOrDefault(c =>  
                          c.CustomerID == customerID);
    
                if (customer == null)
                {
                    return NotFound();
                }
                return Ok(customer);
      }

LINQ

Language Integrated Query is a library of collections and iterators built by Microsoft to work with data such as a collection of objects in memory, rows of tables in a database, and XML file elements. LINQ provides a powerful query ability to languages, such as C# and VB.NET, instead of learning new languages. The LINQ syntax is more like the syntax used to write queries in Structured Query Language (SQL). The LINQ library contains a set of methods based on IEnumberable<T> such as Select, Sum, Where, and so on, which can be used for restrictions or projections of data.

For example, there is a Customer table in a database. The following code example shows you a select statement:

  1. Select all customers:
    var cust = from c in Customers 
        select c
  2. Select specific customers:
    var cust = from c in _db.Customers
        where c.CustomerID=="ALFKI"
        select c

    Note

    LINQ: You can get familiar with LINQ by referring to http://msdn.microsoft.com/en-us/library/bb397933.aspx.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset