When to use RESTful APIs in a Django project - django

My project
I have a backend web application written with Django and a mobile application written with HTML/CSS/jQuery and wrapped in PhoneGap. I need the mobile app to communicate with the web app and I first thought I would build my own REST API.
My understanding
WSGI is a specification (based on HTTP) that defines how to handle communications between a web server and a Python application, basically how to translate HTTP requests into Python objects and vice versa. All we need to provide to the WSGI server (gunicorn for instance) is a WSGI application. In Django we will typically have a wsgi.py file at the root of the project with
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
So Django has a built-in support for the WSGI specification and we, programmers, do not even have to think about how our application interfaces with the web server. Nice.
REST is an architecture style based on 6 constraints defining how data are transmitted between components within a program or separated programs (not necessarily web applications). A RESTful API is an API that fulfills those constraints. I heard that there is a whole framework for Django, surprisingly called django-rest-framework, that helps developers to build REST APIs.
My questions
Hey, why would I need a REST API if the WSGI application already provides a way to parse HTTP requests and return responses? I mean, since my mobile application is nothing less than an embedded webpage, why can't I just use regular urls to access my web application and return HTML code that depends on the type of device that sent the request?
If indeed a REST API is not needed in this case, what is the purpose of a REST API in a Django project? When is it useful?

Well as far as using Django Rest Framework is it has support built in to handle a lot of things like throttling, serializing and de-serializing django query sets into json and back again. It's got built in support to work with django's auth system.
As far as not using it, I suppose there is nothing wrong with having django view methods peruse posted data and serialize to and from json to send responses back, handle authentication, authorization and throttling etc...However that is a crap load of code which you will ultimately need to write for any api and not having to do that is a huge break.
Another benefit to using something like Django Rest Framework is the contribution from the community. Major companies and small companies use it alike. Typically the purpose of an API is to have external parties consume it. Something like Django Rest Framework tries to follow best practices in this regard making it easier for your customers to consume your api.

Related

Running a meteor app as part of a wider django project

