I’m new to python and just finished the django tutorial. I have a django powered site and I’m writing an android application which needs to send and receive data from the same database managed by django. The website and the application provide the same functionality, but I don’t want pages rendered for the application, I just want to send/receive commands and serialised objects. Essentially what I need to do is
receive http request (from mobile) in django ---> Run myProgram.py ---> Update database ---> send confirmation to client.
Could I have a few pointers about what/where to edit? Thanks.
It seems that you are trying to make an API with Django. You can read here more about REST APIs. The basic idea is that your web site will have a set of command links/urls – where each link will either do some action (update db, etc), just return some information (most commonly in JSON – e.g. return an object from db), or will do both.
What you will have to do is make a list of all possible commands the api will have to handle. That will include all the commands of retrieving, inserting, updating, and deleting data.
For this example, lets assume the only job of the application is to manage items in a store. This is a very simplified demo however it should get the point across.
Here is a Django model (within
Storedjango app):So then lets assume the possible commands for api are:
URL structure for all the commands
Getting info about all items
For getting information information from django, django serialization functions are very helpful. Here is a django docs for that.
What this will do is return a JSON array with all the items like so:
Adding new item
For this your android app will have to send a JSON object to the django.
JSON object:
So now your django app has to parse the info from the request in order to create a new item:
Some notes:
Note the use of the POST request type. This is very crucial in REST API’s. Basically depending on the request type, different actions will be done. This is going to be much more vivid in the next view.
Getting, updating, and removing
So what this method will be is do different actions according to the different request type.
Comments
Note that this is a very, very simple demo. It does not account for any error checking, user authentication, etc. But hopefully it will give you some ideas.