Web API Demos

Web page by Kevin Harris of Homer IL

Please contact Kevin Harris of Homer IL concerning this web site

Web API Demos

Some Web API demonstrations contain sections of code which get copied in at various points. Instead having sections of code mysteriously appear, Jon Flanders, in this free Pluralsight Web API Tutorial video, builds the code from scratch starting with really simple examples and building up to more complex examples.

Demo 1: Really Simple Get

The first demo uses an empty project. In Visual Studio 2015 make sure the Web API is checked on the template screen, but not templates are used which makes for a simple, basic project that shows just the essentials of getting the Web API to function. Create a controller (HelloWebApiController) with a default Get() method and you have a functioning Web API. The API routing is already set up in App_Start/WebApiConfig.cs. Run the project, start Fiddler, and call the Web API from a browser (http://localhost:59486/api/HelloWebApi). The Browser will prompt you to accept the JSON response from the web service. You will be able to see the response and request in Fiddler, as shown in the screen capture below.

.Simple Web API Get

Simple Web API Get

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;

namespace KevinEmptyWebApi.Controllers
{
    public class HelloWebApiController : ApiController
    {
        // GET: HelloWebApi
        public string Get()
        {
            return "Hello Kevin at " + DateTime.Now.ToString();
        }
    }
}

HelloWebApiController.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
using System.Web.Http;

namespace KevinEmptyWebApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

WebApiConfig.cs

Demo 2: Web API Template Modified

This demo uses the Web API template with the generated "ValuesController" modified to use a static list of strings with the standard interface. This allows you to run the Web API and use fiddler to capture the traffic (to view headers, body, etc.) and manually compose Web API calls to add (Post), retrieve (Get), update (Put), and delete (Delete) data into the list.

To create the project, in Visual Studio 2015 Professional, New Project, Web API template, Change Authentication to No Authentication, Uncheck Host in the Cloud and Add Unit Tests. Modify the generated "ValuesController" to work with a List as shown in code below. To make the Web API calls, use the Composer tab in Fiddler and then view the results in Fiddler's Inspectors tab.

.Executing and Examining Results in Fiddler


Executing and Examining Results in Fiddler

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.Collections.Generic;
using System.Web.Http;

namespace KevinWebApiTemplateModified.Controllers
{
    public class ValuesController : ApiController
    {
        static List<string> data = initList();

        private static List<string> initList()
        {
            var ret = new List<string>();
            ret.Add("Kevin");
            ret.Add("Harris");
            return ret;
        }

        // GET api/values
        public IEnumerable<string> Get()
        {
            return data;
        }

        // GET api/values/5
        public string Get(int id)
        {
            return data[id];
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
            data.Add(value);
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
            data[id] = value;
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
            data.RemoveAt(id);
        }
    }
}

Modified Values Controller

Demo 3: Creating Response Messages with HttpResponseMessage

The following code uses HttpResponseMessage in the Get(id) method to return a 404 (not found) code along with the text "Item not found" when a requested item was not found. The Post(value) method uses HttpResponseMessage to return a 201 (created) code and create a Location header containing a URI which points to the location of the newly created item.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace KevinWebApiTemplateModified.Controllers
{
    public class ValuesController : ApiController
    {
        static List<string> data = initList();

        private static List<string> initList()
        {
            var ret = new List<string>();
            ret.Add("Kevin");
            ret.Add("Harris");
            return ret;
        }

        // GET api/values
        public IEnumerable<string> Get()
        {
            return data;
        }

        // GET api/values/5
        public HttpResponseMessage Get(int id)
        {
            if (data.Count > id)
            {
                return Request.CreateResponse<string>(HttpStatusCode.OK, data[id]);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Item not found");
            }
        }

        // POST api/values
        public HttpResponseMessage Post([FromBody]string value)
        {
            data.Add(value);
            var msg = Request.CreateResponse(HttpStatusCode.Created);
            msg.Headers.Location = new Uri(Request.RequestUri + "/" + (data.Count-1).ToString());
            return msg;
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
            data[id] = value;
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
            data.RemoveAt(id);
        }
    }
}

ValuesController.cs using HttpResponseMessage to Create Responses



Error | ASP.NET Developer

Error

Error message

  • Warning: Cannot modify header information - headers already sent by (output started at /srv/disk9/1218369/www/kcshadow.net/aspnet/includes/common.inc:2748) in drupal_send_headers() (line 1232 of /srv/disk9/1218369/www/kcshadow.net/aspnet/includes/bootstrap.inc).
  • PDOException: SQLSTATE[42000]: Syntax error or access violation: 1142 INSERT command denied to user '1218369_b2cf'@'185.176.40.58' for table 'watchdog': INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => cron [:db_insert_placeholder_2] => Attempting to re-run cron while it is already running. [:db_insert_placeholder_3] => a:0:{} [:db_insert_placeholder_4] => 4 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://www.kcshadow.net/aspnet/?q=webapidemos [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 54.80.87.62 [:db_insert_placeholder_9] => 1534851976 ) in dblog_watchdog() (line 160 of /srv/disk9/1218369/www/kcshadow.net/aspnet/modules/dblog/dblog.module).
The website encountered an unexpected error. Please try again later.