It’s not everyday that I find myself in the land of Python, but I recently started working on a project with a friend’s company to help them reach an upcoming deadline.
The project uses Tastypie to generate an API based on Django models, which works great! However, when I wanted to return generic data I ran into a bit more resistance than expected.
The API pointed me to Using Tastypie With Non-ORM Data Sources, though I was hoping for something less heavy handed. I didn’t want to make resourceful routes around a custom data source, I just wanted to return a simple json object.
I ended up with the following solution:
# Custom object that we'll use to build our response. class CustomResourceObject(object): def __init__(self, name=None, label=None): self.label = label self.name = name # The Tastypie resource that will return our data. # Make sure to inherit from Resource instead of ModelResource. class CustomResource(Resource): # You will need to add fields for each property # that will be returned in the response. label = CharField(attribute='label', readonly=True) name = CharField(attribute='name', readonly=True) class Meta: # Start by disabling all routes for this resource allowed_methods = None # Allow the `get` index call where we will return data list_allowed_methods = ['get'] # Use the custom object we created above object_class = CustomResourceObject # API endpoint for this resource resource_name = 'custom_endpoint' # Create our array of custom data def get_object_list(self, request): return map(lambda val: CustomResourceObject(label=val, name=val), DjangoModel.CHOICES) # Return our custom data for the API call def obj_get_list(self, bundle, **kwargs): return self.get_object_list(bundle.request)
Photo via Visual hunt