I've been using django-tastypie recently to create restful apis and i wanted to use it especially with an android client.
I've put together a sample application,
django rest backend and an android client to demonstrate this.
So here is a quick walk through of the code.
Here is the models.py which describes a recipe.
from django.db import models
class Recipe(models.Model):
name = models.CharField(max_length=50)
content = models.TextField()
def __unicode__(self):
return self.name
We set up a Resource for our API using tastypie.
from tastypie.resources import ModelResource
from recipes.models import Recipe
class RecipeResource(ModelResource):
class Meta:
queryset = Recipe.objects.all()
resource_name = 'recipes'
allowed_methods = ['get']
include_resource_uri = False
def alter_list_data_to_serialize(self, request, data_dict):
if isinstance(data_dict, dict):
if 'meta' in data_dict:
#Get rid of the meta object
del(data_dict['meta'])
return data_dict
Now we set up the urlpattern to access the data
from django.conf.urls.defaults import patterns, include, url
from recipes.api.api import RecipeResource
from django.contrib import admin
admin.autodiscover()
recipe_resource = RecipeResource()
urlpatterns = patterns('',
url(r'^api/', include(recipe_resource.urls)),
url(r'^admin/', include(admin.site.urls)),
)
Test the api using curl.
$ curl -H 'Accept: application/json' http://localhost:8000/api/recipes/
Now that the api works as expected the next part is to create an android app client to consume the api.
This will be a simple app for viewing recipes.Later we will add the ability to add recipes to our recipe
database from the android client.
This will be covered in part 2 of this tutorial.
No comments:
Post a Comment