REST API Crash Course - Introduction + Full Python API Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone welcome to your rest api crash course my name is caleb in this video we're going to talk about everything you need to know to get started with rest apis we're going to first talk about the concepts then we're going to talk about how to consume an api and then we're going to build our very own api in python so it's a lot of useless and it's a lot of useful information so if you need a reference of all this i created a pdf that you guys can get for free with a link in the description so go check that out if you just need to like you know look at the definitions and study or whatever but anyways we're going to jump in by first talking about what a rest api is why you should care and where this is used in software and if you're watching this video and you're not really doing anything with software not really sure why you're here but you can probably move on to one of my other videos so which all of my videos about software so anywho api stands for application programming interface so i tried talking and explaining this last time i recorded this and it just didn't go so well because i cannot talk and write very well at the same time application programming interface it's basically a fancy way to say a way two pieces of software can communicate with one another so if we have this software over here this is some really cool software system we built and here is another one and let's say these are built in different programming languages that's where an api is going to come in and save the day it allows different applications that aren't built exactly the same to communicate so we'll say this one was built in python and this one was built in javascript poor developer i'm so sorry well an api allows us to build functionality in this application to make a request to this other application and then this application can give a response back to this application and that is where the api comes in we're building this interface for these pieces of software to communicate with one another now in general it's a one-way thing so this app is not going to request information from this app and get it back instead it's always we have a server and then a client the client consumes information given from the server so this is a very common setup you'll see in all of computing the same way when you go to get a website you know you go to youtube.com you're making a request and then that server gives back a response it works exactly the same way with a rest api although instead of getting html you're going to get json so json is a language or a notation of describing information it's just like text and it stands for javascript object notation so it's a way to notate what objects look like but it doesn't have to be done with javascript it's actually supported in pretty much every language and this is now the standard for apis you may run into apis that use xml however this is kind of old-fashioned and probably not what you would want to use going forward so i would recommend even if you're more familiar with xml for some reason to learn json or json you'll hear both so json's not complicated don't feel like you have to learn another programming language or something it's just a series of key value pairs just like an object in javascript hence the word javascript object notation or like a dictionary in python where you have a key and then an associated value so it's pretty much just an associative array we'll get into what json looks like and how to use it soon when we go build our own api but don't worry too much about that so json is basically the the language of communication and the api is you know what things we can communicate you know maybe you want to get a list of users or maybe you want to update some comments whatever you want to do that's all defined as api endpoints so you know right here where we're making that request that's an example of an end point we're going to talk about the different types of endpoints that we can create now what about this rest thing here well that stands for um i think representational state transfer i had to look that up a little bit ago because i was like represent what was it anyways this is the means of communication so you know i can talk to you in english but how am i talking to you am i talking to you over the phone am i texting you am i talking to you face to face well that is describing how we're communicating and this rest aspect is communicating over the web or the internet so this is all going to be done by making requests similar to how you would request a website but instead of html you're requesting json just as i mentioned earlier so to make this a little bit more concrete let's go over an example of an app i'm working on so i have some software written in python and this is the server software you may also hear as the back end software and this is the software that's going to communicate with a database that's where all of our information and data is going to be stored so this talks to the database now we want other pieces of software to be able to communicate to this back-end software but we don't just want them to be able to access anything we don't want to give direct access to this database so instead we expose different api endpoints so an example of an api endpoint would be forward slash and this i haven't described what the actual app is for but forward slash drinks now the actual app is to get a list of drinks and be able to rate these you know like zero to ten or to put them in different categories of how good they are and then you can basically keep track of all your favorite drinks it's a little silly but i thought it'd be a fun project and um basically i i like to drink i don't like to drink i like to drink non-alcoholic beverages like lacroix or like stevia drinks and energy drinks or whatever but there's so many of them i can't keep track of them all so i just wanted to build a little website to you know rank them you know and instead of just getting all of the drinks you might want to get a specific drink so in this situation we would pass in an id so in this situation we are getting data and that's one of the different methods of apis we're going to talk about api methods here in a minute but what this means is my software that i built over here and in this situation let's just say this is javascript i can get all of the drinks or a specific drink from my backend software just by making a request to this web address now you might be looking at this like what that doesn't look like a web address well because this is a web server this is going to have either an ip address or a domain name so let's say i put this up on a website caleb's favorite drinks dot com not a real website to the extent of my knowledge and then forward slash drinks forward slash and then you can pass in some id such as five now the actual structure for these urls and what data you want to get that is totally up to you however there are some general standards and i will describe why i went with this coming up soon but basically we have the list of data we're trying to get from and then we pass in which specific element we want and this will return json of all the information about that drink now oftentimes when you have a website you're going to have web pages you know people can view on their web browser or you're going to have the api and often these will be split out into two subset applications so you might have caleb's favorite drinks dot com forward slash api forward slash drinks forward slash five or another common thing is to have a different domain such as api dot caleb's favorite drinks dot com you don't have to you can mix those together however just for organizational sake often the api is in some separate section either a sub directory or a sub domain now you might look at this setup as i often do when i'm working on applications and be like why the complexity why do you need to have two applications and then the database why don't you just connect from this application all the way to the database skipping all this junk well obviously you can do that you can do whatever you want but this is not always advisable for various reasons the most biggest importantest reason of not going from the client application directly to the database is security specifically if you are using javascript now oftentimes the client is going to be javascript because that's used for web pages however you could also make a console application or a mobile application so it's not always going to be javascript but if you go to a website you can go into the developer tools and you can see all of this javascript or you can right click and view source and it'll have the javascript files linked there and you can view all of that so you don't really want to put sensitive information on the client here because it's all viewable to the person using your software which means they could then go to the database themselves directly tinker around you know drop database lol we don't want them doing that so instead we just expose specific things that we want people to see such as the list of drinks but they can't go in there and see everybody's user information or people's address or any of that now beyond security the other big reason is versatility so right now we have one front-end application in javascript but with this setup we could very easily build a mobile application and yes this is a cell phone and we could also consume the same api so what happens now is both of these front-end applications are sharing the same back-end which means these are always going to have the same data they're going to be synchronized so that is how when you have applications on your phone you can go in there and change data and then you can go log in on your computer and all of that stuff still exists it's because they all share the same backend so you know when you're messaging someone on social media well those messages are being sent to a back-end server that does all the processing and all of the hard work of the application and that website you're looking at is really just a pretty cover to this back end so you know javascript maybe your application here is in swift but ultimately we're hiding the back end of this application and separating those which brings up the next good point which is modularity because the front end and the back end are separated and we're just defining this consistent way to communicate we can actually swap different things out and not necessarily break i say necessarily because you know in practice it's it could be difficult but in theory you should be able to swap out different things without breaking other pieces of the application so right now this is written in python but i could be like and i don't really feel like writing in python you know when i decide to upgrade to something like visual basic and in this situation we can expose the same exact api endpoint so this website and this mobile phone app they don't even need to know about those changes to the back end because they're still getting their list of drinks that's all they care about they just want their drinks this is great because you can change the back end of software without requiring an update to the app or requiring a new deployment of the website as long as you're able to give a consistent interface to working with your backend last reason and then i promise i'll stop rambling okay i got a little bit more rambling but basically the last thing i wanted to share of why this setup is good is interoperability which i think is a word and basically what i'm saying here is that these front-end applications they don't all have to be built by you or the front end development team for your company you can actually expose certain endpoints such as this one right here and you could make this public so if you make certain endpoints public you don't have to worry about authentication or authorization and in that situation anybody could go ahead and create some new app new and improved to consume your api so you know if i don't like the way instagram looks i can go create my very own instagram viewer because they have an api that can be consumed now sometimes you'll still need to get some kind of token or some way to authorize saying hey i'm okay to use this api but a lot of the times these apis are going to be publicly available so the api we're going to consume soon is just a public api that anybody can use and it's really cool honestly so many websites you might not even realize have apis so for example if you wanted to do something like create a trading bot or like a cryptocurrency trading bot well oftentimes different exchanges are going to have apis so you can automate different things in code so it's not always just about making a pretty interface but it might be about automation how can we connect these apps and make things happen automatically so if the thing's not public it might be private but you can still access it you just need a way to verify that it's you and not just anybody's going on there and trading cryptocurrencies or spending your money so there the authorization aspect of this is like a whole another beast but a common thing you often see is oauth 2. that is an authentication technique that's fairly common so if you want to look into how to protect your api and make you basically have to log in you can look into oauth that's o-a-u-t-h-2 now i want to take a moment to talk about the different methods of requesting data from the server so we've talked about get and this one's pretty simple it's what's used to retrieve data from the server and these are often written in all uppercase letters so you're just like screaming give me this information all right so get is used to retrieve data i could just say get data but fancy here alright so there's a few other ones you should know about and that is post post is used to write data so anytime you want to write information to the server you're going to use post and then there is delete almost didn't use capitals there but i fixed it and this is used to you know delete stuff now there is another one that's pretty common why do i always write like this way i don't know and that is put and this is actually fairly confusing if you're new and the difference between post and put is pretty gray and people will even argue about which you should use where here's my opinion post should be used to write new data put should be used to write but in this situation we're going to update data so now i want to show you how these things correlate to the most popular things you have to do with the database which is crud so the different things you need to do we need to be able to create data post read data get update data put and delete data delete now why exactly is there confusion between post and put that's what i want to talk about now well first let's talk about how post input are generally used post is used to add a resource put is used to replace a resource and that's why it's natural in my mind to say you can use put to update data and post to add new data but replacing a resource requires some way to identify it and often this is done with an id so my thoughts are if you're doing a post request you want to add data so you might have the address of drinks and you want to add a new drink with put you're probably going to need to identify what resource you want to replace so it might look like drinks forward slash 600 and 5 for an id now with the setup i tend to do i usually don't have this id value until that's that data is already inserted in the database with a post so when you're adding new data you don't know what that id is going to be because that's auto-incremented in the database then if you want to update that data then you use the id but there's another difference and this is more defined in the spec of how an api is supposed to work and less about pure functionality because you're the one who defines the functionality so if you want your api to work correctly then you need to make sure you implement it in this way and that is put is designed to give the same result every time if you make the same request so for example if you're replacing this drink with a new drink you can replace this id over and over again as long as that new one has the same exact id so let's say you have a grape drink and you replace it with cola and then you replace cola again with cola and then cola again with cola no matter how many times you do this the same resource exists and it doesn't hurt if you accidentally put that request numerous times post is usually a little bit different because that feature or capability is not guaranteed so what that means is if you add a new drink let's say you add cola and then you add cola again well in this situation you're not replacing anything so each time you add cola it's making a new record in that table so put is guaranteed to be able to be executed numerous times without any kind of side effects post on the other hand is not guaranteed by the spec and in that situation you could actually have duplicate records in the database or you could get an error on that second one if the drink name is defined to be unique now i'm probably going to mess this word up but there's a word to describe this i'd impotent it yeah i idempotent i don't know so put is said to be this i'm not even going to try anymore just whatever that's called now in general i think there's a lot of confusion between post and put and you can pretty much do the same behaviors with either one so i tend to just try to stick with post most of the time even if i'm updating a resource it you can do it with post just the same you can define it however you want it's sort of how with modern html you can make a section be a div or you can be a little bit more specific and say oh this is a footer both kind of give the same results and if you're not using footer right then you might just make things worse so a lot of people still end up just using divs so if you're using html that's just maybe that kind of puts it in perspective i don't know there's another method patch which is used to replace different pieces of a resource so maybe you just want to update one field however in our situation the data we're working with is so small that it's pretty much just easier to replace it with a new version so that way you don't have to keep track of individual changes however if you're working with very large data you can definitely look into patch so my theory is you basically keep the state of an object in the client side application and then once you save you just send that new state and replace the old state in the database hopefully that makes sense all right so let's get some practice with apis by consuming an existing api we're going to take a look at stack overflow so all of the questions on here you can get access to this information through an api so we can build an application to work with stack overflow so to do this you actually go to api.stackexchange.com and in here you can see the documentation for all of this so here's the different api endpoints so we can get the answers badges posts which is just a combination of questions and answers and i'm going to take a look at the questions here so we're going to get all of the questions and here is an example of how you would invoke this so you can hit run and you can see in this web address there's this question mark and then some variables with assigned values and then an and sign ampersand and a sort these are known as query parameters and they can be used in this situation to modify the results of the api now if you want to know how to actually invoke this without it running it in this little test window you basically just take this address here and you would paste it after api.stackexchange.com like so so that's what it's going to look like hitting enter you get a bunch of data here not exactly as pretty as this which by the way this is json format so it's just key value pairs and in the pairs you can have arrays or uh you could consider them list if you're more familiar with python so we have items right here which is a list of questions each question is surrounded by curly braces so there's the opening curly brace and it has tags owner a bunch of other stuff and then it ends and then we have another question which has tags owner a bunch of other stuff and it just repeats in a list so what we're going to do is we're going to work with this api so a tool i would recommend you get is called postman and in here you can work with your apis and it's just a little bit easier because you can customize the body and the different headers of your request and what we're going to do is we're just going to take this web address here and paste it on here so we're going to have http colon slash api.stackexchange.com and then forward slash questions and then all that other stuff so hit send and we'll get a response sort of like this so basically this is json here we have this items and then a list of the different questions so let's go ahead and we'll come back to postman later but for now let's take this url and try to work with this in a python script so if you need help setting up a python environment then you can check out my beginner python programming all in one however i'm just going to assume you can at least get a python environment set up and we're in a python file what we're going to do is we're going to need a few tools so we're going to say import requests and import json so if this is your first time working with requests you might need to install it so what we can do is we can open a terminal and say pip3 install request all right so now we have requests installed and we should be able to make a request to a web page by saying request dot get and pasting in a web address inside of a string here so let's just uh make sure this is nice and formatted properly like so and that's going to return a response so we can assign that to a response variable and then what we'll do is we'll just print this response and see what we get and you can see we get a response 200 which means okay now we can actually see the data that's returned by running dot json as a method here and that's going to give us all of the data exactly as we would if we requested it in the web browser or with postman so we got the items and then a list of all of the different questions so we can basically zoom in on this and instead of just having [Music] one key value pair where we have items and then a giant list we could actually explore items specifically by passing in items here so we're going to index for items and then run this now and we have just a list now so we're no longer working with the items we just have a list of questions so then what we could do is we could iterate over these so let's get rid of this print and we'll say for data in items or if you want to be more specific you could say for question in items this will be good for now and then we'll do is we'll just print data and you can just print each one individually like so or you can be more specific and grab something like the title which i know is an attribute of it so running this and you can see here are all of the titles so that's pretty cool so basically that is right right here the title we're going to be grabbing each one of these so every single item in this list and you can also get something like the link if you wanted so you could say print data link and now we got a series of question and answers and let's just print a space just to make it a little bit prettier there we go so here is the question and then here is the link which we can control click to open and there you go so maybe you could build some kind of application to help you find good stack overflow questions to try to answer before anyone else does so you can be a little bit more specific you know you could go in here and you could check to see the answer count answer count it's like 2 for this one so maybe maybe you only want to print the ones where the answer count is zero so you could say if data and then ask for the answer count is zero then we want to print the data and just to show you guys that it's working we'll say else print skipped and also just print another space at the end actually i'll just uh take that out of the loop there we go so this is our setup now and we can run this and you can see skipped and then we got a question and then skipped and then a question another question and it seems to be working so that's how you consume an api now i want to talk about how we can create our own api so what i want to do is x out of this file here and we are in a folder api and open a terminal which i have one here and we can get the path so just make sure you're in that directory we're going to execute a sequence of commands in the terminal here so the very first thing is we're going to create a virtual environment so to do that you say python3 hyphen m virtual environment v env and then give it a name such as dot v e and v and that's going to create a new folder in here for your virtual directory which i talked about this in my previous video where we deployed a python web app but this is basically to isolate the dependencies for this specific application now we can do is we can activate that by saying source and then traveling to it so it's in the dot v env folder bin activate so that is how you activate a virtual environment then we can install our dependencies pip3 install flask and we're also going to install pip3 install flask sql alchemy and that's going to be used to work with the database so this is an example of an orm which i think is object relational mapper and we can output all of our dependencies in a file if we want so we can say pip3 freeze and put this in requirements.txt so anytime you add a new dependency you'll want to do that just so all of our requirements are in this text file so whoever uses this project in the future can get the dependencies then we can just create our file so we'll say application.py and that's going to create this application.py file which is where we're going to do our coding so to start off we'll just create a basic flask application so we'll say from flask import flask and then we say app is flask underscore underscore name underscore underscore right there so that's how we set up flask and what we can do now is we can make a simple route basically an endpoint by saying app.route and giving it a path and then we can define a method that we want hit when someone visits this route so all we're going to do for right now is just return a string hello all right so let's just make sure this is working so what we can do is run our application to do this we're going to create a few environment variables real quick so flask app is application application.py and the flask environment is development and you're going to need to do that anytime you open up your terminal so if you x out of your terminal and then reopen it those are going to go away so you'll need to do those again and then you just say flask run all right so this is where our website's located and we'll just open that all right already made a stupid mistake we don't put the colon here just after the uh method so do a refresh now this needs to be uppercase there we go should be everything all right we got our app up and ready to go so the very first thing i want to do is make a get request so we're going to make an app to store drinks so we'll say app dot route and the path for this is just going to be drinks and we'll say deaf get drinks and it's going to return something we'll just say drinks right now but that's not a thing so what we need to do is we need to put some code here to make it a thing if you want to just test it out for right now what you could do is you could return a dictionary and let's just say we got drinks and we'll just put drink data for right now so we should be able to save that and it'll automatically refresh and then when we refresh our page or we go to actually forward slash drinks and we get some data back in json so it's sort of working now we just got to worry about connecting to a database so to do this with the object relational mapper we basically define all of the things we want to store in our database as models so we're going to create a class so we can do that up here and all we're going to do is we're going to say class drink and for sql alchemy we just say db.mod so it's going to inherit from this so it's already going to have various built-in functionalities and that's how we can use it with sql alchemy so then we define the columns and we're going to put three of them in here so we're gonna have an id and the way you create a column is by saying db.column and passing in any attributes of it so it's going to be an integer and then we set it as the primary key by saying primary key is true next up we're going to have a name which is db column and this one is going to be a string so to do that you say db string and you can pass in a max length we'll just say 80. and another attribute in here is unique true if you want the name to be unique and you can also say nullable is false so you can't have any nulls then the last one on here we're going to use is description and we'll say db.column and this is going to be a string as well and we'll just give this 120 characters however i'm not going to put any other attributes on the description now we want to override another method in here and that is called the rep wrapper method repr for uh representation probably and for this we we pass in self which refers to the object so we can grab the object's attributes by saying self dot something so we're just going to return a string and this will be invoked whenever we try to print out the the drink in the list so you'll see what i mean here soon so we'll say f to make a parameterized string and we can say self.name and then maybe you know a hyphen and then self.description all right cool so that is how we create a model and what we're going to do is we're going to set up our database with a table for drinks and to do that the easiest way is to use the python terminal so what i'm going to do is i'm going to quit our server control c and then i'm going to say python3 so that's going to open up the interactive mode in python and what you can do is you can say from application import db so what we do is we import our database from application import database however all we did is define the model we need to actually make this connection to the database in our code first before we can reference it so to do that we're going to go up here and say from flask sql alchemy import sql alchemy so all lower case and then sqla is capital here then to get that db variable we just say db is an instance of sql alchemy and we're going to pass in our flask app so that's the setup for sql alchemy the last thing we have to do is we need to configure our database so we can connect to it so we say app.config and we're going to pass in a string here sql alchemy database dot u r i and you don't have to have all of this stuff memorized you can find this in the documentation for flask fairly uh simply and then we're going to say sqlite and then three forward slashes data.db so that's how we say we're going to create an sqlite database called data.db in the same directory and then i think this db variable actually will come after this config so we'll paste that there and there we go so we should be able to x out of the python interactive mode restart it and now we should be able to do is say from application which refers to our application because we named application.py import db great we didn't get any errors we did get this warning here uh warning us about significant overhead and you can change some settings but you really don't have to worry about that so to create our tables we say db dot create all hit enter and you can see it actually creates the database as well since we didn't have that now because this is what's known as an object relational mapper the way we work with our relational database is with objects so if we want to create a new drink we create a drink object and we can assign it to a variable called drink and the way we pass in data to create a drink is we do a named parameters so we can say name is grape soda and then a comma description uh i don't know tastes like grapes maybe seems pretty fitting so that is how we create oh and you see when we do this name drink is not defined so anytime we want to use something from our file we have to import it so this class drink needs imported as well so from application import drink and now we should be able to use the up arrow key to bring back our previous code hit enter and now we have a drink object and you can see it by typing in drink and it says grape soda tastes like grapes and that is where this repr method comes in it basically the name hyphen and the description now to add it to our table we say db.session dot add drink and then db.session.commit and that's an important step yeah we want db.session.com not doctor so db dot session commit now we should be able to get all of our drinks by saying drink dot query dot all hit enter and you can see it's a list now with just one element grape soda so if you wanted to add another drink what we can do is go through that process again so we'll do this one in line so we'll say db.session dot and we'll create a drink the name we'll call this one cherry and we'll give it this description and this cherry drink i drink tastes exactly like this cherry ice cream so that i used to eat so it tastes like that one ice cream all right perfect hit enter and then db.session.commit now let's check drink.query.all hit enter and now you can see we have multiple elements we have grape soda and cherry so then we can exit and go back to flask let's say flask run so we got our server running but now we need to create a way to get those drinks inside of this route right here so it's going to be pretty similar to what we did earlier if i can scroll up just a little bit we said drinks.query.all so let's go ahead and do that in this code right here we will say drinks is equal to drink dot query dot all unfortunately it's not something that we could just put right here by saying drinks that'd be nice but i'll show you what happens so what we can do is if we refresh this page and it says object of type drink is not json serializable i've worked around trying to figure out how to make this as easy as possible i i really didn't come up with too many great ideas but here's basically what i decided we're just going to build a list so we're just going to basically write out what the json should look like so we're going to say output is just an empty list from here what we're going to do is we're going to iterate through the drinks so we'll say for drink in drinks and we're going to describe what it will look like inside of a dictionary so the end goal is to have a list of dictionaries so we'll just say drink data is a dictionary where name comes from drink.name and the description comes from drink dot description like so and then once we got that dictionary all we have to do is say output dot append and pass in drink data so that's going to add that dictionary to this list right here and it's going to do that twice one for each drink that's currently in in the database and then what it'll do is we'll just say drinks and pass in output instead so now we have a nice list of dictionaries and that should be serializable so we can do is do a refresh over here and there we go we have an outer object and then key value pairs one key with the pair of a list of dictionaries so a very similar format to how the api for stack overflow looked now what i want to do is i want to create the ability to pass in an id in here so let's say we passed in a1 and we were able to get the first drink so let's go ahead and build that functionality i'm going to clean up my screen just a little bit here because we're not going to need this terminal right now i'm just going to shrink that and i'm going to hide our different files on the side there so what we do now is we create a new route so dot route and this is also going to be two drinks and then forward slash and you can use less than and greater than signs to define a parameter here so that's going to be substituted for a specific number now a lot of people debate on whether this should be plural or singular since we're grabbing one drink i decided to do it plural and i'll show you why so i found the stack overflow question singular or plural name of resource while creating it and this person talks in here and you know there's a bunch of different thoughts in here about the best way to do it and as i was reading this i looked up at the web address and i saw questions plural with the id so i was like hm i think i'm sold i'm just going to keep it plural so that is why i decided that so let's go back to our code in here and we're going to create a new method so we'll say def get drink and this one's going to have a parameter id so instead of having a drinks variable we're going to have a drink variable and now we're just going to get a drink so to do that we can say drink dot query dot get or 4004 it's kind of a tongue twister there and from here we can pass in the id that's going to give us a drink object and then we can just return that and build a quick dictionary so we'll say jsonify and we're going to build out the json the key is going to be name that's going to come from drink.name and then the second key is going to be description and that's going to come from drink.description so dictionaries are serializable instantly you actually don't even have to call jsonify here so you can just return a dictionary like so but sometimes you'll need to call jsonify if you're not working with a dictionary so i think that should work let's save and let's go back to our web page and you can see we get one drink back and we can try it again with id2 we get that second drink and then we try id3 and we get not found because there's not a third drink in there now i wanted to show you real quick if you go back to id2 here you can right click inspect and get a little bit more information about this request so hit network and do a little refresh you can see this request here and it's a get request the response was 200 okay and you can see the content type is application json it's a little bit different than if you're on a web page we can do is we can inspect on here and go to network get that first request on here and that's 200 okay also get but this time the content type is text forward slash html so yeah just want to call that out for you guys let's go ahead and go back and now i want to talk a little bit about adding a new drink so let's go ahead and create another route on here we'll say app.route the path is going to be drinks and you can actually have another parameter in here which is methods and say post which is good to do if you're defining for a post request you can put any of the methods in here you could put get or delete or whatever and you can actually condition so you could check to see what method the person's requesting so you could you could in theory define all of this in one method and then you know check to see if they're trying to get all the drinks or add all of the drinks however i like to just have a little bit more separate so i put them in separate methods here and we'll just create a separate method so add drink now this one's going to be a little bit more complicated because we actually have to get the request data so when the person calls this they're going to pass in the structure of what a drink should look like so we're going to get this by creating a new drink and where are the attributes for the drink going to come from well the name is going to come from request dot json so that's how you can access the json data that they send it's through request.json and we're going to be looking for name and we're going to do the same exact thing for the description and that is going to come from request.json description we go now we can add these by saying db.session.add and pass in the drink db.session.commit then what we can do we can return whatever we want we could say successfully added or you could do the id so if you wanted to return the id it's going to look like return id colon drink dot id so that id attribute is going to be added to this drink object so that's pretty convenient save that and now let's give it a try so we'll go over to here but we can't really pass in all the data for our requests real easily so this is where postman comes in handy so from here what we can do is we can define what a drink should look like in json inside of the body of our request and then we just set it to post and also we'll want to update our web address so you can copy that from right here paste that there and what we're going to do is we're going to give this a name zoom in a little bit what's the name gonna be uh we'll call it cola and then the description is delicious all right so just check everything is right we got body raw json post and the correct web address hit send we got an error on line 42. let's go back to our code real quick looks like we might have some kind of formatting issue here unexpected name request for request to work i think we need to do another import from flask so we'll say request there and hopefully that'll do the trick i'm also getting another warning down here i think we need to uh take this and move it up a line it wasn't causing any issues but best practice there all right let's go back down in our code and it looks like we don't have any more warnings so we will go back to postman and hit send and it looks like we're making progress okay so the issue here is that we're not using the right web address so we need to go to drinks no forward slash and hit send so that was nice that that worked and in this situation it returns the id of three so now we can get all of the drinks we can still keep this body here we don't have to delete that hit send and you can see all the drinks there or you could pass in the id of three hit send and you can get that new one last thing i want to talk about is how to delete a drink so let's go ahead and go back to our code and create a new route we'll say app.route the path is going to be drinks and we're going to take the id so that way we know which drink to delete and then for the methods we're going to say delete there we go and we'll say def delete drink so for this to delete a drink we're going to say db dot session dot delete and pass in the drink structure the best way to get this drink structure i thought would just be to get it from the database so we're going to create a variable drink and say dot drink.query.get and pass in the id so i'll take the id as a parameter from this web address and then after we delete we say dbe dot session dot commit and i was having a little bit of an issue now in general i haven't done a lot of like error checking and different edge cases however i was getting it where i would delete a drink and it wouldn't exist and i would get an issue so i decided just to add a little bit of extra casing here so if drink is none what we're going to do is we're just going to return and i'm just going to say something like error not found or something or you could return a 404 just showing some different options here and you know if that doesn't happen then i'm just going to assume everything's good and we're just going to return uh we'll say message and i don't know we'll just say something like yeet there we go okay let's test this one out for this what we're going to do is we're going to do a delete and we don't have to pass in anything with the body just to show you guys i'll delete that just to make sure it's clear we do pass in the id here however hit send and it says yeet if we hit send again it says error not found so that is how you do the most basic api calls we have the ability to get all the drinks a specific drink add a drink or delete a drink i didn't really do anything for updating a drink but a drink is so simple like i feel like you could just delete a drink and then re-add it or if you want to practice you could try some put requests here but that's all i got for you guys for the basics of creating an api in python it's a lot more to it but hopefully that'll get you started next if you want to like you know study more you know study different error codes and just different cases you know what happens if they submit the wrong structure or what happens if the api is offline there's so many different scenarios so building out a fully functional good api is quite some work so thank you guys and let's get back to uh the chalkboard i guess so that's my introduction to rest apis lots of information stay tuned for the upcoming video and be sure to subscribe you
Info
Channel: Caleb Curry
Views: 209,286
Rating: 4.9675951 out of 5
Keywords: rest api, rest apis, python api, api introduction, flask rest api, python flask, get, post, put, delete, put vs post, post vs put, idempotent, sqlalchemy
Id: qbLc5a9jdXo
Channel Id: undefined
Length: 52min 50sec (3170 seconds)
Published: Thu Nov 19 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.