ebook img

Django for APIs: Build web APIs with Python and Django PDF

155 Pages·2020·5.352 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Django for APIs: Build web APIs with Python and Django

Django for APIs Build web APIs with Python and Django William S. Vincent Thisbookisforsaleathttp://leanpub.com/djangoforapis Thisversionwaspublishedon2020-08-13 ThisisaLeanpubbook.LeanpubempowersauthorsandpublisherswiththeLeanPublishing process.LeanPublishingistheactofpublishinganin-progressebookusinglightweighttools andmanyiterationstogetreaderfeedback,pivotuntilyouhavetherightbookandbuild tractiononceyoudo. ©2018-2020WilliamS.Vincent Also By William S. Vincent DjangoforBeginners DjangoforProfessionals Contents Introduction 1 Prerequisites 1 WhyAPIs 2 DjangoRESTFramework 3 Whythisbook 4 Conclusion 4 Chapter1:WebAPIs 5 WorldWideWeb 5 URLs 6 InternetProtocolSuite 7 HTTPVerbs 8 Endpoints 8 HTTP 9 StatusCodes 11 Statelessness 12 REST 12 Conclusion 13 Chapter2:LibraryWebsiteandAPI 14 TraditionalDjango 14 Firstapp 17 Models 19 Admin 21 Views 24 CONTENTS URLs 24 Webpage 27 DjangoRESTFramework 28 URLs 29 Views 30 Serializers 31 cURL 32 BrowsableAPI 33 Conclusion 34 Chapter3:TodoAPI 36 InitialSetUp 36 Models 40 DjangoRESTFramework 42 URLs 44 Serializers 45 Views 46 ConsumingtheAPI 48 BrowsableAPI 48 CORS 50 Tests 53 Conclusion 54 Chapter4:TodoReactFront-end 56 InstallNode 56 InstallReact 57 Mockdata 59 DjangoRESTFramework+React 63 Conclusion 66 Chapter5:BlogAPI 67 InitialSetUp 67 Model 68 CONTENTS Tests 72 DjangoRESTFramework 73 URLs 74 Serializers 76 Views 77 BrowsableAPI 78 Conclusion 82 Chapter6:Permissions 83 Createanewuser 83 AddlogintothebrowsableAPI 86 AllowAny 90 View-LevelPermissions 92 Project-LevelPermissions 94 Custompermissions 95 Conclusion 99 Chapter7:UserAuthentication 100 BasicAuthentication 100 SessionAuthentication 102 TokenAuthentication 103 DefaultAuthentication 105 Implementingtokenauthentication 106 Endpoints 108 dj-rest-auth 109 UserRegistration 114 Tokens 118 Conclusion 123 Chapter8:ViewsetsandRouters 125 Userendpoints 125 Viewsets 131 Routers 132 CONTENTS Conclusion 138 Chapter9:SchemasandDocumentation 139 Schemas 140 Documentation 142 Conclusion 146 Conclusion 147 NextSteps 147 GivingThanks 148 Introduction TheinternetispoweredbyRESTfulAPIs.Behindthesceneseventhesimplestonlinetaskinvolves multiplecomputersinteractingwithoneanother. AnAPI(ApplicationProgrammingInterface)isaformalwaytodescribetwocomputerscommu- nicatingdirectlywithoneanother.AndwhiletherearemultiplewaystobuildanAPI,webAPIs— whichallowforthetransferofdataovertheworldwideweb—areoverwhelminglystructuredin aRESTful(REpresentationalStateTransfer)pattern. InthisbookyouwilllearnhowtobuildmultipleRESTfulwebAPIsofincreasingcomplexityfrom scratchusingDjango1andDjangoRESTFramework2,oneofthemostpopularandcustomizable waystobuildwebAPIs,usedbymanyofthelargesttechcompaniesintheworldincludingInsta- gram,Mozilla,Pinterest,andBitbucket.Thisapproachisalsouniquelywell-suitedtobeginners becauseDjango’s“batteries-included”approachmasksmuchoftheunderlyingcomplexityand securityrisksinvolvedincreatinganywebAPI. Prerequisites Ifyou’rebrandnewto webdevelopmentwithDjango, Irecommendfirst readingmyprevious book Django for Beginners3. The first several chapters are available for free online and cover proper set up, a Hello World app, and a Pages app. The full-length version goes deeper and coversaBlogwebsitewithformsanduseraccountsaswellasaproduction-readyNewspaper sitethatfeaturesacustomusermodel,completeuserauthenticationflow,emails,permissions, deployment,environmentvariables,andmore. ThisbackgroundintraditionalDjangoisimportantsinceDjangoRESTFrameworkdeliberately mimicsmanyDjangoconventions. 1https://www.djangoproject.com/ 2http://www.django-rest-framework.org/ 3https://djangoforbeginners.com/ Introduction 2 It is also recommended that readers have a basic knowledge of Python itself. Truly mastering Pythontakesyears,butwithjustalittlebitofknowledgeyoucandiverightinandstartbuilding things. Why APIs Djangowasfirstreleasedin2005andatthetimemostwebsitesconsistedofonelargemonolithic codebase.The“back-end”consistedofdatabasemodels,URLs,andviewswhichinteractedwith the“front-end”templatesofHTML,CSS,andJavaScriptthatcontrolledthepresentationallayout ofeachwebpage. Howeverinrecentyearsan“API-first”approachhasemergedasarguablythedominantparadigm inwebdevelopment.Thisapproachinvolvesformallyseparatingtheback-endfromthefront- end.ItmeansDjangobecomesapowerfuldatabaseandAPIinsteadofjustawebsiteframework. TodayDjangoisarguablyusedmoreoftenasjustaback-endAPIratherthanafullmonolithic websitesolutionatlargecompanies! Anobviousquestionatthispointis,“Whybother?”TraditionalDjangoworksquitewellonitsown andtransformingaDjangositeintoawebAPIseemslikealotofextrawork.Plus,asadeveloper, youthenhavetowriteadedicatedfront-endinanotherprogramminglanguage. Thisapproachofdividingservicesintodifferentcomponents,bytheway,isbroadlyknownas Service-orientedarchitecture4. It turns out however that there are multiple advantages to separating the front-end from the back-end. First, it is arguably much more “future-proof” because a back-end API can be consumed by any JavaScript front-end. Given the rapid rate of change in front-end libraries– React5 was only released in 2013 and Vue6 in 2014!–this is highly valuable. When the current front-end frameworks are eventually replaced by even newer ones in the years to come, the back-endAPIcanremainthesame.Nomajorrewriteisrequired. Second,anAPIcansupportmultiplefront-endswrittenindifferentlanguagesandframeworks. Consider that JavaScript is used for web front-ends, while Android apps require the Java 4https://en.wikipedia.org/wiki/Service-oriented_architecture 5https://reactjs.org/ 6https://vuejs.org/ Introduction 3 programminglanguage,andiOSappsneedtheSwiftprogramminglanguage.Withatraditional monolithic approach, a Django website cannot support these various front-ends. But with an internalAPI,allthreecancommunicatewiththesameunderlyingdatabaseback-end! Third, an API-first approach can be used both internally and externally. When I worked at Quizlet7 backin2010,wedidnothavetheresourcestodevelopourowniOSorAndroidapps. ButwedidhaveanexternalAPIavailablethatmorethan30developersusedtocreatetheirown flashcardappspoweredbytheQuizletdatabase.Severaloftheseappsweredownloadedover amilliontimes,enrichingthedevelopersandincreasingthereachofQuizletatthesametime. Quizletisnowatop20websiteintheU.S.duringtheschoolyear. The major downside to an API-first approach is that it requires more configuration than a traditionalDjangoapplication.Howeveraswewillseeinthisbook,thefantasticDjangoREST Frameworklibraryremovesmuchofthiscomplexity. Django REST Framework Therearehundredsandhundredsofthird-partyappsavailablethataddfurtherfunctionalityto Django.Youcanseeacomplete,searchablelistoveratDjangoPackages8,aswellasacurated list in the awesome-django repo9. However, among all third-party applications, Django REST Framework is arguably the killer app for Django. It is mature, full of features, customizable, testable, and extremely well-documented. It also purposefully mimics many of Django’s tra- ditional conventions, which makes learning it much faster. And it is written in the Python programminglanguage,awonderful,popular,andaccessiblelanguage. IfyoualreadyknowDjango,thenlearningDjangoRESTFrameworkisalogicalnextstep.Witha minimalamountofcode,itcantransformanyexistingDjangoapplicationintoawebAPI. 7https://quizlet.com/ 8https://djangopackages.org/ 9https://github.com/wsvincent/awesome-django

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.