Building APIs with Django and Django Rest Framework Release 2.0 Agiliq Aug 07, 2021 Contents 1 Introductions 3 1.1 Whoisthisbookfor? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.2 Howtoreadthisbook? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2 Setup,ModelsandAdmin 5 2.1 Creatingaproject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 2.2 Databasesetup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 2.3 Creatingmodels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2.4 Activatingmodels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3 AsimpleAPIwithpureDjango 9 3.1 TheendpointsandtheURLS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 3.2 Connectingurlstotheviews . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 3.3 Writingtheviews. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3.4 UsingtheAPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3.5 WhydoweneedDRF?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 4 SerializingandDeserializingData 13 4.1 SerializationandDeserialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 4.2 CreatingSerializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 4.3 ThePollSerializerindetail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 4.4 UsingthePollSerializer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 5 ViewsandGenericViews 17 5.1 CreatingViewswithAPIView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 5.2 UsingDRFgenericviewstosimplifycode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 5.3 Moregenericviews . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 5.4 NextSteps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 6 Moreviewsandviewsets 25 6.1 AbetterURLstructure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 6.2 Changingtheviews . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 6.3 IntroducingViewsetsandRouters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 6.4 Choosingthebaseclasstouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 6.5 Nextsteps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 7 AccessControl 31 i 7.1 Creatingauser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 7.2 Authenticationschemesetup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 7.3 TheloginAPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 7.4 Finegrainedaccesscontrol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 7.5 Nextsteps: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 8 TestingandContinuousIntegeration 37 8.1 CreatingTestRequests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 8.2 TestingAPIswithauthentication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 8.3 UsingAPIClient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 8.4 .postandcreate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 8.5 ContinuousintegrationwithCircleCI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 8.6 SettingupCircleCI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 8.7 Writingcircleconfigurationfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 9 Appendix 45 9.1 TestingandUsingAPIwithPostman . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 9.2 DocumentingAPIs(withSwaggerandmore) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 ii BuildingAPIswithDjangoandDjangoRestFramework,Release2.0 BuildingAPIswithDjangoandDRFtakesoverwheretheDjangotutorialsstop. IntheDjangotutorials,youbuilta regularDjangopollsapp. WewillrebuildanAPIforasimilarapp. In the chapters to come, we will build a REST(ish) api with authorization, rate limiting, first with pure Django and thenwithDRF.Wewillcovertesting,continuousintegration,documentationtoolsandAPIcollaborationtools. Chapters: Contents 1 BuildingAPIswithDjangoandDjangoRestFramework,Release2.0 2 Contents 1 CHAPTER Introductions BuildingAPIswithDjangoandDjangoRestFrameworkstartswheretheDjango“Polls”tutorialstops,andtakesyou throughbuildingthepollsapp,butthistimeusingAPIs.YouwilllearnthebasicsofDjangoRestFrameworkincluding serialization, views, generic views, viewsets, testing, access control. You will also learn about API documentation usingswaggerandraml. 1.1 Who is this book for? IfyouhavefinishedtheDjango“Polls”tutorial, andwanttolearnusingDRFtobuildAPIs, thisbookisperfectfor you. ThisbookassumessomeknowledgeofDjangoandPython,whichyoushouldhavebuiltifyouhavefinishedthe “Poll”turtorial. NoexistingknowledgeofDRFisassumed. 1.2 How to read this book? The chapters are meant to be read in order. If you have existing knowledge of some chapters, you can quickly go throughthatchapter,butIhighlyrecommendreadingtheminorderaseachchapterbuildsontheprevious. 3 BuildingAPIswithDjangoandDjangoRestFramework,Release2.0 4 Chapter1. Introductions 2 CHAPTER Setup, Models and Admin InthistutorialwewillwalkthroughaprocessofcreatinganAPIforabasicpollapplication. WewillbeusingPython 3.6.x,Django2.0.xandDjangoRestFramework3.7.xforcreatingAPI. Firstthingsfirst,let’sinstalltherequiredmoduleswithinavirtualenvironment. mkvirtualenv pollsapi pip install Django pip install djangorestframework 2.1 Creating a project Earliestinorder,tocreateaprojectweshouldmovetothedirectorywherewewouldliketostoreourcode. Forthis gotocommandlineandusecdcommand. Thentriggerthestartprojectcommand. django-admin startproject pollsapi Thiscommandgivesusa‘pollsapi’directoy. Thecontentsofthisdirectorylooklikethis: manage.py pollsapi/ __init__.py settings.py urls.py wsgi.py 2.2 Database setup We will use SQlite database, which is already included with Python. The pollsapi/settings.py file would alreadyhavethecorrectsettings. 5 BuildingAPIswithDjangoandDjangoRestFramework,Release2.0 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Now, use the migrate command which builds the needed database tables in regard to the django_pollsapi/ settings.pyfile. python manage.py migrate 2.3 Creating models Beforecreatingourdatabasemodels,letuscreateourpollsapiApp. python manage.py startapp polls Theabovecommandresultsina‘polls’directorycontainingdifferentfiles: admin.py apps.py models.py tests.py views.py Stepinto‘models.py’fileandstartwritingthemodels.ForcreatingthepollsapiwearegoingtocreateaPollmodel, aChoicemodelandaVotemodel. Oncewearedonewithdesigningourmodels,themodels.pyfileshouldlook likethis: ThesemodelsarethesameasyouwouldhaveseenintheDjangointroductiontutorial. from django.db import models from django.contrib.auth.models import User class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) def __str__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll, related_name='choices', on_delete=models.CASCADE) choice_text = models.CharField(max_length=100) def __str__(self): return self.choice_text class Vote(models.Model): choice = models.ForeignKey(Choice, related_name='votes', on_delete=models.CASCADE) (continuesonnextpage) 6 Chapter2. Setup,ModelsandAdmin
Description: