Consuming RESTful API with RESTframework

As explained in previous post, we’re going to demonstrate how RESTframework handles REST web services. I’ll be consuming a simple Django demo web service created in previous post, so either grab the sources or read the post and build it yourself. Assuming you have this service running on localhost, port 8000, we can continue.

First, download RESTframework from GitHub. With git client, simply type in terminal:

$ git clone git@github.com:ivasic/RESTframework.git

The quickest way to get RESTframework into your project is just including all the files from RFClasses  folder. RF does not have any external dependencies so building shouldn’t be a problem.

RFClasses

RFClasses

Now, we’ll also need JSONKit to parse API response and MBProgressHUD to show some progress. Grab both from GitHub and add to your project.

Fetching objects list

We’ll have 2 view controllers in our demo app. One will be a simple object list and the other one will be, even more simple, view controller for creating a new object. First, we’re going to show how to fetch the object list. We’ll need a GET request to /objects/ URL and we’ll need to parse the JSON array we get in response and show in the table view.

RFRequest* r = [RFRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/"] type:RFRequestMethodGet resourcePathComponents:@"objects", nil];
[MBProgressHUD showHUDAddedTo:self.view animated:YES].labelText = NSLocalizedString(@"Loading...", @"");
[RFService execRequest:r completion:^(RFResponse* response) {
	[MBProgressHUD hideHUDForView:self.view animated:YES];
 
	if (response.error) {
		UIAlertView* aiv = [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"") message:response.error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
		[aiv show];
		return;
	}
 
	self.dataSource = [response.dataValue objectFromJSONData];
	[self.tableView reloadData];
}];

So, what we’re doing in this code snippet is:

  • Creating a GET RFRequest with appropriate URL and resource path
  • Attaching MBProgressHUD to our view to show spinner progress
  • Executing RFRequest and defining the block to execute after RFResponse is received
  • Inside this block, we simply check for errors, parse the response, add to our tableView dataSource and reloading the table
You can see all this in action in the project sample attached to this blog post (at the bottom).

Creating new objects

Our view controller for creating new objects is responsible for creating POST requests to /objects/ URL. Again, very simple, you just need to do this:

RFRequest* r = [RFRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/"] type:RFRequestMethodPost resourcePathComponents:@"objects", @"", nil];
 
[r addParam:self.txtName.text forKey:@"name"];
[r addParam:self.lblDate.text forKey:@"date"];
 
[MBProgressHUD showHUDAddedTo:self.view animated:YES].labelText = NSLocalizedString(@"Submitting...", @"");
[RFService execRequest:r completion:^(RFResponse* response) {
	[MBProgressHUD hideHUDForView:self.view animated:YES];
 
	if (response.error) {
		UIAlertView* aiv = [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"") message:response.error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
		[aiv show];
		return;
	}
 
	UIAlertView* aiv = [[[UIAlertView alloc] initWithTitle:@"Success" message:@"Success" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
	[aiv show];
 
	[self.navigationController popViewControllerAnimated:YES];
}];

Similar to our previous snippet, but this time we also add some parameters to the request – name and date strings.

This is a brief overview with sample Xcode project of how RESTframework consumes RESTful web APIs. Questions welcomed via comments as usual.

 

Download project: RESTframework demo Xcode project download

Building RESTful API with Django

In order to demonstrate how RESTframework for Cocoa works, I’m going to create a small RESTful API demo in Django/Python and use that as a demo web service we’re gonna query from our soon-to-be demo iOS app. Hopefully, you can also pick up a thing or two from this tutorial as well since Django seems to be a very powerful framework for building RESTful APIs with. If you don’t want to bother with Django, you can simply download the project (see the end of this post) and run it as a demo web service. Next post will explain how to use my RESTframework to consume this web service.

Requirements

You’ll need Python, of course, and I’ve tested this on v2.7 although I’m pretty sure it should also work on v2.6 and possibly v2.5. Then you’ll need django and djangorestframework both available for install with pip or easy_install.

Django project

Create a new django project and the first django app.

$ django-admin.py startproject DjangoTest
$ cd DjangoTest
$ django-admin.py startapp api

Now we need to modify our initial project settings. For the sake of simplicity, I’ll be using SQLite3 database since it doesn’t require any installation or setup. To do this, edit settings.py in your project dir.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'database.db',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

Another thing we need to do in settings.py is to add your app and djangorestframework to the installed apps section.

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'DjangoTest.api',
    'djangorestframework',
)

Okay, now let’s run and test if it worked.

$ python manage.py runserver

Now go to http://localhost:8000/ and make sure you see “It worked” message.

Next step is creating some resources for our RESTful API. I’ve created a simple model to hold a name and creation date. Looks like this:

class Object(models.Model):
	name = models.CharField(max_length=50)
	date = models.DateTimeField()

We’re almost there. We need to sync our database now after we’ve created the model (do this every time you change the model, see more info here)

$ python manage.py syncdb

RESTful API using django-rest-framework

Now our django project is ready. Using djangorestframework we will add RESTful API interface for our ‘api’ app. Assuming you’ve installed it correctly, all we need to do is to create another python file where we will store our resources. Name it resources.py and put this inside:

from djangorestframework.resources import ModelResource
from api.models import Object
 
class ObjectResource(ModelResource):
	model = Object
	fields = ('name', 'date')

When this is done, we need to add some URLs where our resources will be located. I’m using nifty views provided by djangorestframework which work with your models without a single line of code. You get 2 URLs for viewing a list of objects (or creating a new one) and one for viewing your object details. urls.py looks like this:

from django.conf.urls.defaults import patterns, include, url
 
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
from djangorestframework.views import ListOrCreateModelView, InstanceModelView
from api.resources import ObjectResource
 
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'DjangoTest.views.home', name='home'),
    # url(r'^DjangoTest/', include('DjangoTest.foo.urls')),
 
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
 
    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
 
    url(r'^objects/$', ListOrCreateModelView.as_view(resource=ObjectResource), name='object-root'),
    url(r'^objects/(?P[^/]+)/$', InstanceModelView.as_view(resource=ObjectResource), name='object'),
)

That’s it. Save and run your project and you’ll be able to access your resources at http://localhost:8000/objects/
For example, querying an URL like this one (providing you added an object with id=1) http://localhost:8000/objects/1/?_accept=application/json would result in this:

{"date": "2011-11-28 09:38:21", "name": "Test"}

Download sample project

Help yourself with the sources for this project ready to unzip & run. You can download the project here – DjangoRESTfulAPI.

REST framework for iOS is now Open Source

I have (finally) open sourced my RESTframework project on GitHub. It aims for simplicity of usage primarily. Querying RESTful web services is really easy now. Supported are iOS versions 4.0 and above and Mac OS 10.6 and above.

Feel free to fork & contribute!

RESTframework on GitHub

RESTful web service, API with ASP MVC 2

In this very simple tutorial, I’ll show how to build a basic RESTful API with Microsoft ASP MVC 2 later to be used with various clients (e.g. iOS application). This is a very basic level tutorial but it will show how easy it is to build powerful REST services in the matter of minutes.

The first thing to do is to create a new MVC 2 project, as simple as shown on the screenshot.

Create new MVC 2 project

Create new MVC 2 project

Now, I have deleted the Account controller and all the views cause I don’t need it for this example, but you don’t have to. The key concept to understand here is pretty simple – instead of returning back the Views as action results, we return JSON. MVC already provides HTTP verbs such as GET, POST, PUT and DELETE so all we really need to do is prepare our data and (de)encode it as JSON and we’re done. Fortunately enough, MVC also provides built-in JsonResult which inherits ActionResult which makes our job even easier. A simple GET action that returns a “Hello World” might look like this:

[HttpGet]
public ActionResult Index()
{
	return Json("Hello World!", JsonRequestBehavior.AllowGet);
}

There you go, a simple GET method is created. Now if you want to return something more complex, you can pass any serializable object to the Json() method and return that back. Here’s an array/dictionary combination.

[HttpGet]
public ActionResult Array()
{
	List<object> objects = new List<object>();						
	Dictionary dict = new Dictionary();
	dict.Add("key1", "value1");
	dict.Add("key2", "value2");
	objects.Add("item1");
	objects.Add("item2");
	objects.Add(dict);
	return Json(objects, JsonRequestBehavior.AllowGet);
}

This produces a JSON like this:

["item1","item2",{"key1":"value1","key2":"value2"}]

Ok, so how about other REST concepts like PUT, POST or DELETE? Easy as well. Define your action and just place a HTTP verb attribute like this example:

[HttpPut]
[ActionName("Index")]
public ActionResult IndexPut(string key, string value)
{
	Dictionary dict = new Dictionary();
	System.Web.Caching.Cache c = HttpContext.Cache;
	if (key == null || value == null)
	{
		dict.Add("result", "failed");
		dict.Add("message", string.Format("No key or no value provided"));
	}
	else
	{
		if (c.Get(key) == null)
		{
			c.Add(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
			dict.Add("result", "ok");
			dict.Add("message", string.Format("You have inserted {0} for key {1}", c[key], key));
		}
		else
		{
			dict.Add("result", "failed");
			dict.Add("message", string.Format("Value for key {0} already exists. Use POST to modify the value", key));
		}
	}
	return Json(dict);
}

The example above takes 2 input parameters named key and value (both strings but can be any object) and puts them into HTTP Cache. It also prevents to PUT another value with the same key. The project source code has other methods as well (POST and DELETE) used to modify the values and delete values for keys. Take a look on how that is implemented. This is very basic stuff so I won’t cover those methods here but feel free to ask in comments if something is unclear.

This REST example will be used for future posts covering REST integration in iOS, so you can keep it somewhere for testing. The project source code can be downloaded here: ASP MVC 2 REST service example

Consuming ASP.NET web services in iOS part 2

In previous blog post I’ve explained how to create iOS friendly ASP .NET web service with JSON RPC so now we’re going to take it further by creating an iPhone app that will consume this web service. Since iOS natively does not support JSON, we’ll be using this nice JSON framework available on Google Code here. This framework provides NSObject categories which allow simple JSON parsing and and it’s really convenient to use with iOS SDK. Other than that, we’ll be using native iOS SDK APIs only to create HTTP connection and query our JSON RPC service. Calling this web service is done by creating NSURLRequest with HTTP POST method and passing method name, method parameters (arguments) and identificator. NSURLConnection uses this request and does the magic we need. Let’s see the code.

First, we need to create JSON string which we’re going to POST to our RPC service. We do this by simply creating a dictionary and breaking it down to JSON representation.

 
//RPC
 
NSMutableDictionary* reqDict = [NSMutableDictionary dictionary];
 
[reqDict setObject:methodName forKey:@"method"];
 
[reqDict setObject:parameters forKey:@"params"];
 
[reqDict setObject:identificator forKey:@"id"];
 
//RPC JSON
 
NSString* reqString = [NSString stringWithString:[reqDict JSONRepresentation]];

We should note 3 arguments we’re posting to the service – method, params and id. Method is RPC method name as declared in JSON RPC web service. Params are arguments this method requires and ‘id’ is the call identifier which RPC call returns when sending back response and it’s used to link the response to the request in case you’re sending out multiple requests. In our case, the method name is ‘HelloWorld’ without arguments and as the identifier we’ll just put 1.

So now we create NSURLRequest and NSURLConnection using this reqString. This is the main part of code so pay attention.

 
//Request
 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
 
NSData* requestData = [NSData dataWithBytes:[reqString UTF8String] length:[reqString length]];
 
//prepare http body
 
[request setHTTPMethod: @"POST"];
 
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
 
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
 
[request setHTTPBody: requestData];

First we create a mutable url request, set it’s HTTP method to “POST” and fill out other HTTP specific header fields. Finally we set our JSON request string as HTTP body.

Now we simply create NSURLConnection, assign a delegate to it and wait for our data.

 
urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
 
[request release];

The delegate part of the calling object has these methods defined.

#pragma mark -
#pragma mark NSURLConnection delegate
 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	NSLog(@"Did receive response: %@", response);
 
	[webData release];
	webData = [[NSMutableData alloc] init];
}
 
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	assert(webData != nil);
	[webData appendData:data];
}
 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	[webData release];
	webData = nil;
	[urlConnection release];
	urlConnection = nil;
 
	UIApplication* app = [UIApplication sharedApplication];
	app.networkActivityIndicatorVisible = NO;
 
	//notify
	[delegate loadingFailed:[error localizedDescription]];
}
 
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[urlConnection release];
	urlConnection = nil;
 
	UIApplication* app = [UIApplication sharedApplication];
	app.networkActivityIndicatorVisible = NO;
 
	//DO something with webData
	[delegate dataLoaded:webData];
 
	[webData release];
	webData = nil;
}

