Joff
Joff

Reputation: 12187

what is the "proper" way to use django REST framework?

I went through the tutorial and I am working my way through the docs so I think I have a good understanding of how the system works and I can think of a few different ways to use it but I am curious about the "proper" way to use it because my instincts might be leading me the wrong way.

1) Should I setup an API and then have my other apps just interact with that?

In this case say it is a blog, would I create an API app /api that would define the models and the api structure which would be responsible for creating, modifying and destroying objects.

Then I would create another app which will display views and forms for authors to actually create blogposts and which would send http requests to the api. This view would also be responsible for letting other users view the blog posts by interacting with the API and retrieving the posts.

2) Would it be better to take care of all of this within the same API app somehow?

Should these scenarios all be covered from within the same views as the REST framework viewsets, etc

It feels like I have a handle on how it works, but not how to put all the pieces together. Thanks

Upvotes: 0

Views: 90

Answers (1)

Windsooon
Windsooon

Reputation: 7110

Should I setup an API and then have my other apps just interact with that?

You should create an API apps to put all your api in it.

Then I would create another app which will display views and forms for authors to actually create blogposts and which would send http requests to the api.

It depends, I used to do like what you said, but now I find out I don't actually have to write any code in the views.py For instance, You have a blog project.

  • Create two app, one is api, the other is blog.
  • Set your model in blog like this.

    class Blog(models.Model):
        blog_title = models.CharField(max_length=30, blank=True)
        blog_content = models.CharField(max_length=140)
    
  • In api app, use django-rest-framework to create class BlogList(generics.ListCreateAPIView) and class BlogDetail(generics.RetrieveUpdateDestroyAPIView) or other APIView and Serializers to handle CRUD for your blog so your don't have to write any code in blog's views.py

  • I will recommend to use Ajax to handle the form instead of django build-in form api. Like CRUD the blogs, just send Ajax call to api/blogs(you handle it in your APIView, use django-rest-framework to handle which field is read only or any other porperty.), sign up or sign in just call api/users. django form api is complicated if you have lots of form and you can't reuse it if you create a mobile app or use in other platform

Would it be better to take care of all of this within the same API app somehow?

Yes, it's easy to maintain your code like I said above.

Upvotes: 1

Related Questions