Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consuming a RESTful API with Django

I'm building a Django application that needs to interact with a 3rd party RESTful API, making various GETs, PUTs, etc to that resource. What I'm looking for is a good way to represent that API within Django.

The most obvious, but perhaps less elegant solution seems to be creating a model that has various methods mapping to webservice queries. On the other hand, it seems that using something like a custom DB backend would provide more flexibility and be better integrated into Django's ORM.

Caveat: This is the first real project I've done with Django, so it's possible I'm missing something obvious here.

like image 690
devights Avatar asked May 14 '12 20:05

devights


People also ask

Is Django GOOD FOR REST API?

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.

Why do we use REST API in Django?

Main advantages of Django REST framework: Simplicity, flexibility, quality, and test coverage of source code. Powerful serialization engine compatible with both ORM and non-ORM data sources. Pluggable and easy to customise emitters, parsers, validators and authenticators.

Which is better for REST API Flask or Django?

Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs. On the other hand, Flask is detailed as "a microframework for Python based on Werkzeug, Jinja 2 and good intentions". Flask is intended for getting started very quickly and was developed with best intentions in mind.


2 Answers

The requests library makes it easy to write a REST API consumer. There is also a Python library called slumber, which is built on top of requests, for the explicit purpose of consuming REST APIs. How well that will work for you likely depends on how RESTful the API really is.

like image 90
Mark Lavin Avatar answered Oct 16 '22 21:10

Mark Lavin


Make the REST calls using the builtin urllib (a bit clunky but functional) and wrap the interface into a class, with a method for each remote call. Your class can then translate to and from native python types. That is what I'd do anyway!

like image 27
Nick Craig-Wood Avatar answered Oct 16 '22 22:10

Nick Craig-Wood