Build a REST API with Flask, Marshmallow and PostgreSQL

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there how's it going everyone in this video we're going to be showing how to build a simplest api using ask and marshmallow so with me here i have my visual studio code open i'm going to be using postgresql as my database and i'm going to use insomia as my testing tool for the api so to get started i'll first create the virtual environment so to do that i'm going to type python minus m then i mean save them then call my virtual environment env so this is going to create a virtual environment within our folder now once this is done the next step will be to activate the virtual environment so once this is done i'm going to activate the virtual environment by saying source env script and activate this is going to activate our virtual environment now once our virtual environment has been activated the next thing is going to be to install the packages that are required for our projector we need to install we need to install flask sql alchemy because that's what we use as our orm i'm also going to install marshmallow since it's what we're going to use for our object serialization and i'm also going to install the database driver for postgresql i'm going to install the binary and then install this is going to fetch these packages and install them within a virtual environment knowing till these packages are finished installing so once these packages are finished installing the next thing is going to be to create a requirements to txt file so i'm going to pick freeze are the requirements to requirements dot txt this is going to create a requirement for txt file with all the necessary requirements so when i open this file we see that all our packages have been installed and the next thing is going to be set up our flask server so i'm going to create a file which i made called app.play and then up to apply i'm going to create the first case this one main safety task i'm going to import and i'm going to create the app instance so app is equal to ask and then you pass in the import name which is name now after passing in the import name the next thing is going to be to create our route so since we're going to create an api let's create a test also i mean all this test route so this is going to be slash going to define its view function so let me just call it hello once i do that i need to just return hello hello world let me save this so i may try and assert by saying if if name is if or true if name is equal to main i'm going to run the app by saying up to trend since we're developing i'm going to say the back is going to be for true true once this is done we save and then the server so i'm going to come say python app.pi within a virtual environment and this is going to start our app so if i be able to make a request to that endpoint so i'm going to come and create another request these are the other routes that we're going to implement and which just create this only that's called a dummy request to test it just to test if our server is returning correct responses so i mean send this to localhost 5000 when i send this it's going to return hello world as the response now the next thing is going to be to set up our database so right now i have pj admin which is the gui tool for postgres i'm going to create a database so i open up my pj admin i create a database here so i'm going to say create i'm going to create a database now this database is being created so i'm going to give it a name let me call it recipes and i'm going to give it the owner so that all now this is going to be post address and then i'm going to save this database is going to be created for us and it's what you're going to use for our api now once our database has been created the next thing is going to be to create a database model so i'm going to use sql alchemy for that so remember i installed sql alchemy within our requirements so it's here which is going to act as our orm it's going to help us to create objects that will help us to model our database so let me create our model so to do that i mean say from flask sqlr3 import sql alchemy so once i do that i'm going to create the dba instance i'm going to create the instance of sql outcome by saying the sql community photo app now when i save this we are going to notice that some errors have been occurred areas like sql data sql academy database uri has not been said so let's set that i'm going to do that slightly above that sql instance so i'm going to say app dot config and this is going to be sql alchemy that's our base uri it's going to be now we're going to pass in the connection string to our sql sql database so in this case we're using postgresql and we are going to name and the name of the database we are going to use is called recipes so we are going to write postgresql and we write the print trade the connection string as so we're going to write the name of our database user who is postgres and the password of that user so i'm going to write the password is this password and once i write this password i'm also going to write the post so which is localhost let me change this so this is going to be localhost and then slash the database so this is going to be database which is recipes so when i save this we are going to see that another error is being shown which is rsq alchemy track modifications so i'm also going to set that to course and say update config this is going to be sql alchemy track modifications and this is going to be equal to false i mean save and you see that now our server is showing no errors so once that is done the next thing is going to be to create our model so our model is going to be showing the way our database is going to be so our recipe is going to have a going to have a name a description going to have a name and a description and it will also have a unique id which is going to be the unique identifier for each recipe in our database so to create our model i'm going to create a class so this class is going to be called recipe and this class is going to inherit from sqlcaming.org so i'm going to say db watch model now once i do this i'm going to attach the id which is going to be the primary key so i'm going to say id is going to be equal to db db it's going to be an integer and then it's going to also be the primary key so we said primary key attribute get the primary key attributes to true in this case and next thing we need is that is the name column so in so i mean say name going to be db and the next thing is going to be specifying the type so this case is going to be string so again say it's going to be a string of characters 255 and we don't want it to be now so against another going to be called false for that column the next thing is going to be to set the description so the description is going to be text so we're going to say description entry before 2db dot text and the descript db.text and we are going to actually this is our column so let's say db.column and this is going to be db.text and the next thing i'm going to say is valuable is going to be called force now for convenience when querying our database we shall need methods or what they call managers but to simplify all that we are going to create our own methods that are going to help us to query our database for example let me first create that first method that's going to help us to retime string representation of our objects so i'm going to do that by creating a function called danda repre this is going to take himself taking the current object and then it's going to return the name of that recipe now the next thing i'm going to do is to write a function that's going to help us to query for all the recipes in the database so to do that i'm going to create a class method so i'm going to call this class method and then create function so this is going to be get all i'm going to call it get all so it's going to take in that class and the next thing is going to just return class dot query dot all now query.org is a manager that is that is that helps us to query uh model classes with sql can we and then dot all specifies that we need a list of all the instances or other objects of the recipe class within our database so this will return our recipes in our database now we also need to create i'm going to arrange create another method which i made called class method and this is going to return one by its id so i can call it i can call it yet by id and then i pass in a class and then the id so this will return so we're going to write class dot query dot get what you want is to get a specific object with that id and then return for zero phone not found in that object is not found so i mean say it or zero four it offers zero four then we pass in the id so this is supposed to look for that object and if it does not exist the server will return your phone found error now once that is done i'm also going to create methods that are specific to the objects themselves that will help us to delete as well as to commit those changes to the database so to do that i'm going to write a method which i'm going to call f and this is going to be sales so this is going to be saving the instance of the object in this case now i'm going to be using ep dot session so we're going to add it to the session first then this is going to be the session.add and then this is going to add a current object which itself and then we shall finally commit it to the database by saying db.session and what this method is going to do is to get that object that you should operate out of this class and add it to the sql communication as well as to save it to the database the next thing is going to be a method that's going to help us to be convenient when deleting with our recipe objects so we're going to create that method and i'm going to call it delete and screen taking the current object which is going to be self now and it takes itself the next thing we're going to do is to add it to the sql academy session so we're going to say db.session but actually this is going to be calling that delete method then we specify that object so the object is going to be that the current object which itself and then we finally commit the changes to database say independent.session dot commit now after doing this the next thing we're going to do is to create a serializer class now remember we're using marshmallow in this video marshmallow helps us to serialize these objects and turn them to data that you can be able to receive as json i'm going to import marshmallow and also create a serializer class from marshmallow so which is going to be a schema so i'm going to come to the top of the code nxf from from marshmallow we need to import schema and then the fields now these fields help us to specify the different fields that we have for our class that you want to serialize for example you can serialize the id field and the name field and the description and the schema is what helps us to act as a model for which we're going to serialize our database model so let's try to do this so i'm going to create that class uh mod the serializer class i'm going to create a which i'm going to call a recipe schema this is going to be the schema from which i'm going serialize our recipe model and it's going to inherit from schema the next thing is going to be specifying the fields for that class so you need to specify the id side is going to be our fields this is going to be an integer so it's a fields but this is going to be an integer and we can also specify that name the name is going to be fields but this is going to be a string so green specified it's going to be a string and we can also say that description is going to be also type string so i'm going to say fields string once we've created our serializer class the next thing is we are going to create these card routes that are going to help us to create read update and delete resources as and you access them via routes so let me go to our api and now we see that different routes that you want to implement so we're going to create one that helps us to get a list of recipes uh create a recipe update delete a recipe and get a recipe by its id so let's do this we need to come here and we've set up our server now let's first create our database model let's migrate them to the database so i'm going to save this i'm going to create a simple and okay see and we having an error here so we are having has no attribute integer so let me fix this so we're going to go to our serializer class and we fix this so this is going to be integer and save i run our app again so our app is now running successfully so i mean stop it for now and you want to create a database so i'm going to open python i'm going to open the python interactive console and once i open that next thing is going to be to import which is recipe and i'm also going to import let me say from app i'm going to import our recipe class which is our model class i'm also going to import that sql alchemy instance which is deep in this case so import them the next thing is going to be running db dot create all so that's our database table is created so in iran db dot create all we are seeing that there is no password that is applied now we are having a personal password supplied so this means that we didn't specify the password for our postgresql so let me check this [Music] see that i provided the password however so let me try to fix that so you need to pull up the documentation so i mean say ask sql me say possible sql and i'm going to look for the sql query let me actually look for the sql team index so i'm going to go to that box and look for that connection so i'm going to look for the configuration so connection your i format once i go to this i'm going to look at postgresql we added three so let me remove one so when i save this it will open the console so i'm going to first exit out of it and we open it with python now when i open this console we are going to we are going to create a database so i made first import the database that are submitted from app watch our database model which is recipe and then the sql community instance which is db um when i import this successfully imported let's try creating our database by saying db dot create all so this is going to create our database so i'm going to go back to our postgresql and try to access our database table so i'm going to go to schemas and when i go to schemas i'm going to search for tables and when we look at our tables we are having our table created and now we need to check for our columns so when i check for columns i see that we now have our columns created for id name and description once that is created the next thing is going to be to create the different routes that are going to help us to do the acquired operations on our api so you need to go to visual studio code and we create the first route and let me delete this demi route so let's first create all the routes i need save at route and this is going to be slash recipes and i mean just say it get all recipes so this is going to be one that works with a get request to get our recipes and i'm just going to pass it for a moment let me even pass in the methods using the first way implementing it so i mean same methods equal to it and this is going to be pass then i'm also going to say at app dot route so we're also going to say our recipes and this in this case is going to be methods is equal to so this case is going to be post and we need to create the view function which is going to be create a recipe i'm just going to we're also going to pass this for now now we're also going to create the one that's going to help us to to get one recipe so i'm going to say apple trout in this case it's going to be the recipe and we shall access it by its id which is an integer so i mean say inch id and say that the method in this case is going to be the gate method since we are getting the recipe i'm going to create a v function which is going to be get recipe then i pass in the id within the view function going to pass now i'm also going to create the route that's going to help us to update our recipe now this is going to take in the url which is going to be recipe slash inch id actually realize i did a mistake here so me has created so which time they said and also add the methods list so in this case the method is going to be because they're going to be updating our recipe so this is going to be the view function and say that and screen taking the id of the recipe to update so we're going to pass this now we're also going to create one last route which is going to be for deleting recipes so in this case we're going to pass in app dodge route then we pass in slash recipe so we need to be recipe slash methods the method this is going to be delete once this is done i'm going to create every function it's going to be delete recipe once i do this i'm going to add the id and then pass now let's implement the different functionalities for creating a reading and updating and deleting our recipe resources from our api so let me first exit out of this console and when i run we enter run python this is going to run our server once our server is running we are going to implement this so i'm going to begin by implementing the route that gets all the recipes from the database our database is empty for now so let's first query for all for an empty list or an empty object that returns uh an empty query set of recipes in our database so let me do this so i'm going to come here let's say recipes it's going to be for true our recipe class is going to be recipes dot so remember i created the convenience method that's going to help us to query for all the recipes within our database so i'm going to go here and that is get all will say recipes don't get all once we do that i'm going to we're going to now create an instance of our serializer class which is the recipe schema marshmallow then we're going to say that our okay let's see we can call it the serializer so i'm just going to call it the serializer in this case is going to be a recipe schema and this schema will create an instance of it so once you want to return recipe data we are going to to just call that damp method on this recipe schema so let's try to do that so i'm going to say data in this case it's going to be um let's say it's going to be serializer but i'm so you're going to hold down so i mean says serializer.damp and then you pass in the data one to serialize so in this case it's going to be the recipe's data so again say recipes now if we want to return json we are going to use the j75 function that comes with flask now i'm going to import j75 from flask so it's from flask import flask and i'm also going to import j75 so we're going to return our http response at json so i'm going to come and say send and this is going to be returned j75 and we are going to return the data so i'm going to just return adjacent if i and we shall remove this and what we shall return is that letter so let me try let me save this and run so let's make a request to localhost 5000 slash recipes and see what we shall get so i'm going to go to insomnia and get a list of recipes so we need to save localhost we need to add the url for our request i'm going to build 5000 slash recipes and i send a get request to this we expect an empty list of recipes so i'm going to send and this is going to return a dictionary or an object digestion object and this is because we expected a list but we never specified that we wanted a list i'm going to go back to our code and what you shall realize is we have our serializer class but if we just instantiate it and we do not specify that we want a list it's going to return the data as an object in json so let's specify that we want a list of this data so i'm going to do this by adding a mini is equal to true when i say mean is equal to true let me change this we need to be main is equal to true and then save and i save this and i resend the request we are going to see that it's going to return an empty list of recipes so let me send and now this is going to return an empty list of recipes so let's try to implement a route that's going to create our recipes so to do that i'm going to come this side and go to the route and which is sending the post method so i'm going to come and say i'm going to remove that pass and first thing we shall do is to get the data from our client as json so i'm going to import the request object from flask import request on import request i'm going to come down to our route and specify that we want our data as request but it json now we expect that our client is going to send data in form of json and this method get json helps us to get that data as json so once we get that that has json the next thing is going to be to create an object of the our model class which is recipe this one and then form an object out of the data we've got as json so to do that we need to say you your ecp is going to be our recipe class and we then create an instance of that class so that name the name attribute of this new object is going to be a data dot get so in this case we want to get the name attribute from the json and want to also get the description and this description is going to be a description from convergation so we're going to say this description now i expect that this data is going to be sent as the body of the request that's going to be that post request from our client so we'll change this variable to description and i'm going to change this to name let's check if our model has more fields we only have name and description which is good and the next thing would be to call our ins our conveniency method that you created that's going to save this this object so i'm going to say new recipe but save this is going to save this instance and we're also going to call our serializer class so that it serializes and returns our object as json to show that that request has been successful so to do that i'm going to just say serializer and i'm going to call that recipe schema so i'm going to create an instance of the recipe schema class once i do that the next thing is going to be to return the data so our data is going to be the serializer and we call that that method on the serializer we're going to pass in our newly created resume so this is going to be the new receipt and we agree to return the response as json so we're going to use js25 and we shall return the data and we can also specify the method that http status code that you want on this status being successful so when you create a resource we use the 201 created status code so i'm going to save this and let's go back to our client so when i go back to insomnia i'm going to go to my uh create a recipe post post url so i mean that in so it's going to be localhost we're going to be locals 5000 slash recipes now all we want is the body from this request so i'm going to specify the body i'm going to come and specify that we need to add a body and that body is going to be chasement so let's specify our body so i'm going to add the body what you want is a name so i specify k as name then i add a value let me call that um milk milk bread so to test this i'm also going to add a simple description so you can say description it's going to be you say make for now let's just say make da [Music] milk and once we do that we try to test this out so i'm going to send and when i send this we see that our our request has been successful and it has returned that 201 created created status code which means that the request has succeeded and the new resource has been created which is good so let's try to implement the next round so the next route is going to be the one that returns a simple uh recipe by its id so the first thing we'll need to do is to query the database for that recipe with a certain id and then return that object as json so to do that you created the convenience method so i'm going to do that by saying um recipe going to be going the recipe class then what get by id then we specify that the id want is the one from the view function that is going to be id so i'm going to return this as json so what i'm going to do is to create the serializer in serializer it's going to be for instance of recipe schema class and we are going to return our data as a result of serializing that object with current so we're going to say actualizer is going to damp that object which is going to be our recipe once this is done we are going to return this data as an http response but it's going to be in form of json so i'm going to use the s75 into return a75 and range return the data now the status code in this case will be 200 so i'm going to save let's try doing this with our client so i'm going to go back to insomnia and in this case we're going to get our recipe by its id so i'm going to specify that we want localhost let's see the url 3cp slash id in this case it's going to be locals 5000 slash recipes and the id is going to be one in this case so i'm going to send this and you see that we've been able to get our resource return let's just implement a remaining route so we're going to implement the route that helps us to update the recipe so i'm going to come to the quad and read first query for that specific recipe would like to update submit a variable and they call it recipe so update this is going to be recipe let's get id and then i pass in the id that comes with a view function so that's going to be id and once i do that we are going to re to get the data as json the data that you want to update so we're going to say data it's going to be go to request what get json and the next thing is to update so to update we're just simply going to say sap to update dot name so when we say the name want to just set that to the data we get from our client that is going to be our name so it's going to be data.get name and then we're also going to say recipe update dot a description all right it's going to be go to letter but get description when we do this we are going to simply save these changes to the database so it says db dot session dot commit and this will basically save our updated object in the database so after doing that we are going to return this as json response so we're going to create our serializer sorry it's a serializer it's going to be go through our recipe schema class and after doing that we want to return the data so we're going to say um uh recipe data so i mean say recipe data it's going to be co2 serializer dot damp and this case what you want to dump is the recipe to update so i mean it's a recipe to update and we're going to return this as json so i mean it's a return uh j75 so i said js75 i'm going to just modify the recipe data let's say return is 25 then it's going to be recipe data and we want to return a status code of 200 so let's try to test this so i mean save as i was going to restart and when i go to our installment i'm going to go to that specific card so let me copy this url since it's the same for updating so i'm going to go to update and then i'm going to paste in the url and i have to specify the body updated body so let me first go back to the post so i'm going to copy this body and go to update so try to change this so instead of doing milk bread let me try saying milk these kids so when i send this we are seeing that response is returning okay which means that our object has been updated let's try to get it so i'm going to go to get a recipe by its id and when i go to the recipe i'm going to get it and we get the milk biscuits which means that our object has been updated successfully so let's try to also create that route that deletes so i'm going to come to delete and the first thing is going to be to query that recipe you would like to delete i need to say recipe true delete it's going to be recipe but get my id and one passing the id that comes from the view function then all we have to do is to say recipe to delete dot delete since we created the convenience method that's going to delete for us this object so let's check that out so i'll go back to our model class so you have that delete method that takes in that object and then deletes it so we are going to come here recipe to delete or delete and all we have to do is to return um return j75 and we want to say that um we are just trying to pass in a message so we need to pass it deleted and since we've deleted this we are just going to return the message deleted and set as code of 204 so let me save this now after doing this let's test that route so i'm going to come here and come and sell a course so let me try to post in the url let me actually write it intel of course five thousand recipe one so when i send this it's saying no content which means that that specific object has been deleted and nobody is returned for a response so let's try to test all the routes that we've created in this video so when i try to get um a list of recipes so let's try to get a restaurant recipes it's going to return an empty list since we do not have any recipe in our database let's try to create a recipe so in a go and create a recipe and send is going to to create the recipe and return to zero one created so let's try to get our recipes to get a list recipes when i send we see that a list of recipes has been um created let's try to create other recipes so i'm going to try to send send send so that we have many recipes in our database so when i get a list of recipes we have a list of recipes up to id5 up to so let me try to get one recipe by its id so if we get recipe one it's not found and we are being returned not found error so let's try to fix this instead of our api returning this not found page what you want to do is to return a not found error so basically flash helps us track those error handler the functions but let's try to do that so i mean say at app dot error handler and i'll pass in that specific area that you want to catch so i mean it's a 5 500 and this is going to be in case we have an internal server error so we are going to return so i write internal server error and in this function what you want to do is to just return a response that's showing us that we have that 500 error so what you're going to do is to d25 and virtual pastor is a dictionary containing a message and that message is going to be there is a problem so this will be at the server so it is i won't be able to know what's happening so let's try to also create the not found error so if i say that update error handler a passing 404 then every function in this case is going to be not found then i pass in error so i'm going to just return j75 and we're going to put in a message and the message is going to be resource and found so let's try to save this and we go back to our api so when i send see that our our api is returning resource not found however the status code is to zero 200. so let's try to fix this so i'll just add the status quo as four zero four let me save i'll also add the status quo here which is going to be 500 so when i save i'm going to try to run this and then we see that we are returning an error code of 404 in this video we've been able to create a rest api using flask postgres and marshmallow if you feel you've watched this video and learned from it please leave a like and please subscribe to the channel for more content like this thank you for watching and see you in the next video
Info
Channel: Ssali Jonathan
Views: 11,438
Rating: undefined out of 5
Keywords: flask, flask rest api, rest api, python flask rest api, flask rest api with sqlalchemy & marshmallow, flask marshmallow rest api, rest api with sqlalchemy & marshmallow, flask build rest api, rest api flask and python, python flask, flask api, python and flask rest api, api, rest api in python and flask tutorial, flask tutorial, flask restful api, marshmallow, postgres, python rest api tutorial, flask restful api with tokens
Id: EAokwpPMVdc
Channel Id: undefined
Length: 45min 26sec (2726 seconds)
Published: Sun Jun 06 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.