Proper way to consume data from RESTFUL API in django Proper way to consume data from RESTFUL API in django python python

Proper way to consume data from RESTFUL API in django


I like the approach of putting that kind of logic in a separate service layer (services.py); the data you are rendering is quite not a "model" in the Django ORM sense, and it's more than simple "view" logic. A clean encapsulation ensures you can do things like control the interface to the backing service (i.e., make it look like a Python API vs. URL with parameters), add enhancements such as caching, as @sobolevn mentioned, test the API in isolation, etc.

So I'd suggest a simple services.py, that looks something like this:

def get_books(year, author):    url = 'http://api.example.com/books'     params = {'year': year, 'author': author}    r = requests.get(url, params=params)    books = r.json()    books_list = {'books':books['results']}    return books_list

Note how the parameters get passed (using a capability of the requests package).

Then in views.py:

import servicesclass BooksPage(generic.TemplateView):    def get(self,request):        books_list = services.get_books('2009', 'edwards')        return render(request,'books.html',books_list)

See also:


Use the serializer instead of .json, as it gives flexibility to return in a number of formats.As while using rest-api , the provided serializer use is preferred.

Also keep the data handling and get data requests in view.py.The forms are used for templating not as the business logic.


Well, there are several things to keep in mind. First of all, in this case your data is not changing so often. So it is a good practice to cache this kind of responces. There are a lot of caching tools around, but redis is a popular option. Alternatevly, you can choose additional NoSQL database just for caching.

Secondly, what is the purpose of displaying this data? Are you expecting your users to interact with books or authors, etc? If it is just an information, there is no need in forms and models. If not, you must provide proper views, forms and models for both books and authors, etc.

And considering the place where you should call an API request, I would say it dependes heavily on the second question. Choices are:

  • views.py for just displaying data.
  • forms.py or still views.py for ineractivity.