IoT Physical Servers and Cloud Offerings.pdf

6,303 views 111 slides Aug 11, 2023
Slide 1
Slide 1 of 111
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111

About This Presentation

Introduction to Cloud Storage models
• Communication APIs
• Webserver-Web server for IoT
• Cloud for IoT
• Python web application framework
• Designing a RESTful web API.


Slide Content

Unit -V
IoT Physical Servers &
CloudOfferings
6/7/2022 1

Outline
•Introduction to Cloud Storage models
•Communication APIs
•Webserver-Web server for IoT
•Cloud for IoT
•Python web application framework
•Designing a RESTful web API.
6/7/2022 2

Introduction to Cloud Computing
•TheInternetofThings(IoT)involvestheinternet-connecteddeviceswhichareused
toperformtheprocessesandservicesthatsupportswayoflife.
•AnothercomponentsettohelpIoTsucceediscloudcomputing,whichactsasasort
offrontend.
•Cloudcomputingisanincreasinglypopularservicethatoffersseveraladvantagesto
IOT,andisbasedontheconceptofallowinguserstoperformnormalcomputing
tasksusingservicesdeliveredentirelyovertheinternet.
6/7/2022 3

Introduction to Cloud Computing
•Insimplewords,CloudComputingmeansprovidingcomputingservicesoverthe
internet(calledascloud).
•ThecomputingservicesincludeServers,Software,Storage,Database,
Networking,Analytics,Intelligenceetc.,
6/7/2022 4

Introduction to Cloud Computing
•Aworkermayneedtofinishamajorprojectthatmustbesubmittedtoamanager,
butperhapstheyencounterproblemswithmemoryorspaceconstraintsontheir
computingdevice.
•Memoryandspaceconstraintscanbeminimizedifanapplicationisinsteadhosted
ontheinternet.
•Theworkercanuseacloudcomputingservicetofinishtheirworkbecausethedatais
managedremotelybyaserver.
6/7/2022 5

Introduction to Cloud Computing
•Anotherexample-youhaveaproblemwithyourmobiledeviceandyouneedto
reformatitorreinstalltheoperatingsystem.
•YoucanuseGooglePhotostouploadyourphotostointernet-basedstorage.
•Afterthereformatorreinstall,youcantheneithermovethephotosbacktoyou
deviceoryoucanviewthephotosonyourdevicefromtheinternetwhenyouwant.
6/7/2022 6

Features of Cloud Computing
6/7/2022 7

Types of Cloud Computing Storage Services
6/7/2022 8

Types of Cloud Services
6/7/2022 9
•Infrastructure-as-a-service(IaaS)providesuserstheabilitytoprovisioncomputing
andstorageresources.Theseresourcesareprovidedtotheusersasavirtual
machineinstancesandvirtualstorage.
•Platform-as-a-Service(PaaS)providesuserstheabilitytodevelopanddeploy
applicationincloudusingthedevelopmenttools,APIs,softwarelibrariesand
servicesprovidedbythecloudserviceprovider.
•Software-as-a-Service(SaaS)providestheuseracompletesoftwareapplicationor
theuserinterfacetotheapplicationitself.

Types of Cloud Services
6/7/2022 10

Advantages
•Cost
•Speed
•Security
•Scalability
•Reliability
6/7/2022 11

Cloud Storage API
•AcloudstorageAPIisanapplicationprograminterfacethatconnectsa
locally-basedapplicationtoacloud-basedstoragesystem,sothatauser
cansenddatatoitandaccessandworkwithdatastoredinit.
•Totheapplication,thecloudstoragesystemisjustanothertargetdevice,
liketapeordisk-basedstorage.
•Anapplicationprograminterface(API)iscodethatallowstwosoftware
programstocommunicatewitheachother.
6/7/2022 12

