Basic CRUD With Flask 1.0.2 , Swagger & SQLAlchemy
This article requires you to implement tutorial install SQLAlchemy to Flask 1.0.2. We also will use this article to implement basic skeleton for Swagger in our Flask project. If you haven’t read it, I suggest you follow those two articles first before we can try to implement SQLAlchemy to our Flask & documented by Swagger.
Alright, assuming you’ve implemented two articles I suggested before, now we can proceed on how to work with basic CRUD in Swagger with SQLAlchemy. We’ll work with api.py from this article from now on. Let’s install SQLAlchemy for now using this command:
$ pip install flask-sqlalchemy
We also need marshmallow to serialize JSON result to our API:
$ pip install marshmallow
Now let’s modify api.py (assumed you’re already using api.py from this article) line 1 to line 7 to be like the code below:
First we’ll implement POST method to accept JSON data so we can insert record first. Let’s modify the POST method at line 48 to 59 to be like the code from like 48 to 59 below:
Cool, now if you run your app and access localhost:5000/docs you can see something like this on your Swagger:
As you can see we have detail parameter to be inputted into Log table. You can insert two records now at least so we can go to GET all logs section and show all records we have inserted here. Let’s modify GET method from line 43 to line 46 to be like code from line 43 to 50:
Now if you try your Swagger (maybe you need to restart your app if not change) you can see the result like this in GET all logs method where I previously added two records before accessing this page:
Cool, now we have two records with id 1 and id 2. Let’s proceed to /my_api/{id} which is used to display record detail in REST practice. Let’s modify the code from line 76 to 79 to be like the from line 76 to 91:
Now you can access GET /my_api/{id} and insert 1 to the parameter and get result as follow:
Let’s implement PUT /my_api/{id} by modifying the code from line 93 to 96 to be like the code below from line 93 to 113:
if you edit PUT /my_api/{id} like the picture below you can see the result:
Great! Now, we’ll proceed to the last part for our REST which is DELETE. Let’s modify the code from line 115 to 118 to be like the code below from line 115 to 132:
Congratulation, we have implemented the very fundamental REST in Flask with Swagger & SQLAlchemy. This code is still messy I know. However, my main concern for now is to make the tutorial as easy as possible to understand. Next article we’ll try to make this code looks nicer!