Structuring a large API in a Django Project - django

Right now I have a large project with an equally large API (done using django rest framework). The current structure is something like this:
api
|-----urls.py
|-----models.py
|
----v1
|-----views.py
|-----serializers.py
|-----permissions.py
|-----tests.py
etc
As you can guess, the views.py file is pretty big and I want to refactor this out. Currently I have a few options in front of me, the one I'm leaning towards is to put an 'api/v1' package into each app and use the api app to tie all the urls together and hold views that don't fall into an app.
Does anyone have any experience with this and could provide guidance?

Yes, that's how we're doing it in the project I'm working on at the moment... have an api module under each app in your Django project

Related

Is separating django frontend and backend with API viable?

I'm used to Django and already developed website with a whole Django or with Django API + React.
For a side project, I'm thinking about creating a Django project with 2 apps:
Django API 2) Django Front.
I absolutely want to decouple front/back to be able to reuse the API in the future, and I like the view system from Django.
Is my idea making sense?
Edit 1:
To clarify.
App 1: Django API serving JSON.
App 2: Django App using API calls in the controllers to generate the views.
Edit 2:
I did a proof of concept and it works like a charm.
The only drawback is that I have to use Cookies to store the JWT token and maintain the session state, which is not convenient
it is possible, but completely wrong with idea.
How it possible. Wrong version:
Try to remember, how we can create integrate test for our view. We Should create client and send request to Django to your view-url with args kwargs querystring e.t.c.
In response you have already answer. Try to imagine: part with client - is your Django front, requested part - your backend.
The same works not only in test, you can create request to ask something on the completely other server.
Redis/MemCashed e.t.c. (pattern sender/receiver) Wrong version:
The Front Django speaks with Backend through Third part application. It can be faster.
"Pythonic" version. Right in your case:
You can create Backend Django part like a library with views as interfaces.
Frontend Django part is completely standalone, it import an use interfaces from library, which is your "BackEnd Module".
If you want - you can use "BackEnd Module" everywhere as import, or you can start it as server and ask info per requests.
Completely independent in this case means, you can install "BackEnd Module" without "FrontEnd Module". "FrontEnd Module" can be installed standalone too and it should take from settings, which interfaces should be used as data-source.
I hope, i am right understand your question.
You could definitely separate front and back, remember, django just creates endpoints and consumes them with its own views, you can even use both.
Here is the documentation for django views: https://docs.djangoproject.com/en/4.0/#the-view-layer
You can use a librarie like React as frontend and connect to your api(django app) and use both.

Implementing MVC pattern with Django Rest Framework

I was wondering how could I implement a MVC pattern on a Django Api project, when I start a django project it gives me the apps.py, admin.py, models.py and the views.py , I understand the the models, should be the "M", and the views the "V", but as i'm using the project like an api, the view would be an Angular or React App, so where I put the logical ? Where is the right place to put the "C" controller on a django rest framework project, is it on views.py ?
You need to understand that web service (which you are going to implement with Django) and your client app (which you are going to implement with Angular) are totally different apps and they should not depend on each other. These apps will have their own Models, Views and Controllers.
If we are talking about some business logic that you need to store somewhere on a backend then you can use an approach where you will have an additional level (usually, people call it services.py) and you will import code from this layer to views.py and only call it there cause your views should stay clean and simple as much as possible.
In an ideal case, especially, at the start, I guess, you will not have some tricky logic and mostly your API will look like simple CRUD, so for that case, you even don't need to store additional logic somewhere you just can use rest framework ViewSets as is and store some little snippets in utils.py.
The bottom line is - you don't understand fundamentals that's why you asked the wrong question. And you don't need it right now. Just go and write your app and read the docs about frameworks that you are using, eventually, you will understand this topic.

What is the preferred layout when dealing with apps using DjangoRestFramework for a ReSTful API?

According to this StackOverflow post: DjangoRestFramework - How do I customize the frontend?
it says "Typically you want to put your DjangoRestFramework REST Api in something like /api". I'm not sure what this means, so I did some more browsing.
In this GitHub project: https://github.com/kevinastone/django-api-rest-and-angular there is an /example/ folder and inside the folder there is a folder called /api/ which has api.py and serializers.py. I've never come across a tutorial which ever told me to create an api.py file and to place an /api/ folder inside the app (it looks like the app is called "example" in the GitHub project).
I've watched this tutorial: https://godjango.com/41-start-your-api-django-rest-framework-part-1/ and it seems as if the instructor created an app called "api" which has serializers.py and urls.py. With that said, different tutorials show different things. What's the preferred way of creating a Django app which uses the DjangoRestFramework for a ReSTful API?
My end goal is to create a Django app with DjangoRestFramework and AngularJS on the frontend.
I'm sure you've already figured this out, but for other people that stumble upon this he's including his api as it's own django 'app', just like in the tutorial you mentioned. His file "api.py" is basically, for all intents and purposes, serving as what most tutorials call "views.py". But as it is where he declares the methods for his api, and not the applications views, calling it "api.py" is clear cut and makes sense. Doesn't matter what you call it so long as it's imported and used appropriately. The best way to make a rest framework is to use paths that are reflexive of their use case. 'api/post_images' for instance, would post an image and not post a comment or retrieve a user's profile information.
If you only have one rest api call, you may not be interested in holding your single api method in it's own designated file. But as your application grows the use this convention will prove its value.

