Create REST API using ASP.NET MVC that speaks both Json and plain Xml

ASP.NET MVC Controllers can directly return objects and collections, without rendering a view, which makes it quite appealing for creating REST like API. The nice extensionless Url provided by MVC makes it handy to build REST services, which means you can create APIs with smart Url like "something.com/API/User/GetUserList"

There are some challenges to solve in order to expose REST API:

  • Based on who is calling your API, you need to be able to speak both Json and plain old Xml (POX). If the call comes from an AJAX front-end, you need to return objects serialized as Json. If it's coming from some other client, say a PHP website, you need to return plain Xml.
  • Similarly you need to be able to understand REST, Json and plain Xml calls. Someone can hit you using REST url, someone can post a Json payload or someone can post Xml payload.

I have created an ObjectResult class which takes an object and generates Xml or Json output automatically looking at the Content-Type header of HttpRequest. AJAX calls send Content-Type=application/json. So, it generates Json as response in that case, but when Content-Type is something else, it does simple Xml Serialzation.

image

Here's the ObjectResult that you can use from Controllers to return objects and it takes care of proper serialization method. Above shows the Json serialization, which is quite simple. XmlSerialization is a bit complex though:

image Things to note here:

  • You have to force UTF8 encoding. Otherwise it produces UTF16 output.
  • XML Declaration is skipped because that's not quite necessary. Wastes bandwidth. If you need it, turn it on.
  • I have turned on indenting for better readability. You can turn it off to save bandwidth.

Some of you might be boiling inside looking at my obscure coding style. I love this style! I am spoiled by jQuery. I wish there was a cQuery. I actually started writing one, but it never saw day light just like my hundred other open source attempts.

Now back to Object Serialization, we got the serialization done. Now you can return objects from Controller easily:

image

You can use the test web project to call these methods and see the result:

image

So far you have seen simple object and list serialization. A best practice is to return a common result object that has some status, message and then the real payload. It's handy when you only need to return some error but no object or list. I use a common Result object that has three properties - ErrorCode (0 by default means success), Message (a string data type) and Data which is the real object.

image

When you want to return only a result with error message, you can do this:

image

This produces a result like this:

image

No payload here. So, the return format is always consistent. Those who are consuming service can write a common Xml or Json parsing code to consume both success and failure response. Those who are building API for their website, I humbly request you to return consistent response for both success and failure. It makes our life so easier.

So, far we have only returned objects and lists. Now we need to accept Json and Xml payload, delivered via HTTP POST. Sometimes your client might want to upload a collection of objects in one shot for batch processing. So, they can upload objects using either Json or Xml format. There's no native support in ASP.NET MVC to automatically parse posted Json or Xml and automatically map to Action parameters. So, I wrote a filter that does it.

image

This filter intercepts calls going to Action methods and checks whether client has posted Xml or Json. Based on what has been posted, it uses DataContractJsonSerializer or simple XmlSerializer to convert the payload to objects or collections.

You use this attribute on Action methods like this:

image

The attribute expects a parameter name where it stores the deserialized object/collection. It also expects a root type that it needs to pass to the deserializer. If you are expecting a single object, specify typeof(SingeObject). If you are expecting a list of objects, specify an array of that object like typeof(SingleObject[])

You can test the project live at this URL:

http://labs.dropthings.com/MvcWebAPI

The code is also available at:

http://code.msdn.microsoft.com/MvcWebAPI

Enjoy!

------------

Here's an Eid gift for my believer brothers. Check out this amazing site www.quranexplorer.com/. You will get online recitation, translation - verse by verse. The recitation of Mishari Rashid is something you have to listen to to believe. Try these two recitations to see what I mean:

Sura 97 - Verse 1
Sura 114 - Verse 1

Press the "Play" icon at bottom left (hard to find).

 

kick it on DotNetKicks.com
Published Friday, October 03, 2008 5:05 PM by omar
Filed under: , ,

Comments

# re: Create REST API using ASP.NET MVC that speaks both Json and plain Xml

Friday, October 03, 2008 3:44 PM by Khurram

I love your eid gift. Its really awesome.

# re: Create REST API using ASP.NET MVC that speaks both Json and plain Xml

Saturday, October 18, 2008 11:35 PM by Pathik

Excellent article. I loved it. I made REST architecture b4 MVC came in picture and it was so difficult but this has solved all problems.

Thanks Omar

# re: Create REST API using ASP.NET MVC that speaks both Json and plain Xml

Thursday, October 23, 2008 4:52 PM by Darrel Miller

I commend your effort but you really need to remove all traces of the word REST from this post.  Your implementation is sooooooo far from being RESTful it is scary.  I'm not saying there is anything wrong with your implementation, it's just not REST. It  violates most of the REST constraints.  Don't believe me?  Ask the guy who invented the term REST.   roy.gbiv.com/.../rest-apis-must-be-hypertext-driven

# re: Create REST API using ASP.NET MVC that speaks both Json and plain Xml

Friday, October 24, 2008 1:14 AM by omar

Hi Darrel,

Good observation! I would like to understand why you think my mention of REST is wrong here.

Here's what I tried to convery:

1) You can create REST like API using ASP.NET MVC. I do not see why this statement is wrong.

2) You can accept JSON and XML payload on RESTful resources via GET and POST protocol. I do not see why this statement is wrong.

REST requires that every resource must have a uniquely identifiable URI. For ex, someapi.com/API/GetUser/Scott gives you a person named 'Scott'. Now, my implementation gives you further control on the representation of 'Scott' resource by allowing you to consume 'Scott' in either Json or POX format.

I suppose if I made the URL like someapi.com/API/User/Scott and based on GET and POST, decide what action to invoke (GetUser or UpdateUser), that would look more like RESTful. But in any way, what URI you provide, how you expose and consume resources are entirely up to you. I am just enabling you to offer two more representation for your resources.

# re: Create REST API using ASP.NET MVC that speaks both Json and plain Xml

Saturday, November 01, 2008 3:14 PM by Stephan

Hi Omar,

There is a nice article from Joe Gregorio:

www.xml.com/.../restful-web.html

which describes the basic mechanisms for REST based services.

Basically, your URIs will look like this:

/API/User

and only the HTTP methods will be different for Create,Retrieve,Update,Delete (Post,Get,Put,Delete)

A nice addition is this article from the same author:

www.xml.com/.../restful-web.html

Regards,

Stephan

# re: Create REST API using ASP.NET MVC that speaks both Json and plain Xml

Friday, November 07, 2008 7:15 AM by Piers Lawson

Nice article Omar, I picked up some ideas. If you are interested in a truely RESTful web service using ASP.Net MVC I have been writing a series of posts at shouldersofgiants.co.uk/blog on this subject. I too had created multiple representations (including XHTML and Help). I also supportted POST overloading. Cheers!

# re: Create REST API using ASP.NET MVC that speaks both Json and plain Xml

Tuesday, November 25, 2008 7:30 PM by farid

not yet an advance developer, so much of your article are too much for me, but stuff u had on ajax and loading and compression, seems like something my side needs to explore,, thanks for the break down explanation,

also thanks for the into to quranexplorer

Leave a Comment

(required) 
(required) 
(optional)
(required)