RESTful Web Services in .NET (Part 2)

Now that I’ve finally got a bit of time I figured I should explain how we updated our old RESTful framework to be nice and slick. Instead of one method per class which handles all sub method variations we now have something much prettier and easier to maintain. The UserService found in the previous post can now look like:

public class UserService : RestService
{
	[RestMethod("GET", "^$")]
	public IList RetrieveAll()
	{
	}

	[RestMethod("GET", @"^(?<id>[0-9]+)$")]
	public User Retrieve(int id)
	{
	}

	[RestMethod("HEAD", @"^(?<name>\w+)$")]
	public User Exists(string name)
	{
	}

	[RestMethod("PUT", "^$", typeof(User))]
	public User Create(User user)
	{
	}

	[RestMethod("POST", "^$", typeof(User))]
	public bool Update(User user)
	{
	}

	[RestMethod("DELETE", @"^(?<id>[0-9]*)$")]
	public bool Delete(int id)
	{
	}
}

As you can see there are a lot of differences:

  • Heavy influence from newer APIs
  • Methods can return any Type
  • Methods can take 0 or more arguments of any Type
  • RestMethodAttribute has been added to match URLs against methods

Most of the code above should be self-explanatory, but in case it’s not here’s some help.

The method decorator [RestMethod("GET", "^$")] tells the framework that any HTTP GET requests against the UserService class without any trailing arguments (http://localhost/user.r) should be handled by RetrieveAll().

The method decorator [RestMethod("GET", @"^(?<id>[0-9]+)$”)] tells the framework that any HTTP GET request against the UserService class which ends with a number only (http://localhost/user.r/1, http://localhost/user.r/5000, etc) should be handled by Retrieve(int id). The cool thing here is that the regex group will provide a match to the argument name so our function will be called with whatever number the URL ends with. So calling http://localhost/user.r/25 where the following is the executed method will result in?

[RestMethod("GET", @"^(?<id>[0-9]+)$")]
public bool Retrieve(int id)
{
	return id == 25;
}

TRUE!! Pretty simple, and very cool. Another nice feature is when the HTTP request contains a body like a POST or PUT would. So POSTing to http://localhost/user.r with a body of:

{'user': {
	'first_name': 'Matthew',
	'last_name': 'Metnetsky'
}}

would call the method decorated with [RestMethod("POST", "^$", typeof(User))] and it’s user argument would actually be set assuming the class implemented a JSON serializer. All of the URL/body mappers are definable by implementing Binder and listing them in the web.config against a Content-Type. By default there are Binders for form variables, JSON, XML, raw streams, and a few more.

So why might I be discussing the external API of a closed library? To PUSH innovation in the current public ones. By taking these ideas and creating an “open” version I’m sure I’d be breaking my contract so I’ve got two options:

  1. Expose our public API to entice and PUSH others to innovate
  2. Get a lot of feedback which might enable me to get our library opened

So…. let me know…. ;-)

RESTful Web Services in .NET (Part 1)

A couple of years ago I tossed together a RESTful IHttpHandlerFactory for .NET. It wasn’t amazing, but it was being used long before Microsoft et all decided to create there own. Instead of extending Page you extended RestService and implemented whatever methods you wanted.

public interface IRestService
{
	void Head(RestEventArgs args);
	object Get(RestEventArgs args);
	object Put(RestEventArgs args);
	object Post(RestEventArgs args);
}

As you can probably guess the request’s HTTP Method was transformed into the function name and executed accordingly. If the method wasn’t “known” we would then use reflection to find the method for execution. Not to fansy as you can see, but it worked.

If a request was made for http://localhost/app/users.r the IHttpHandler factory would load users.r and it would tell us what class you assigned to it (much like @Page CodeBehind/Inherits in .aspx). From there we would instantiate the class and call the appropriate method. Whatever you returned would be marshalled for wire transfer based on it’s type.

	class User : IXmlSerializable
	{
		/* ... */
	}

	public class UserService : RestService
	{
		public object Get(RestEventArgs args);
		{
			return new User(5, "Matthew", "Metnetsky");
		}
	}
}

Calling http://localhost/app/users.r would execute UserService::Get(..) which would return a User instance. The results are then inspected for a few different interfaces like IXmlSerializable, IJsonSerializable (one of ours), etc. Based on what is supported by the Type, we then check if the requester supports it by interogating their “Accepts” header. This way each requester can receive what they understand how to handle (for instance – don’t send JSON to AS3). The system really worked well, and it’s simplicity made it damn fast.

Like all frameworks however, once it was actually in use we were able to see the pitfalls and issues. Take a look at the following URLs:

  • http://localhost/app/users.r
  • http://localhost/app/users.r/1
  • http://localhost/app/users.r/matthew

In order to handle all of the urls above the Get(RestEventArgs) method turned into one big switch/if/else conditional. Some people made it prettier than others, but the result was the same. So about 14 months ago we upgraded our framework – check back soon to see how we did it, and why I’m bringing it up now.