Appendix G. Django-Rest-Framework
Having ârolled our ownâ REST API in the last appendix, itâs time to take a look at Django-Rest-Framework, which is a go-to choice for many Python/Django developers building APIs. Just as Django aims to give you all the basic tools that youâll need to build a database-driven website (an ORM, templates, and so on), so DRF aims to give you all the tools you need to build an API, and thus avoid you having to write boilerplate code over and over again.
Writing this appendix, one of the main things I struggled with was getting the exact same API that Iâd just implemented manually to be replicated by DRF. Getting the same URL layout and the same JSON data structures Iâd defined proved to be quite a challenge, and I felt like I was fighting the framework.
Thatâs always a warning sign. The people who built Django-Rest-Framework are a lot smarter than I am, and theyâve seen a lot more REST APIs than I have, and if theyâre opinionated about the way that things âshouldâ look, then maybe my time would be better spent seeing if I can adapt and work with their view of the world, rather than forcing my own preconceptions onto it.
âDonât fight the frameworkâ is one of the great pieces of advice Iâve heard. Either go with the flow, or perhaps reassess whether you want to be using a framework at all.
Weâll work from the API we had at the end of the last appendix, and see if we can rewrite it to use DRF.
Installation
A
quick pip install ...
Get Test-Driven Development with Python, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.