Cloud Storage API
•TheAPIdefinesthecorrectwayforadevelopertowriteaprogramthat
requestsservicesfromanoperatingsystem(OS)orotherapplication.
•APIsareimplementedbyfunctioncallscomposedofverbsandnouns.
•Therequiredsyntaxisdescribedinthedocumentationoftheapplication
beingcalled.
6/7/2022 13

How APIs Works
•APIsaremadeupoftworelatedelements.
•Thefirstisaspecificationthatdescribeshowinformationisexchanged
betweenprograms,doneintheformofarequestforprocessinganda
returnofthenecessarydata.
•Thesecondisasoftwareinterfacewrittentothatspecificationand
publishedinsomewayforuse.Thesoftwarethatwantstoaccessthe
featuresandcapabilitiesoftheAPIissaidtocallit,andthesoftwarethat
createstheAPIissaidtopublishit.
6/7/2022 14

Why APIs are important
•Theweb,softwaredesignedexchangeinformationviatheinternetand
cloudcomputinghaveallcombinedtoincreasetheinterestinAPIsin
generalandservicesinparticular.
•Softwarethatwasoncecustom-developedforaspecificpurposeisnow
oftenwrittenreferencingAPIsthatprovidebroadlyusefulfeatures,
reducingdevelopmenttimeandcostandmitigatingtheriskoferrors.
6/7/2022 15

Why APIs are important
•APIshavesteadilyimprovedsoftwarequalityoverthelastdecade,andthe
growingnumberofwebservicesexposedthroughAPIsbycloudproviders
isalsoencouragingthecreationofcloud-specificapplications,internetof
things(IoT)effortsandappstosupportmobiledevicesandusers.
6/7/2022 16

Basic Types of APIs
•APIstakethreebasicforms:local,web-likeandprogram-like.
•LocalAPIsaretheoriginalform,fromwhichthenamecame.Theyoffer
OSormiddlewareservicestoapplicationprograms.Microsoft's.NETAPIs,
theTAPI(TelephonyAPI)forvoiceapplications,anddatabaseaccess
APIsareexamplesofthelocalAPIform.
6/7/2022 17

Basic Types of APIs
•WebAPIsaredesignedtorepresentwidelyusedresourceslikeHTML
pagesandareaccessedusingasimpleHTTPprotocol.AnywebURL
activatesawebAPI.
•WebAPIsareoftencalledREST(representationalstatetransfer)or
RESTfulbecausethepublisherofRESTinterfacesdoesn'tsaveanydata
internallybetweenrequests.Assuch,requestsfrommanyuserscanbe
intermingledastheywouldbeontheinternet.
6/7/2022 18

Basic Types of APIs
•ProgramAPIsarebasedonremoteprocedurecall(RPC)technologythat
makesaremoteprogramcomponentappeartobelocaltotherestofthe
software.
•Serviceorientedarchitecture(SOA)APIs,suchasMicrosoft'sWS-seriesof
APIs,areprogramAPIs.
6/7/2022 19

WAMP-AutobahnforIoT
•WebApplicationMessagingProtocol(WAMP)isasub-protocolofWebsocket
whichprovidespublish-subscribeandremoteprocedurecall(RPC)messaging
patterns.
•WAMPenablesdistributedapplicationarchitectureswheretheapplication
componentsaredistributedonmultiplenodesandcommunicatewithmessaging
patternsprovidedbyWAMP.
6/7/2022 20

WAMPSession Between Client and Router
6/7/2022 21

WAMP -Concepts
•Transport:Transportischannelthatconnectstwopeers.Thedefaulttransport
forWAMPisWebsocket.WAMPcanrunoverthetransportsaswellwhich
supportmessagebasedreliablebidirectionalcommunication.
•Session:Sessionisaconversationbetweentwopeersthatrunsovera
transport.
6/7/2022 22

