Search code examples
djangoresttastypiedjango-rest-framework

Django: return query result as api


I'm trying to build an API server using Django. I have a few tables and I need to run queries based on the parameters passed in by url:

http://server.com/api/request/p1=123&p2=321...

and the server would extract p1 and p2 from url and run queries using them, and then return the result in json or xml.

I have tried Tastypie, and it's very easy to set up for retrieving data from one model. But my case is a bit complicated than that, and sometimes I need to run spatial queries. So if I could run the query and return result as json/xml, it would be great!

Very new to the backend technology, any help for a start point is appreciated!

Thanks!

[Edit] Just want to make my case clearer. Say I ran a raw query using qs = cursor.execute(sql), etc., and I want to return that result as json/xml to a api call. Can I do that with either Tastypie or Rest Framework? Or can I do it without any help from 3rd party framework?


Solution

  • Here's a view I use return json, you should be able to adapt it pretty easy:

    import json
    from django.http import HttpResponse
    from django.template.defaultfilters import slugify
    from .models import *
    
    def response_times(request):
        response_data = {}  #Create an empty dictionary
        websites = Website.objects.all()  #Query your models
        for site in websites:  
            key = slugify(site.name)
            response_data[key] = {}
            history = History.objects.filter(website=site)[:60]
            response_data[key]['response_times'] = []
            for response in history:
                response_data[key]['response_times'].append({'time': str(response.time), 'timestamp': response.added.strftime('%s')}) 
        return HttpResponse(json.dumps(response_data), content_type="application/json")