Incerteza
Incerteza

Reputation: 34924

REST API in Django 1.7

Against all the odds, I couldn't find an example of how to build a simple "Hello world" REST API in Django (not in Django REST framework). So that a user makes a get request to, say,

my_app/api/v1/hello_world

they receive

{"hello": "world"}

Is there any? Or could you give it to me?

Upvotes: 0

Views: 191

Answers (1)

Mark Lavin
Mark Lavin

Reputation: 25164

There have been a number of examples of "Hello World" applications with Django. One in particular that I co-authored can be found here: http://radar.oreilly.com/2014/04/simplifying-django.html Here is an adapted example to produce the output you wanted:

from django.conf import settings
from django.conf.urls import url
from django.core.management import execute_from_command_line
from django.http import JsonResponse


settings.configure(
    DEBUG=True,
    SECRET_KEY='placerandomsecretkeyhere',
    ROOT_URLCONF=__name__,
    MIDDLEWARE_CLASSES=(),
)

urlpatterns = [
    url(r'^my_app/api/v1/hello_world/$',
        lambda request: JsonResponse({'hello': 'world'}))
]


if __name__ == "__main__":
    execute_from_command_line()

It required Django 1.7+ for the JsonRsponse but it would be easy to adapt to older versions using the HttpResponse. Save this as hello.py and you can run the server with python hello.py runserver. Hitting it with curl will produce:

$ curl -i http://localhost:8000/my_app/api/v1/hello_world/                                                         
HTTP/1.0 200 OK
Date: Thu, 27 Nov 2014 14:48:07 GMT
Server: WSGIServer/0.1 Python/2.7.3
Content-Type: application/json

{"hello": "world"}

However, this is just an exercise in code golf and an over-simplification of building a RESTful API. If you want to learn the basics of how Django routes requests to responses (mapping regex patterns to callables), this example can help. If you want to learn to build a meaningful REST API then Django REST framework is a fantastic tool for building robust and self-documenting APIs.

Upvotes: 2

Related Questions