Turning a usual django website into a RESTful api

I've been working on. A web project for few months now.And it's a simple website with usual django models views urls and templates,with simple Ajax using jquery for the templates.
Now thinking of having a possibility of making an application soon. I am thinking of using Tastypie to make a RESTful api for my website. So the idea is to
Use Tastypie to make a RESTful api.
Using backbone.js to make my website a single page application
Using plist and json for my android and ios applications.
My concern starts here, with this new course of action, would. I have to make most of my website again? And if that is the case should I stop working on what I've already made and then start from scratch following the above guidelines? Again, in context to tastypie and backbone.js, what would happen to my already written views and template logic?
I've been reasearching over this topic alot and cannot find a definitive answer. So thought of asking all of you who are already experienced or have gone through the same transition.
I have almost no exposure to RESTful APIs. But I am getting inclined towards a RESTful approach as it would make app development easier.
PS. I would really appreciate if I don't get negative votes for it, but advice instead.
You could try it out side by side in the same site/project. Keep the existing django views. Add new tastypie ones under a different URL, for instance "/api/".
Likewise, a single page app? That is just one new template next to the existing ones. Keep it at "/single/" for the moment. And keep the existing pages.
The actual functionality will probably stay the same. Extract useful code as separate functions out of your existing views and call them from both tastypie and your original views. This will probably even make your existing code clearer and cleaner :-)
I'd say it's much of a philosophical question.
If the site is on a deadline or in production I would probably put it in git and give it two head branches:
production branch
refactor branch
The benefit then is that you can keep the old site up and add new features and merge this in your refactor branch.
Then again it much depends on the complexity and how the site acts today.
Doing the two branch system will give you the option to stop the refactor without losing your old version.

Django and Restful APIs

I have been struggling with choosing a methodology for creating a RESTful API with Django. None of the approaches I've tried seem to be the "silver" bullet. WAPI from http://fi.am is probably the closest to what I would like to accomplish, however I am not sure if it is acceptable in a true RESTful API to have parameters that are resource identifiers be in the querystring instead of in a "clean" URL format. Any suggestions for modifying WAPIs RestBinding.PATTERN to "clean" up the URLs? Another option I've explored is Django-Rest-Interface. However this framework seems to violate one of the most important pieces I need, and that is to include the full resource URL for references to other resources (see http://jacobian.org/writing/rest-worst-practices/ Improper Use of Links). The final option is to use django-multiresponse and basically do it the long way.
Please offer me your best advice, especially people that have dealt with this decision.
For Django, besides tastypie and piston, django-rest-framework is a promising one worth mentioning. I've already migrated one of my projects on it smoothly.
Django REST framework is a lightweight REST framework for Django, that
aims to make it easy to build well-connected, self-describing RESTful
Web APIs.
Quick example:
from django.conf.urls.defaults import patterns, url
from djangorestframework.resources import ModelResource
from djangorestframework.views import ListOrCreateModelView, InstanceModelView
from myapp.models import MyModel
class MyResource(ModelResource):
model = MyModel
urlpatterns = patterns('',
url(r'^$', ListOrCreateModelView.as_view(resource=MyResource)),
url(r'^(?P<pk>[^/]+)/$', InstanceModelView.as_view(resource=MyResource)),
)
Take the example from the official site, all above codes provide api, self explained documentation (like soap based webservice) and even sandboxing for testing. Very convenient.
Links:
http://django-rest-framework.org/
I believe the recently released django-piston is now the best solution for creating a proper REST interface in Django. django-piston
Note: django-piston seems to no longer be maintained (see comments below)
django-tastypie is a good way to do it, their slogan: "Creating delicious APIs for Django apps since 2010" is pretty comforting ;)
You could take look at django-dynamicresponse, which is a lightweight framework for adding REST API with JSON to your Django applications.
It requires minimal changes to add API support to existing Django apps, and makes it straight-forward to build-in API from the start in new projects.
Basically, it includes middleware support for parsing JSON into request.POST, in addition to serializing the returned context to JSON or rendering a template/redirecting conditionally based on the request type.
This approach differs from other frameworks (such as django-piston) in that you do not need to create separate handlers for API requests. You can also reuse your existing view logic, and keep using form validation etc. like normal views.
I don't know if this project can be useful for you, but sending a link can hardly hurt. Take a look at django-apibuilder , available from http://opensource.washingtontimes.com/projects/django-apibuilder/ . Perhaps it can be useful?
/Jesper
Have a look at this RestifyDjango.
Somewhat related are Django XML-RPC and JSON-RPC.
https://github.com/RueLaLa/savory-pie
Savory Pie is a REST framework that supports django.
I would suggest you look into Django Rest Framework (DRF), play around with this and see if it suits your requirements. The reason I recommend DRF is because it makes making the API views really simple with the use of GenericAPIView classes, Mixin Classes and Mixed in Generic views. You can easily make use of tried and tested design patterns for making your API endpoints as well as keeping your code base neat and concise. You also DRY when writing your code which is always great. Your API views are literally 2-3 lines long.
You can checkout this tutorial http://programmathics.com/programming/python/django-rest-framework-setup/ that begins from setting up your environment to going through the different ways to make your RESTful API using the django rest framework.
Disclaimer: I am the creator of that website.