Django REST Framework - Build an API from Scratch

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone welcome it's Caleb in this video we're going to be building an API with d jeno and this video unlike a lot of the other videos out there on YouTube is not going to require any prior knowledge or prior code so we're going to start with a brand new project and talk about everything you need to do to get your API built so it might take a little bit of extra time at the beginning getting things set up but we'll be all on the same page and probably end up with a better product now this video was inspired by another video I did which was the concepts of rest apis followed up with some python code but we used a a different framework known as flask so I thought it would make sense to kind of go through that same process but with d Jango now Jango is a little bit more complicated so if you need some extra resources on jeno you can check out my previous video which was my Jango crash course but that's not a prerequisite for this video so what we're going to do is we're just going to jump in and create a brand new project just so everybody's on the same page an API allows multiple applications to communicate with one another so if you can describe all of the data for your application in a consistent format typically Json format you can easily send and receive data between different applications so a lot of big apps out there will have apis that you can use for example stack Overflow has an API Instagram API I'm sure Google has like a bajillion apis and you can work with their applications through code so that is what the API is for and typically the API will allow you to do things like view data create new data update data delete data so we're going to look into how to do these things in this video so the first thing we're going to do is we're going to make a directory and we're going to call this drinks this will be a little app to get information about your favorite beverages so what we'll do is we'll change directory into the drinks directory and from here we're going to create a new Django application so for this you're going to need python so Python 3 you can make sure you have it installed if you don't don't you can go on the internet and download it from the python website so that's the first step and before we go in and start installing Jango and all these different things I want to actually create a virtual environment so the virtual environment is where we're going to install all the dependencies we need for our project to run such as jeno and this virtual environment will be activated whenever we want to work on our project so to create a virtual environment we say Python 3 hyphen M and then use the ven V command and then give it a name such ASV EnV which is what I always name my virtual environments and what that's going to do is it's going to create a venv directory so you'll have to say ls- a to see it and you can see it right there so what I want to do is I want to open up this directory we're in inside of Visual Studio code so you can go file open or open folder select that directory hit open and now when you open a terminal it's automatically going going to be in that path so from here we have the virtual environment directory you can see those files over here but we actually need to activate it so the way you do that is you say dot space and then the name of the directory and you're going to go to a path which is for/ bin SL activate so you can see that right in here we got bin activate that is the command to activate the virtual environment you're going to see this in parenthesis over here on the left so you'll want to go through that activation process anytime you want to work on your project and now when we install dependencies they're going to be just for this virtual environment so you don't have clashing dependencies across projects all right so what we need to do now is we need to start installing stuff so we can say pip install jeno that's going to download jeno and any dependencies we're also going to say pip install Jango rest framework and that's the tool we're going to use to create create the rest API so now that we have Jango installed we should be able to say Jango admin and when you hit enter you'll see a bunch of other commands you can execute after that which is all useful stuff for your application for example you can run the server or you could start a project and that's the one we're going to use so we'll say Jango admin start project give it a name like drinks and then say we want this in the current Direct Dory hit enter and when we do this we can open our files and see we now have this drinks directory inside of this outer directory here so it's a little strange to see the same name here twice but this outer directory can be named whatever you want I just created that for organization sake so that way our virtual environment and this manage.py file are all in the same directory all right so far so good we'll clear this off so when we create a project there's going to be a file created called manage.py so what we can do is we can use this file and say Python manage.py and think of this as a wrapper around the Django admin that does a little extra setup for us and makes things easier for us so what we can do is we can say python manage.py run server and this will start the server on this URL so we can open that up and see that here so this is the homepage for your website now don't get too excited cuz we have a lot more to do the first thing is this error here it says 18 unapplied migrations so the migrations represent the data structure for the databases and those need to be created so you can run python manage.py migrate to apply them and that's going to create those databases so I'm going to leave this server running and open a new tab here we'll start the virtual environment activate and now we'll say python manage.py migrate so that will apply all the migrations you can see we get a bunch of okays so we have the essential database tables created we're going to follow the same process for our custom data type so whatever you want to make your API about in this case it's going to be an API to get information about drinks we need to create a model that represents what a drink looks like so this model is just going to be a python class and we give it various attributes as you continue to build your application you're going to get more and more models and your dat database is going to become more complex so D Jango has an admin page that will allow you to see the different tables and see the data inside of the tables this is pretty handy when you're building an API because you can make sure everything's working checking it against the database tables so what we want to do now is go to this admin site so in the browser you can go to for SL admin here is the admin page however there's not going to be a username and password already set mine just autofilled from Save username passwords so I'm going to tell you how to generate this let's go back to the terminal python manage.py create super user this is going to ask for a username and password we're just going to go with admin and just give us some email address and I'm just going to give it a really lame password such as password and it'll complain about the security with this but you can override it just putting yes all right so we have that user now we can go in and log in and you can see the tables so what we want to do now is we want to get our own table on here so to do that we need to create a model so let's go back to our code check out our files and inside of our drinks app what we're going to do is we're going to say new file models.py now to tell D Jango that this is a model not only do we put it in the models.py file but we also need to inherit from a model class so we need to get this class in this file so we'll say from django.db B import models now when we create our class which we'll just call it drink we inherit from models. model so that is how jeno knows this is a model class and now we can just give it some attributes such as name and then we say the data type the way we do this is by saying models Dot and there's various data types on here such as charfield which is the one we want and you can give it in max length if you wish so I don't know what the world long as drink name is but I highly doubt there's much out there over 200 characters we can also say we have a description and we'll do something similar models. charfield max length 500 all right so each drink should have a name and a description so we're not creating a specific drink here rather we're just describing what every drink should look like now to create a database table from this information we just need to create another migration so to do that we can say python manage.py make migrations and then the name of your app which is drinks now before you do this I'll show you actually what happens when you hit enter you're going to get an error no installed app with label drinks so by default there is this settings.py file and in here it will list all of the different apps you are using so our app for drinks actually isn't on here so what we can do is we can add this two here by saying drinks and that should fix the problem so let's try it again all right there we go migration for drinks and it created 00001 initial py and you can see that in this migrations folder over here okay so we created a migration the migration describes the change to our data structure but it doesn't actually apply that to the database so to do that we need to issue a command we issued previously which was python manage.py migrate so that will apply any unapplied migrations so we'll hit enter and you can see applying okay so there's one more thing we have to do to get our tables to show up in here and that is we need to create a file inside of our drinks directory which is going to be admin.py and here is where we can register the different tables we want to show up in our admin panel now just to be clear you don't have to use this admin site so if you just don't feel like it's going to be that helpful you don't have to register your models in this admin.py file or even create that super user or anything like that however for my sake I think it's going to be a little bit more helpful so in here we need to say from D Jango do contrib import admin and then import our model here so models import drink so the dot here refers to the same directory so models right here all right so we got the Imports the only other thing we have to do is say admin. site. register and then pass in the model drink that should be it so give that a save and I think this requires a refresh of the server so you can see nothing showed up yet so let's go back kill This Server here with contrl C rerun it and that's going to register that model so let's go back refresh and there we go all right so we have our drink table and you can test functionality here so we can add in a name grape soda and we'll just say very grapey all right save okay so we have that drink object in here and you can go in and see the data so now when we're testing our API adding items we can easily see that in this database so let's go ahead and add another drink so that way we can get a list of all of our drinks so this time we'll say orange soda very orangey awesome save now we have two drink objects here and you can change the representation of the object instead of just seeing drink object one or drink object two you can do that by going into the model file and inside of this class creating ancore uncore store uncore method and inside here you're going to take self which is how you create a method on the drink objects and all this has to do is return a string so for example we could just return name plus a space Plus the description so now when we go back to the page do a refresh you can see a little bit more detail about the drink all right so we've done a lot of things we created a model we created a few instances and stored them in the database but now what I want to do is I want to talk about how we can get that through the API so we already installed D Jango rest framework but we need to add that to our installed app list so let's start by going to settings.py and in here here we can just say rest framework all right and now what we're going to need is we're going to need a file so inside of this drinks directory here we're going to create [Music] serializers.py and this is going to describe the process of going from a python object to Json so here is an example of Json this is the structure we want to get back obviously the attributes are going to be a little bit different so we would have you know the drink name and then a drink description but it's going to look something like this so that is what the serializer class is for so to do this we're going to create a class and call this drink serializer and this is going to inherit from serializers do model serializer such a difficult word to say say all right so where is this coming from we're going to import this from rest framework import serializers all right so we have it imported now all we have to do in here it's pretty simple we're going to have an in class and call it meta and this is going to be the metadata describing the model so the model is going to be a drink which we're going to need to import so from models import drink and then the other thing we're going to need are the fields so you can go in here and you're going to make a list of all the fields so ID this is going to automatically be added to that model and we're also going to have the name and the description so we're going to use the serializer when we're trying to return our model through our API so the next thing we need to do we have our model we have our serializer we actually need to create an endpoint so to do that we're going to create another file inside of drinks and this is going to be called views.py so this is where you create all of your endpoints an endpoint being a certain URL that you can access data from so as an example we'll say Def and we're going to get a drink list this is going to take a request and in here what we're going to do is we're going to get all the drinks serialize them and then return Json so how do we get all the drinks well the very first thing as always we're going to have to import it we're going to have multiple Imports here so I'll just try to write them all out right now the very first thing we're going to want is from D Jango HTTP import Json response from our model so from Models import drink and then from serializers import drink serializer all right so let's try to go through these steps we're going to get all the drinks so to do that we can say drink so access the drink class and then dot objects doall so that's going to be all the drinks and we can just assign that to a variable drinks so the second step to serialize them we're going to use our drink serializer class so we're going to create an instance of that so we'll say drink seral alizer and this is going to take the drinks list as well as setting many equal to true so that'll serialize all of them because we have a list here and we're going to get a reference to this object so we'll just call a serializer and assign it this initializer call here all right so we have our serializer now all we have to do is return Json and to do that we're going to return a Json response pass in our serializer do data and I think that should be it so we created our view now we need to say what URL is going to hit this View and that's all done inside of urls.py so open that file scroll through here and you'll see your url patterns down here so we can create a new path and this will just be drinks and it's going to hit our view which we actually need to import so we'll just import all of the views so we'll say from drinks import views so that'll grab that file right there and then down here we'll just say views Dot and then what we can do is pass in whatever function we want to hit such as drink list so to now see what happens we need to visit this path so on our website what we'll do is we'll just go to instead of the admin page we'll go to drinks hit enter in order to allow non iary objects to be serialized set the safe parameter to false so that's just a quick change inside of our view in the return Json response we'll just put a comma and say safe is false all right give that a save we'll go back and do a quick refresh and there we go we get a list of data so if instead of having a list you want it to be an object all you could have to do is throw this serializer do dat in a dictionary so we'll just say drinks and set that equal to the data that should do the trick let's do a refresh and now we have an object with an attribute drinks which contains the list that's generally how I prefer to return data but either one works congratulations at this point you have a working API it's pretty limited all you can do is get a list of data but you can start working on the other things you can do such as adding a drink editing a drink deleting a drink let's get into some of those things now so this whole process is called crud create read update delete right now we have the read ability so we still need to do the c r and the D if we want that full crud capability through our API so yeah now that we're not returning anything other than an object we do not need this safe equals false so we can remove that save do a quick refresh make sure it still works and it's not broken so we're good to go okay so before we go in and create a bunch of other API endpoints for the different methods so let me just explain a little bit for those of you who are fairly new this is a function that will take a get request so when we literally just put in this URL we're getting this data so that's why it's called get like don't overthink it so you can see this if you go into inspect and then go into the network so this is going to record any network traffic through this page and we do a quick refresh and you can see see we have this request here so let's take a look at this you can see that the request method is get we're getting data and here's the URL and then here's the response so that's what the request looks like there's a bunch of other stuff in here too but that's the main stuff so there are other request methods that we need to deal with including post put and delete so when we have a function such as this here we can actually make it take multiple request types so not just get requests but also post requests to add a new drink so to do that we're going to use a decorator and a decorator is something you put above your function to describe its functionality in some way and this is going to be API View and you're going to put the methods that you can accept such as get and we're also going to build the functionality for post as well Now API view where does that come from from rest framework. decorators and don't feel like you have to have all this memorized I've been referring to documentation as I build this just to make sure I get these Imports correct so from rest framework. decorators we have a problem cannot be resolved so first thing it's import API View and for this import here well there's a few things you might want to check to make sure this is fixed first thing make sure Django rest framework is installed which we did so so far so good make sure it's spelled right um and you might also check the settings.py and make sure you typed that out here properly which we did so the only thing left I can think of is actually to do with The Interpreter so command shift p or control shift p on Windows and type in select interpreter so from here what you can do is you can select your virtual environment so it'll look at those dependencies as opposed to the dependencies installed globally on your machine so once I select that you can see that those problems went away I think things would have worked still but this is just the lens for visual studio code to see what dependencies you have installed and because all those dependencies are just installed in this virtual environment directory we need to basically say hey here is where I want you looking not at my Global installed dependencies so that's just a minor detail don't really worry about it too much but if you do run into that issue that is the fix so we made it such that we can accept get and post and we can condition on that value inside of this so if request. method is get then here is what we want to do and then what we can do is also check for post so if request. method is post what we can do is we can add a drink to the database so this is basically going to be a very similar process but in the opposite order so we're basically going to take the data they sent us deserialize it and then create a drink object out of it so the command is going to be pretty similar to what we have here just slightly different so we're going to create a drink serializer and instead of passing in some value like the drinks we created up here we're going to get that data from the request so we will say data is equal to request. dat and we're going to get a reference to this object so we'll say serializer similar to how we did up here all right so next thing we need to do is we can actually check to see if the data they sent is valid and the way you can do that is to call a method on this object so if serializer do is valid what are we going to do we're going to save it and the way you can do that is with serializer do saave once that's done we will return a response and in here we're going to say serializer do dat and we're also going to pass a status code so we can say status and set it equal to status. http 2011 created so the status needs imported and it looks like this response might need imported too so you can just do it this way where if you get this little light bulb here and you can see there's a few different options so you have to be careful when you do this automatic and we actually don't want any of these suggested ones so what we're going to do is we're going to go up to the top and just do it manually we'll just say from rest framework. response import response and from rest framework import status all right so those are going to be our two Imports that we need so that we can return a response object and have a status value a lot of the stuff is given to us to make it easier for us from jeno so we don't have to worry a whole lot about the response all we do is pass in serializer ddata and then the status and it looks like we might have an error with our API view here where it's supposed to only have one positional argument and I think that's because we just have to pass these in as a list so now we're just passing in one argument as a list so our server is good to go and now let's test adding an element to the database through the API so you could use a tool such as postmen and we're just going to get the data you can see this is the response so now let's try to add some data and it's going to be pretty similar but instead this time in the body we're going to send data so you can select raw here and under text change this to Json and you can paste in an object like this here just I copied it from down there we're just going to change some of the information here so first I don't think you need the ID that should be done automatically and for the name we can just say like strawberry soda I don't know I'm out of SoDo ideas and for the description we'll just say very good all right cool let's send this in we have a little error here where it didn't work we have a runtime error checking back in the terminal it's complaining about the slash in the URL so let's check our urls.py and it has a slash here but the URL we're using does not have a slash so I'll just add that in there and try again so we still have that same data we'll hit send and you can see it comes back with an ID so this part comes from inside of the view where we pass the data back in the response so we give the data back but now that data has the additional attribute of the ID you should be able to see that this data made it to the database in two ways the first is to actually just get the drinks again so when we get the drinks we get three elements back alternatively you can take a look at the admin page since we set that up we'll go to admin and we can see drinks and you can see there are three drinks in this table now you'll see from the admin panel you can open up any of these drinks and get more information about it currently there's not a whole lot of information here but you can imagine there being a long list of attributes this ability to get more details about an individual drink is a pretty important part of the API so imagine you go to drinks and instead of getting the entire list you just want to get the first drink here so you pass in the ID of one and you get that drink information but currently it's not working so let's talk about how we can set this up the very first thing we want to do is go into urls.py and create a new URL path so we'll say path and the path for this one is still going to be drinks but we're going to have a parameter here of type int and you can just say like I ID or PK or something like that for primary key and this is going to hit views. drink detail all right so this is the view we want to create we just have to now go build out that view so let me zoom out a little bit now that we're working with a little bit more code hopefully everybody can see everything fine let's go ahead and create a new function and this will be called drink detail it's going to be pretty similar where it has a request parameter and we're also going to have that same decorator API view however this one's going to have a few other options so we're going to have the ability to get information about a drink the ability to update or we're going to use put for that and the ability to delete a drink so this we're going to just follow a similar pattern where we just check the different options so if request. method is get we're going to do something for now we'll just say pass if request. method is post pass and we actually probably want this to be an LF so only one of these will execute on any request and we'll just have an LF for delete so if request on method is delete we'll do something else here now forget we're going to do it a little bit different than the way we did up here as we have a new better way of doing it so sort of how we did down here we we returned a response whereas up here we did a Json response so it's a little bit different and response comes from the D Jango rest framework and it is the preferred way of doing things because we're actually going to be able to set up some functionality to return Json or HTML for better data browsing so I'll show you how to do that here in this get request and then we could actually go and edit this one up here as well so as we've been doing we're going to create a drink serializer and this serializer is going to take the object to get so what we're going to do is actually put that up here so we'll say drink doobs doget and you can pass in the primary key so PK is equal to the ID which is going to be a second parameter passed in right here so taking a look back at the URLs real quick you can see we pass in this extra parameter the value of this is going to be sent to views into this variable so we can get a drink by its ID using the ID variable here and assigning it to the PK parameter so the primary key equal to that ID we passed in and we can check to see if this is valid so we can say try and this can throw an exception so we'll say accept and the exception is of type drink dot does not exist so if something goes wrong this exception will be hit and we can just return response status is equal to status. http and you can see all the different options here on the status the one we're interested in is 404 not found so now this is basically that checking just to make sure it's a valid request and we can use the the drink object throughout so we'll just assign it to a variable drink and now whenever we need to refer to that drink object we don't have to go through this process again so we could just pass in drink here and we're going to get a reference to the serializer and now all we have to do is return response and pass in serializer do dat so these two lines are all it takes for the get request and it's going to be very similar to this one up here but let's just uh focus on this right now let's try it out we'll just be able to get the data right now but we should be able to go to the API and pass in some ID such as one we hit enter and we get all the information for that drink we pass in two orange soda three strawberry soda and then let's say four nothing if we do the same thing in the browser we should be able to get one back that works and you can see this new HTML output here it's kind of cool if we put in four it says four or4 not found so here is another example of where that response comes in handy so this response is not Json specific so it's allowing us to see this HTML view where we can work with our data through the web page it's very similar to the admin panel so this kind of serves as same purpose but now it's on the front end and doesn't require a login and you can't necessarily see everything in the databases all right let's go back to our code and let's go ahead and fill out the post and delete actually this should be put not post so put is going to be used for updating I think that was just a typo from earlier but the process is going to be fairly similar to this post up here so no big deal so we can just say serializer is a new drink serializer pass in the drink and since we're going to be editing the drink you can think of it as very similar to creating a new drink we actually need to pass in the data that's being sent with the request so we'll say data is equal to request. dat and then we can just check to see if it's valid so if serializer do is valid what we're going to do is save the data so serializer do saave and then just return response serializer do dat so give that data back if it's not valid we're just going to return response and we can say serializer do errors and set a status so status is equal to status. http 400 bad request so that is the process for updating data we can test that out so let's go over to postman let's go ahead and get the data for 4 three and now what we want to do is make a put request and let's go ahead and change the data so we'll go into the body paste this here but let's say soda edited now when we hit send you can see it gives us back the new data and when we get the data you can see it's persisted so we're still getting that change delete is super easy so let's go back go in here and all we need to do is take that drink object that we had a reference to earlier right here and say drink. delete so just a typical way of doing it in D Jango if you have some Jango experience but we're going to return a response and pass in a status code so status is status. HTTP 204 no content that should allow us to delete stuff now so if we go in here and say say delete pass in the ID of three we don't have to have anything in the body we can remove that from the request hit send we don't get anything back however now when we try to get the data it's not there anymore and if we get all the drinks you can see we only get one and two all right cool so let's go ahead and take this new response behavior and put that in our old version up here so it's going to be very similar to this get here so let's copy these two lines go up here and we actually pretty much have that serializer already so we'll just say return response serializer do dat let's just try that out make sure it still works hit send you can see it's working but now we can go to the browser view all the drinks and we get to see it in this very cool HTML view so let's try something in here let's go into let's say drinks one and you can edit the data right here so we could say let's uh go with name set that equal to test and then we'll do description set that equal to Suite description and then close the object we'll hit put it looks like it updated it and we can go back to our drink list and see all of them and that's changed so we've went through pretty much three different ways of working with this data the first being the admin panel but that doesn't really use the API for the API you can use this HTML page or you can use a tool like Postman now you might want just get normal Json data through the browser so you could say something like Json but you can see that doesn't work I'm going to show you the fix for this right now what we need to do is we need to build that capability in our URLs so not only do we want these URLs but we want these URLs with different extensions so what we can do is we could use a function called format suffix patterns and pass in our URL pattern patterns and then we just reassign this returned value to URL patterns so whatever this returns we want to replace the URL patterns variable now we just need to import this and it's going to come from rest framework. URL patterns import format suffix patterns all right so that should give us that the server's working let's go back to the browser hit enter all right got an expected keyword argument format the quick fix for this is we just need to add a parameter to our views so let's go back to our view and for this one not only do we take request but we'll take format and default It To None we're going to do the same thing for our other view here so format is none now we should be able to go check in the browser do a refresh and there you go you have it in Json just like we would get from Postman or you can just remove Json if you want it in this HTML view now I do want to do some front end on consuming the apis we create however I don't want to quite do a full stack application in this video so what we're going to do is we're just going to do a very simple request through python to show how you might consume an API and then I'll leave it open for future research or a future video if you want to subscribe and stay tuned for upcoming episodes so in our project what I'm going to do is I'm just going to clear out all these files and we're just going to create a new file and I'm just going to put it in our main directory consume. py so we're not going to need to work with d Jango stuff anymore but we need to keep our server running if we want to consume this data so let's just keep that running and in a new tab what we can do is we can run this python file so you can do that by just saying python consume. py that'll do it or you can hit this play button right here and that'll show up either in the terminal and the output depending on your settings so let's go ahead and say print testing run the application you can see the output there so I'm going to do it through the terminal just so we have this virtual environment here and I'm going to say pip install requests and this is a module that allows us to make really simple requests to pages on the internet so what we could do is we could say import requests and then say response is requests Dot get and pass in a URL we'll just say 127.0.0.1 coolant 8000 slash drinks which I believe is the URL that's running our server right here and then we'll just print the response. Json so let's try it out and if you get this error here no connection adapters we just have to put HTTP so needs to know the protocol we'll run it now and you can see we get that data in our python application so that's the Bare Basics of consuming an API literally three lines of code very very simple so in this video we've done a ton it's a lot to learn and throughout this video I had to reference the documentation a lot too especially for all the different Imports so don't feel like you have to be perfect from day one maybe by day two or three but until then you're okay to make a few mistakes if you want more content like this I'm working on a python backend course I'll leave a link to early access to the notes are free and you'll also get notified through email when the course is released we also have a ton of other Python and web development videos on this channel
Info
Channel: Caleb Curry
Views: 195,185
Rating: undefined out of 5
Keywords: django tutorial, django course, python django tutorial, python django, django 101, django, django for beginners, django for backend development, django for beginners build websites with python and django, python django course, python, Python Django Tutorial, jango, api website tutorial, python programming, rest api, django rest framework, web development, django framework, django project, learn django, django crash course, django crash course 2021, software developer
Id: i5JykvxUk_A
Channel Id: undefined
Length: 40min 39sec (2439 seconds)
Published: Mon Feb 21 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.