WAMP -Concepts
•Client:Clientsarepeersthatcanhaveoneormoreroles.Inpublish-subscribe
modelclientcanhavefollowingroles:
–Publisher:Publisherpublishesevents(includingpayload)tothetopic
maintainedbytheBroker.
–Subscriber:Subscribersubscribestothetopicsandreceivestheevents
includingthepayload.
6/7/2022 23

WAMP -Concepts
•InRPCmodelclientcanhavefollowingroles:
–Caller:Callerissuescallstotheremoteproceduresalongwithcallarguments.
–Callee:Calleeexecutestheprocedurestowhichthecallsareissuedbythecaller
andreturnstheresultsbacktothecaller.
6/7/2022 24

WAMP -Concepts
•Router:Routersarepeersthatperformgenericcallandeventrouting.Inpublish-
subscribemodelRouterhastheroleofaBroker:
–Broker:Brokeractsasarouterandroutesmessagespublishedtoatopictoall
subscriberssubscribedtothetopic.
6/7/2022 25

WAMP Protocol Interaction between the Peers
6/7/2022 26

WAMP Protocol Interaction between the Peers
•Inthisprotocol,WAMPtransportusedisWebsocket.
•WAMPsessionsareestablishedoverWebsockettransportwithinthe
lifetimeofWebsockettransport.
6/7/2022 27

Publish Subscribe Messaging using WAMP -
Autobahn
6/7/2022 28

Publish Subscribe Messaging using WAMP -
Autobahn
•TheclientinPublisherrolerunsaWAMPapplicationcomponentthat
publishesmessagestotherouter.
•Therouterinbrokerrolerunsontheserverandroutesthemessagesto
thesubscribers.
•Therouterdecouplesthepublisherfromthesubscribers.
•Thecommunicationbetweenpublisher-brokerandbrokersubscribers
happensoveraWAMPwebsocketsession.
6/7/2022 29

Commands used for installing Auto Bahnin
Python
6/7/2022 30

Commands used for installing Auto Bahnin
Python
6/7/2022 31

WAMP -Autobahn
•CreateaWAMPPublisherComponent.
•Thepublishercomponentwillpublishamessagecontainingthecurrent
timestamptoatopicnamed‘test–topic’.
•CreateaWAMPSubscribercomponent.
•Thesubscribercomponentthatsubscribestothe‘test-topic’
6/7/2022 32

WAMP Publisher Component
6/7/2022 33

WAMP Subscriber Component
6/7/2022 34

WAMP Subscriber Component
•Run the application router on a websocketserver as follows:
6/7/2022 35

Xively Cloud for IoT
•Itisacommercialplatformasaservice(PAAS)thatcanbeusedfor
creatingsolutionsforIoT.
•WithXivelycloud,IoTdeveloperscanfocusonthefrontendinfrastructure
anddevicesforIoT(thatgeneratethedata),whilethebackenddata
collectioninfrastructureismanagedbyXively.
6/7/2022 36

Xively Cloud for IoT
•Xivelyplatformcomprisesofamessagebusforreal-timemessage
managementandrouting,dataservicesfortimeseriesarchiving,directory
servicesthatprovidesasearch-abledirectoryofobjectsandbusiness
servicesfordeviceprovisioningandmanagement.
•Xivelyprovidesanextensivesupportforvariouslanguagesandplatforms
•TheXivelylibrariesleveragestandardsbasedAPIoverHTTP,socketsand
MQTTforconnectingIoTdevicestotheXivelyCloud.
6/7/2022 37

Xively Cloud for IoT
•TostartusingXivelypythonlibrary,firstweneedtoregisteradeveloper
accountandthencreatedevelopmentdevicesonXively.
•Whenanewdeviceiscreated,XivelyautomaticallycreatesaFeedIDand
anAPIkeytoconnecttothedevice.
•FeedIDisacollectionofchannelsordatastreamsdefinedforadevice
andassociatedmetadata.
•APIkeysareusedtoprovidedifferentlevelsofpermissions.
•ThedefaultAPIkeyhasread,update,createanddeletepermissions.
6/7/2022 38

