Skip to content Skip to sidebar Skip to footer

Django : Create A Json For Rest-api

I want to create json data of following table. This table has two field Name and ID. I want to create the JSON data like => {'Instances': [{'Name': 'test2', 'ID':'7a3a2eab-7d3b-

Solution 1:

Assuming that:

instances = api.nova.server_list(self.request)

returns list of instances, I don't see a point defining a serializer function inside the get function.

With the instances simply create the dictionary as follows:

data_list = [{"Name" : instance.name, "ID" : instance.id} for instance in instances]

data = {"Instances" : data_list}

and then simply do:

return HttpResponse(json.dumps(data), content_type = 'application/json')

Solution 2:

I would highly encourage you to look at these resources for creating a REST API in Django:

Django Rest Framework: http://www.django-rest-framework.org/

Tastypie API: http://tastypieapi.org/

I have personally used Tastypie successfully to create a REST API returning JSON data from models. Here is a link to the Tastypie documentation to get started: https://django-tastypie.readthedocs.org/en/latest/

Post a Comment for "Django : Create A Json For Rest-api"