I'm currently working on a project which would require some realtime functionalities such as Multi-user chatrooms etc.
Ideally, I’m looking to have meteor run the chat application(on a different port) and mongodb act as message broker to the django back-end which would take care of user registration , management and everything 'non-realtime' related.
This would involve setting up a reverse-proxy which would redirect to a different port based on the url (please let me know if i'm wrong in this)
Would this be possible(or even advisable)? Another option would be to implement the same with tornado. but I have no experience with building tornado-based apps and rather do this with a framework I’m comfortable with.
Thanks,
You can have Django serve the Meteor front-end while providing access to its data using django-ddp, giving you some distinct advantages:
Continue to serve your existing Django project/apps.
No extra services or ports to manage.
Scale out by simply adding more front-end Python/Django servers (server to server IPC is done via the existing database connection).
Use django.contrib.auth user accounts in your Meteor app.
Familiar Python/Django code (no "callback" style such as with Tornado).
Use time-tested, trusted relational databases.
Use Django migrations to effectively manage schema changes.
There's a Gitter chat room where I can give you assistance if you need it.
DISCLAIMER: I'm the author of django-ddp.
A meteor application is more than capable of handling the user registration flow and many other things. Why not just build the application entirely in meteor? Your application sounds like a perfect candidate for meteor, with realtime interaction with your database at the core.
The other option would be to use swampdragon which adds realtime data binding within django. It allows for simple bi directional communication between the server and the client. Again, essential for a chat application. It nice and easy to get setup and running as well.
Are there any specific reasons to not implementing your application in one framework alone?

communication method between django <-> application server (node.js)?

A client talks to Django, and django uses node.js to do some javascript related work to give back the client a http response.
I wonder how I should set up the link(?) between the django and node.js.
Simply, I could use python's requests library and talk http, but is this best I can do?
If I were to build the communication link in c++, I would create non-block socket with Send/Recv Thread and use mutex(or similar) between the django view code and the send/recv thread.
I guess that's what is called asynchronous io in node.js world.
Is there a similar thing in python so that I could use on django side to talk to another server?
I heard many big companies use Thrift, would it fit here?
I also see gevent might be relevant keyword here, but not sure.
I am not sure if my answer is still relevant, but I'll give it a try.
IMHO, the best solution for you would be to have a RESTful API for your Django app. This has several advantages:
it provides a lot of decoupling between your Django app and your Node.js one, so in case you ever want to reuse any of them or to replace one of them, it will be easy
it allows you to design an API for each of them and to hide the rest of your implementation (your Django app should not care how Node.js does its job, but only the response that it provides)
there are many great frameworks out there that can help you quickly build your APIs (at leat for Django there is Django REST framework)
If you don't want to build a RESTful API, python's request library is probably the best and easiest way.
Good luck.

Deviding Django application (social network) to Django Frontend and RESTfull API

I'm writing Django application (social network) and thinking about dividing monolithic project to two projects: UI and API. For example, Django will be used only to render pages, interacting with and taking data from API, written on web.py.
Pros are following:
I can develop and test API independently.
In the future, other UI can appears (mobile, for example), it will require service.
I plan to outsource web UI developing, so, if my application will have two modules, I can provide outside only UI one, not sharing logic of application.
Cons are following:
I'm working alone, and developing two projects are harder, then one.
I will not be able to use cool Django admin panel. I will need to write my own.
web.py is more low-level comparing with Django.
It's like a brain dump, but I will be really appreciated if you share your experience in creating web application with UI module and independent API module.
Update (more specific question, as Mike asked)
What Python framework will you use for creating REST API of social network, which can be used by different client applications? Is using web.py that returns JSON only and rendering it by Django for web is good idea?
Thanks,
Boris.
I've been in a situation similar to yours. I ended up writing both, the UI and the API part in Django. Currently, I am serving them both out of the same process/project. You mentioned you wanted to be able to outsource the UI development, but do hear me out.
In the meantime, I have used django-piston to implement the RESTful front end, but a bit of preparation went into it:
Encapsulate all DB and ORM accesses into a library. You can do that either for your entire project, or on an app by app basis. The library is not just a low-level wrapper around your DB accesses, but also can be for higher-level 'questions', such as "all_comments_posted_by_friends()" or something. This accomplishes two things:
You can call your pre-canned queries from UI views as well as API views without having to re-implement them in multiple places.
You will later be able to replace some - if not all - of the underlying DB logic if you ever feel like going to a NoSQL database, for example, to some other distributed storage model. You can setup your entire app of this ahead of time, without actually having to worry about the complicated details of this right at the start.
The authentication layer for the API was able to accept an HMAC/token based header for programmatic access and normal Django auth. I setup the views in such a way that they would render plain JSON for the programmatic clients (based on content-type), and would render the data structure in HTML (with clickable links and clickable docstrings) if browsed by a human from a browser. This makes it possible that the API is fully explorable and clickable by a human without having to read any docs, while at the same time it can be easily processed by a client just via JSON.
On effect, the database layer I build serves as the internal API. This same database layer can be used from multiple applications, multiple processes, if you wish to do so. The UI views and the REST views were both implemented in Django. They can either be in the same process or in separate processes (as long as they have access to the same database right now).

Appropriate back-end for a single-page web application?

Historically I've mainly written web apps in Django, but now I'm increasingly finding that I want to write single-page web apps using Backbone.js or a similar JavaScript framework, with a back-end that solely consists of a database and an API.
My questions is this. If my application structure looks like this:
1. Database
|
v
2. API methods
|
v
3. Single-page front-end written with Backbone
and I'm most comfortable in Django - but also keen to learn new things too, such as NoSQL and Node, if they are appropriate - what would people recommend I use for (2)?
Typically I would use Django with Piston as the API app, but it seems rather heavyweight to have all of Django and only use it as an API provider. Perhaps I shouldn't be worrying, though.
If you use Django, which is an MVC framework, and use Backbone, you might be comfortable setting up your app in pure Node.js or Express.js, with additional modules for connecting to your choice of database.
With Express, if you plan to serve only JSON via RESTful interface, you don't even need to use Views, which is handy. You would only need to set up models and routes (that also serve as controllers).
Any server side framework or lang that is capable of supporting or providing for RESTful APIs should work. I myself as using Slim PHP right now. But seeing that you are from a Django/Python background perhaps this post would be helpful to you.
Recommendations of Python REST (web services) framework?

Should my web based app be a consumer of my api?

I will be developing a mobile app (iPhone) and a web based app (Django) soon. For the mobile app I will be creating a REST api (most likely using Django) to send data back and forth from phone to server.
When I comes time to create the web based version does it make sense to just create it as any other client of the api. In other words both the mobile app and the web app will get there data from an external API over HTTP. Or should the web based app have direct access to the database that the api is using and just get its data that way?
Break it into three "sections". The first uses a Python API to manipulate the database. The second interfaces your REST API with your Python API. The third talks web and uses the Python API.
I would create the web application to serve the API to the mobile client. That is, give the web based application direct access to the database. This will simplify your XML / JSON RESTful resource access.
I would say no, don't use the API for the HTML version. If you design your Django well, you can end up with less code than using the API for the HTML version. You also get to retain the ability to have a web designer work with the Django templates whenever the boss wants the spelling changed on something.
I'd suggest trying to define a base app for your iPhone app to interface with, and then extend that within a second app for the HTML version. App1 would have all of your models (including business logic), and a views.py for processing the data to/from the iPhone. Then create App2 which uses App1.models, but creates its own views.py. With any luck, you'll find yourself with the ability to change nothing but the template used to render the output, so you can reuse your views by passing the template as an argument.
For example:
App1.views:
def list(request, template="list.json"):
list = Model.objects.filter(deleted=False).filter(user=request.user)
list.reverse()
## Lots of other logic to work on the list.
return render_to_response(template, {list: list,})
App2.views:
def list(request, template="list.html"):
return App1.views.list(request, template=template)
I think the answer to this question has changed over time. A year ago when asked it was probably still too much hassle to do this, but now I'd definitely say yes - using your API as the basis is the smart thing to do. As Web sites use more HTML5 and Mobile apps get smarter it really makes sense to have all your "UIs" read/writing from the same API layer. This will give you much more flexibility in the future.