Xively Cloud for IoT
6/7/2022 39

Xively Cloud for IoT
6/7/2022 40

Xively Cloud for IoT
•Xivelydeviceshaveoneormorechannelsandeachchannelenables
bidirectionalcommunicationbetweentheIoTdevicesandXivelycloud.
•IoTdevicescansenddatatoachannelusingtheXivelyAPIs.
•Foreachchanneloneormoretriggerscanbecreated.Atrigger
specificationincludesachanneltowhichthetriggercorresponds,trigger
conditionandanHTTPpostURLtowhichtherequestissentwhenthe
triggerfires.
•Triggerareusedtoprovideintegrationforthirdpartyapplications.
6/7/2022 41

Xively Cloud for IoT
•LetusconsideranexampleofusingXivelycloudforanIoTsystemthat
monitorstemperatureandsendsthemeasurementstoaXivelychannel.
•Temperaturemonitoringdevicecanbebuiltbyraspberrypiboardanda
temperaturesensorisconnectedtotheboard.
•Theraspberrypirunsacontrollerprogramthatreadsthesensorvalues
everyfewsecondsandsendsthemeasurementstoaXivelychannel.
•Box8.4showsthepythonprogramforsendingthetemperaturedatato
XivelycloudbyusingXivelypythonlibrary.
6/7/2022 42

Xively Cloud for IoT
•Tokeeptheprogramsimpleandwithoutgoingintothedetailsofthe
temperaturesensor,syntheticdataisused(generatedrandomlyin
readTempSensor()function).
•AfeedobjectiscreatedbyprovidingtheAPIkeyandFeedID.Thena
channelnamedtemperatureiscreated.
•ThetemperaturedataissenttothischannelintherunController()function
every10seconds.
6/7/2022 43

Xively Cloud for IoT
6/7/2022 44

Xively Cloud for IoT
6/7/2022 45

Xively Cloud for IoT
6/7/2022 46

Xively Cloud for IoT
•Figure8.6showsthetemperaturechannelintheXivelydashboard.Inthis
exampleasingleXivelydevicewithonechanneliscreated.Xivelycanalso
havemultiplechannelsandmultipledevices.
6/7/2022 47

Xively Cloud for IoT
6/7/2022 48

Python Web Application Framework -Django
•Djangoisanopensourcewebapplicationframeworkfordevelopingweb
applicationsinPython.
•A"webapplicationframework"ingeneralisacollectionofsolutions,
packagesandbestpracticesthatallowsdevelopmentofweb
applicationsanddynamicwebsites.
•DjangoisbasedontheModel-Template-Viewarchitectureandprovidesa
separationofthedatamodelfromthebusinessrulesandtheuser
interface.
6/7/2022 49

Python Web Application Framework -Django
•DjangoprovidesaunifiedAPItoadatabasebackend.
•ThuswebapplicationsbuiltwithDjangocanworkwithdifferentdatabases
withoutrequiringanycodechanges.
•Withthisfiexibilityinwebapplicationdesigncombinedwiththepowerful
capabilitiesofthePythonlanguageandthePythonecosystem,Djangoisbest
suitedforcloudapplications.
•Djangoconsistsofanobject-relationalmapper,awebtemplatingsystemand
aregular-expression-basedURLdispatcher.
6/7/2022 50

DjangoArchitecture
•DjangoisModel-Template-View(MTV)framework.
Model
•Themodelactsasadefinitionofsomestoreddataandhandlesthe
interactionswiththedatabase.Inawebapplication,thedatacanbe
storedinarelationaldatabase,non-relationaldatabase,anXMLfile,
etc.ADjangomodelisaPythonclassthatoutlinesthevariablesand
methodsforaparticulartypeofdata.
6/7/2022 51