Once the connection gets a response we create NSData (webData) and we append bytes to it in didReceiveData callback. In the end we either get didFailWithError or didFinishLoading and take actions accordingly.

Finally, the app would return something like this when launched.

iPhone calling JSON RPC web service

iPhone JSON RPC

For your convenience, I have attached XCode project for download. Please note that this is an example only and should be treated as such, I don’t provide guarantee of any kind for this code.

JSON RPC iOS example project

Consuming ASP .NET web services in iOS part1

Since, at the time of my writing, iOS SDK does not natively support SOAP WebServices many have found different ways to consume these web services. Some of them include manually making HTTP requests and parsing response, using WSDL to ObjectiveC generators and more. One of the convenient ways I found when it comes to RPC is to combine the niceness of ASP .NET with JSON-RPC which can be accessed in iOS easily. So, let’s begin creating an iOS friendly ASP .NET web service.

The framework which makes this possible is Jayrock. Jayrock is a modest and an open source (LGPL) implementation of JSON and JSON-RPC for the Microsoft .NET Framework, including ASP.NET.

Let’s see how we can make this work. First, let’s create a simple HelloWorld() web service. Open up Visual Studio and create ASP .NET web project (or any other suitable type).

Visual Studio New Web Application Dialog

Create New Application

Add a generic handler to your app and call it whatever you like.

Visual Studio Add Handler

Add generic handler

Now we need to reference Jayrock library, so right click your project and “Add Reference”, browse to find Jayrock.dll and Jayrock.Json.dll and add references to them. Once you’ve finished that, we can continue to build our web service.

Open the handler you’ve created and modify the class to look something like this:

[csharp]public class my_service : Jayrock.JsonRpc.Web.JsonRpcHandler
{
	[Jayrock.JsonRpc.JsonRpcMethod("HelloWorld")]
	public string HelloWorld()
	{
		return "Hi iOS, this is ASP.NET!";
	}
}[/csharp]

  And now we’re ready. Try out this service in your browser, you should be able to see its description and test page. You can also test to see if it actually works, like this.
Jayrock RPC page

Jayrock RPC

If you see this, we’re completed JSON RPC web service in C# ASP .NET. In the next part of this blog, we’ll create an iOS app which will consume this service. Stay tuned!