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

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.

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.

Restful routes and Django

I'm in a process of migrating Rails project into Django. Rails project was built using restful routes and it never touches the database. Instead, it simply redirects to different methods which all call an external service with the specified action method. Now, I have found a number of frameworks for django that provide restful capability plus a bunch of bells and whistles, but it's an overkill for my current case.
As an alternative, I can ignore action method in urls.py by simply providing a regex to validate urls and then parse the request method in views.py, redirecting to the appropriate method. Is this a way to go or are there any other approaches that I can look at?
Class based views look like the idiomatic way to organize restful view functions by request method.
Django snippets has several simple example implementations.

Django: One project for integrated blog, forums, and custom web app?

Im still fairly new to Django, so please explain things with that in
mind.
I'm trying to create three websites using 2 subdomains and 1 domain:
for the blog, blog.mysite.com
for the forums, forums.mysite.com
for the custom web app, mysite.com
When building the custom web app, I used contrib.auth to make use of
the built-in django provided user models and functionality.
For the forums, I am planning on using SNAPboard (http://
code.google.com/p/snapboard/) with minimal, if any, modifications. On
initial inspection, it looks like it also uses contrib.auth users.
For the blog, I will probably be rolling my own lightweight blogging
app (since that seems to be the Django way and, also, b/c as Bennet
mentions, there is no killer Django Blog app)
Currently, I am considering two features that require some integration
between the three sites. First, I want to have the users of the custom
web app to use the same account to also log into the forums. Second, I
also (but I haven't figured out how I'm going to do this yet) would
like my blog posts to automatically become a topic for discussion in
the forums (this is just an idea I had, I might end up dropping it).
Ok, so to my questions:
1) Again, I'm new to Django, but this integration leads me to believe
the three websites need to be all under one project. Is this correct?
2) How would I accomplish the url structure for the websites that I
described above (blog.mysite.com, etc)? In the project's urls.py, I
don't know how to filter off of subdomains. If it was mysite.com/
forums/, that would be easy, but I don't know how to to catch
forums.mysite.com and forward it to the appropriate Django app.
3) Would I have to make use of the django.contrib.sites framework? I
don't understand that framework fully, but it seems like it's used
when two different websites are using the same django app in the
background. Whereas my three websites are all using different django
apps, but I want them to share a little bit of data.
Thanks for your help.
1) Yes, it's only true way for that
2) Use middleware
3) No, you don't need it.

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.