DjangoArchitecture
Template
•InatypicalDjangowebapplication,thetemplateissimplyanHTML
pagewithafewextraplaceholders.Django’stemplatelanguagecan
beusedtocreatevariousformsoftextfiles(XML,email,CSS,
Javascript,CSV,etc.)
6/7/2022 52

DjangoArchitecture
View
•Theviewtiesthemodeltothetemplate.Theviewiswhereyouwritethe
codethatactuallygeneratesthewebpages.Viewdetermineswhat
dataistobedisplayed,retrievesthedatafromthedatabaseandpasses
thedatatothetemplate.
6/7/2022 53

Starting Development with Django
CreatingaDjangoProjectandApp
•WhenanewDjangoprojectiscreated,anumberoffilesarecreatedas
describedbelow
6/7/2022 54

Starting Development with Django
•ADjangocanhavemultipleApps,wheretheseAppsareusedtowritethe
codethatmakeswebsitefunction.
•Whenanewapplicationiscreatedanewdirectoryfortheapplicationis
alsocreatedwhichhasanumberoffilesincluding–
6/7/2022 55

Starting Development with Django
6/7/2022 56

Starting Development with Django
•Djangocomeswithabuiltin,lightweightwebserverthatcanbeusedfor
developmentpurposes.
•WhentheDjangodevelopmentserverisstartedthedefaultprojectcanbe
viewedattheURL:http://localhost:8000.
6/7/2022 57

Starting Development with Django
6/7/2022 58

Starting Development with Django
ConfiguringaDatabase
•Developershaveawidechoiceofdatabasesthatcanbeusedforweb
applicationsincludingbothrelationalandnonrelationaldatabases.
•DjangoprovidesaunifiedAPIfordatabasebackendthusgivingthe
freedomtochoosethedatabase.
•DjangosupportsvariousrelationaldatabaseenginesincludingMySQL,
PostgreSQL,OracleandSQLite3.
6/7/2022 59

Starting Development with Django
•SupportfornonrelationaldatabasessuchasMongoDBcanbeaddedby
installingadditionalengines(Eg.Django-MongoDBenginefor
MkongoDB).
•Thefirststepinsettingupadatabaseistoinstallandconfigurea
databaseserver.
•Afterinstallingthedatabase,thenextstepistospecifythedatabase
settingsinthesetting.pyfileintheDjangoproject.
6/7/2022 60

Commands to setup My SQL
6/7/2022 61

Database setting to use MySQL with a
DjangoProject
6/7/2022 62

6/7/2022 63

Starting Development with Django
6/7/2022 64

Defining a Model
•AModelactsasadefinitionofthedatainthedatabase.
•Box8.10showsanexampleofaDjangomodelforTemperatureData
collectedbyanIoTDevice.
•TheTemperatureDatatableinthedatabaseisdefinedasaclassinthe
DjangoModel.
•Eachclassthatrepresentsadatabasetableisasubclassof
django.db.models.Modelwhichcontainsallthefunctionalitythatallows
themodelstointeractwiththedatabase.
6/7/2022 65

Defining a Model
•TheTemperatureDataclasshasfieldstimestamp,temperature,latandlon
allofwhichareCharField.
•Tosyncthemodelswiththedatabase,runthefollowingcommand:
•>pythonmanage.pysyncdb
•Whenthesyncdbcommandisrunforthefisttime,itcreatesallthetables
definedintheDjangomodelintheconfigureddatabase.
6/7/2022 66

Defining a Model
6/7/2022 67

DjangoAdmin Site
•Djangoprovidesanadministrationsystemthatallowstomanagethe
websitewithoutwritingtheadditionalcode.
•This“admin”systemreadstheDjangomodelandprovidesaninterface
thatcanbeusedtoaddcontenttothesite.
•TheDjangoadminsiteisenabledbyaddingdjango.contrib.adminandd
jango.contrib.admindocstotheINSTALLED_APPS sectioninthe
settings.pyfile.
6/7/2022 68

