Friday, February 7, 2014

Implement CRUD operation with Web API 2.0

Previously I had 2 articles on Web API:


Developing Services for Modern Apps using MVC Web API 2 with Visual Studio 2013
Securing ASP.Net Web API Service




In these articles I shown you how to set the service up and how to secure your service. Today I am going to show you how to implement CRUD operations using Web API.



CRUD stands for Create, Read, Update and Delete. In any application, CRUD operations are the basic operations. One could not imagine a comprehensive application (or software) can live without CRUD operations. any services for an application more than likely needs to provide these basic operations for its applications.



It is especially true for modern app, because most of modern apps run in limited environment. Limited in processing power, limited in memory, limited in second tier storage. Besides, as cloud technologies become common in mobile computing world, it is common that one could uninstall the app and install it back. and when the app is been reinstalled, he or she wants to see the data he had before. on the other end, it is a critical requirement that when an app is uninstalled, NOTHING should be left behind on the device. So you need to save the data for user but cannot save it locally. the only answer is "save the data in the server". With that CRUD operations on the server side become a crucial element in mobile computing.



As I mentioned in my previous article, HTTP is the preferred protocol for services for mobile apps ( modern apps) and Web API is Microsoft's answer to the demand of providing RESTful service through HTTP. As positioned in such way, you might guess, Web API should provide CRUD operations. you guess it right ! Web API does provide CRUD operations. and the implementation is surprisely simple. in this article I will walk you through on how to implement these operation in detail.



Before I go to the detail, I want to touch on HTTP protocol a bit ( I am not HTTP expert for sure, some of you might have far more experience on HTTP than I do, please bear with me for the moment, if you do, you can skip this part of the article)



There are GET, PUT, POST and DELETE operations in HTTP protocol. in GET operation, you can just get and you also can provide parameter for the operation. This is prefect for the CRUD operations:



GET : Read All
GET with parameter: Read by key
POST :Create ( or Add or Insert)
PUT :Update
DELETE :Delete




Enough talking, let's dive into the code... Talk is cheap, ( isn't it?) show me the code ( here you are!)

The following code example assume you have created an WebAPI project following my first article and you have a Web API project up and running. in this example for simplicity, I omitted the Data access layer You can hook it up with any data access layer you want, I personally prefer Entity Framework. In fact, Visual Studio 2013 offer many template when creating Controller. One of them is a template that directly hook up with EF. I also omitted security implementation you can refer to my second article for security implementation..



1) create your Model class under Models folder: in my example, I have the following very simple class:

public class Person
{
public int Id { get; set; }
public String LastName { get; set; }
public String FirstName { get; set; }
}



2) add your controller



Under Controllers folder, right mouse click and select <Add><Controller>. you will be presented with 7 options on what kind of controller you want to create (I choose Web API2 Controller with read/write actions for simplicity reason, you could choose Web API2 Controller with actions using Entity Framework. ) then provide a name for your controller.( you are able to do so because there is a Sample factory behind it) In my case I select Person. and IDE will create a class as following:

public class PersonController : ApiController
{
// GET api/person
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

// GET api/person/5
public string Get(int id)
{
return "value";
}

// POST api/person
public void Post([FromBody]string value)
{
}

// PUT api/person/5
public void Put(int id, [FromBody]string value)
{
}

// DELETE api/person/5
public void Delete(int id)
{
}
}
}



3) add code to replace these stub code for those operations

code block one:

For this demo, I created a static list as data store, and instantiate it with some members in a static contractor

private static List<Person> _MyFamily = new List<Person>();

static PersonController()
{
_MyFamily.Add(new Person { Id = 1, LastName = "Lu", FirstName = "Peter" });
_MyFamily.Add(new Person { Id = 2, LastName = "Yin", FirstName = "Maggie" });
_MyFamily.Add(new Person { Id = 3, LastName = "Lu", FirstName = "Claire" });
_MyFamily.Add(new Person { Id = 4, LastName = "Lu", FirstName = "Wendy" });
_MyFamily.Add(new Person { Id = 5, LastName = "Lu", FirstName = "Olivia" });
}



Code block 2: Get All

you will change you Get method to the following:

public IEnumerable<Person> Get()
{
return _MyFamily;
}

That means whenever your site is hit with http:/<your site address>/api/Person/, the site will return all it has in MyFamily list




Code block 3: Get Person by Id

you will change you get by id method as following:



public Person Get(int id)
{
return _MyFamily.Where(p => p.Id == id).First();
}




In this method, you will search for the person with the specified id and return it back to the caller. ( this is kind of POC code, in live development, you need to handle scenarios like not found.)



Code block 4: Post

you will replace you Post method as following:



public void Post([FromBody]Person value)
{
_MyFamily.Add(value);
}




In this method, you add the person you are given into the list. ( this is kind of POC code, in live development, you need to handle scenarios what happen if the person exists.)




Code block 5: Put

you will change you Put method as following:

public void Put(int id, [FromBody]Person value)
{
var target = _MyFamily.Where(p => p.Id == id).First();
if (target != null)
{
target.FirstName = value.FirstName;
target.LastName = value.LastName;
}
}




Code block 6: Delete

you will change you Delete method as following:

public void Delete(int id)
{
_MyFamily.Remove(this.Get(id));
}




4) test your web app service with test client

Build your project and start your project in IE. you will see a screen shot like this:




Click on <API> you will get to see your Person Controller as following:




Click on first link GET api/Person you will get to see this screen:



Click on TestAPI and then click on <Send> button on the right bottom of the dialog, . you will get the body content as following:


[{"Id":1,"LastName":"Lu","FirstName":"Peter"},{"Id":2,"LastName":"Yin","FirstName":"Maggie"},{"Id":3,"LastName":"Lu","FirstName":"Claire"},{"Id":4,"LastName":"Lu","FirstName":"Wendy"},{"Id":5,"LastName":"Lu","FirstName":"Olivia"}]

this is List<Person> instance in Json format. if you want it to be XML form, just add a header "Accept" , "application/xml" then click on <Send>, you will get the object serialized in xml format as following:

<ArrayOfPerson xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PeterLu.ChampionService.Models"><Person><FirstName>Peter</FirstName><Id>1</Id><LastName>Lu</LastName></Person><Person><FirstName>Maggie</FirstName><Id>2</Id><LastName>Yin</LastName></Person><Person><FirstName>Claire</FirstName><Id>3</Id><LastName>Lu</LastName></Person><Person><FirstName>Wendy</FirstName><Id>4</Id><LastName>Lu</LastName></Person><Person><FirstName>Olivia</FirstName><Id>5</Id><LastName>Lu</LastName></Person></ArrayOfPerson>


you can use the test client to test other API calls...( test client is very handy when ity comes to testing your Web API functionality.

No comments:

Post a Comment