geeks
geeks

Reputation: 2055

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-498b-bc69-ba39396ada4f"},{"Name": "test1", "ID":"1114cb76-f3df-4c60-8b12-5ad14224ffbd"}]}

Name           ID
test2          7a3a2eab-7d3b-498b-bc69-ba39396ada4f
test1          1114cb76-f3df-4c60-8b12-5ad14224ffbd
ce-2           8b97b82b-a9e4-4fe0-adcb-eeaaac170301
ce-1           afaa50ad-8025-415b-81c4-566c8e06f388

I am getting the above data from api.nova.server_list(self.request). I tried to write following code to convert data into json data in python+django, but didn't succeeded.

   class InstanceList(django.views.generic.View):
    def get(self, request, *args, **kwargs):
          instances=api.nova.server_list(self.request)
          def serializer(m):
              ret= {} 
              ret['Name']= m.name
              ret['Id']=m.id
          context= {
              'instances': [serializer(m) for m in instances],
          }
          return HttpResponse(json.dumps(context), content_type='application/json')

Upvotes: 0

Views: 210

Answers (2)

thecodesmith_
thecodesmith_

Reputation: 1312

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/

Upvotes: 1

Arpit Goyal
Arpit Goyal

Reputation: 2254

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')

Upvotes: 1

Related Questions