DjangoAdmin Site
•TheadminsitealsorequiresURLpatterndefinitionsintheurl.pyfile.
•Todefinewhichapplicationmodelstobeeditableintheadmininterface,a
newfilenamedadmin.pyiscreatedintheapplicationfolder.

6/7/2022 69

DjangoAdmin Site
6/7/2022 70

DjangoAdmin Site
6/7/2022 71

Defining a View
•Theviewcontainsthelogicthatgluesthemodeltothetemplate.
•Theviewdeterminesthedatatobedisplayedinthetemplate,retrieves
thedatafromthedatabaseandpassesittothetemplate.
•Conversely,theviewalsoextractsthedatapostedinaforminthe
templateandinsertsitinthedatabase.
•Typically,eachpageinthewebsitehasaseparateview,whichis
basicallyapythonfunctionintheviews.pyfile.
6/7/2022 72

Defining a View
•Viewscanalsoperformadditionaltaskssuchasauthentication,sending
emails,etc.,
•Box8.12showsanexampleofaDjangoviewfortheWeatherStation
app.
•Thisviewcorrespondstothewebpagethatdisplayslatestentryinthe
TemperatureDatatable.
•InthisviewtheDjango’sbuiltinobject-relationalmappingAPIisusedto
retrievethedatafromtheTemperatureDataTable.

6/7/2022 73

Defining a View
•Theobject-relationalmappingAPIallowsthedeveloperstowritegeneric
codeforinteractingwiththedatabasewithoutworryingaboutthe
underlyingdatabaseengine.
•Sothesamecodefordatabaseinteractionsworkswithdifferentdatabase
backends.
•Aspecificpythonlibrarycanbechosetothedatabasebackendused(eg.
MySQLdbforMySQL,PyMongoforMongoDBetc.)towritedatabase
backedspecificcode.
6/7/2022 74

Defining a View
•In the view shown in Box 8.12, the
TemperatureData.objects.order_by(‘_id’)queryreturnsthelatestentryin
thetable.
•Toretrieveallentries,canusetable.objects.all().
•Toretrievespecificentries,usetable.objects.filter(**Kwargs)tofilterout
queriesthatmatchthespecifiedcondition.
6/7/2022 75

Defining a View
•Torendertheretrievedentriesinthetemplate,therender_to_response
functionisused.
•Thisfunctionrendersagiventemplatewithagivencontextdictionaryand
returnsanHttpResponseobjectwiththatrenderedtext.
•Box8.13showsanalternativeviewthatretrievesdatafromtheXively
cloud.
6/7/2022 76

Defining a View
6/7/2022 77

Defining a View
6/7/2022 78

Defining a View
6/7/2022 79

Defining a Template
•ADjangoTemplateistypicallyanHTMLfile(itcanbeanysortoftextfile
suchasXML,email,CSS,Javascript,CSVetc,).
•Djangotemplatesallowseparationofthepresentationofdatafromthe
actualdatabyusingplaceholdersandassociatedlogic(Usingtemplate
tags).
•Atemplatereceivesacontextfromtheviewandpresentsthedatain
contextvariablesintheplaceholders.
6/7/2022 80

Defining a Template
•Box8.14showsanexampleofatemplatefortheWeatherStationapp
andthevariablescontainingtheretrievedtemperature,latitudeand
longitudearepassedtothetemplate.
6/7/2022 81

Defining a Template
6/7/2022 82

Defining a Template
6/7/2022 83

Defining a Template
6/7/2022 84

Defining a Template
6/7/2022 85

Defining the URL Patterns
•URLpatternsareawayofmappingtheURLstotheviewsthatshould
handletheURLrequests.
•TheURLsrequestedbytheuserarematchedwiththeURLpatternsand
theviewcorrespondingtothepatternthatmatchestheURLisusedto
handletherequest.
6/7/2022 86

Defining the URL Patterns
•Box8.15showsanexampleoftheURLpatternsfortheWeatherStation
ProjectandtheURLpatternsareconstructedusingregularexpressions.
•Thesimplestregularexpression(r’^$’)correspondstotherootofthe
websiteorthehomepage.
6/7/2022 87

Defining the URL Patterns
6/7/2022 88

Defining the URL Patterns
•WiththeDjangomodels,views,templatesandURLpatternsdefinedfor
theDjangoproject,theapplicationfinallyrunswiththecommandsshown
inBox8.16.

6/7/2022 89

Designing a RESTfulWeb API
•DjangoRESTframeworkcanbeinstalledasfollows:
6/7/2022 90

Designing a RESTfulWeb API
•AfterinstallingtheDjangoRESTframework,createanewDjangoproject
namedrestfulapi,andthenstartanewappcalledmyapp,asfollows:
6/7/2022 91

Designing a RESTfulWeb API
•TheRESTAPIallowstocreate,view,updateanddeleteacollectionof
resourceswhereeachresourcerepresentsasensordatareadingfroma
weathermonitoringstation.
•Box8.17showstheDjangomodelforsuchastation.
•Thestationmodelcontainsfourfields–stationname,timestamp,
temperature,latitudeandlongitude
6/7/2022 92

Designing a RESTfulWeb API
6/7/2022 93

Designing a RESTfulWeb API
•Box8.18showstheDjangoviewsfortheRESTAPI.
•ViewSetsareusedfortheviewsthatallowstocombinethelogicforaset
ofrelatedviewsinasingleclass.

6/7/2022 94

Designing a RESTfulWeb API

6/7/2022 95

Designing a RESTfulWeb API
6/7/2022 96

Designing a RESTfulWeb API
•Box8.19showstheserializersfortheRESTAPI.
•Serializersallowcomplexdata(suchasquerysetsandmodelinstances)
tobeconvertedtonativepythondatatypesthatcanbeeasilyrendered
intoJSON,XMLorothercontenttypes.
•Serializersalsoprovidede-serialization,allowingparseddatatobe
convertedbackintocomplextypes,afterfirstvalidatingtheincoming
data.
6/7/2022 97

Designing a RESTfulWeb API
6/7/2022 98

Designing a RESTfulWeb API
•Box8.20showstheURLpatternsfortheRESTAPI.
•Since,ViewSetsareusedinsteadofviews,itcanautomaticallygenerate
theURLconfforAPI,byregisteringtheViewSetswitharouterclass.
•RoutersautomaticallydetermininghowtheURLsforanapplication
shouldbemappedtothelogicthatdealswithhandlingincoming
requests.
6/7/2022 99

Designing a RESTfulWeb API
6/7/2022 100

Designing a RESTfulWeb API
•Box8.21showsthesettingsfortheRESTAPIDjangoproject.
6/7/2022 101

Designing a RESTfulWeb API
•Box8.21showsthesettingsfortheRESTAPIDjangoproject.
6/7/2022 102

Designing a RESTfulWeb API
•AftercreatingthestationRESTAPIsourcefiles,thenextstepistosetup
thedatabaseandthenruntheDjangodevelopmentwebserveras
follows:
6/7/2022 103

Designing a RESTfulWeb API
•Box8.22showsexamplesofinteractingwiththeStationRESTAPIusing
CURL.
•TheHTTPPOSTmethodisusedtocreateanewresource,GETmethod
isusedtoobtaininformationaboutaresource,PUTmethodisusedto
updatearesourceandDELETEmethodisusedtodeletearesource.
6/7/2022 104

Designing a RESTfulWeb API
6/7/2022 105

Designing a RESTfulWeb API
6/7/2022 106

Designing a RESTfulWeb API
6/7/2022 107

Designing a RESTfulWeb API
6/7/2022 108

Designing a RESTfulWeb API
6/7/2022 109

Designing a RESTfulWeb API
6/7/2022 110

Designing a RESTfulWeb API
6/7/2022 111
Tags