How to build CRUD API using Flask, MYSQL

How to build CRUD API

How to build CRUD API using Flask, MYSQL

Prerequisites:


1. Python3.
2. MYSQL server downloaded and ready to run.
3. Flask.

 

Setting Up Our Back-end Environment:

We need to run the following commands to install the library:

pip install flask_restplus

pip install flask

pip install mysql

Pip is a package installer for Python and it comes with Python. Flask is a popular Python web framework, meaning it is a third-party Python library used for developing web applications.

Flask-RESTPlus is an extension for Flask that adds support for quickly building REST APIs. Flask-RESTPlus encourages best practices with minimal setup.

It provides a coherent collection of decorators and tools to describe your API and expose its documentation properly (using Swagger).

REST or RESTful Methods

HTTP methods are mapped to CRUD (create, read, update and delete) actions for a resource. Although you can make slight modifications such as making the PUT method to be create or update, the basic patterns are listed as follows.

  • GET: Get/List/Retrieve an individual resource or a collection of resources.
  • POST: Create a new resource or resources.
  • PUT: Update an existing resource or collection of resources.
  • DELETE: Delete a resource or collection of resources.

Now as our project’s environment is ready, let’s get our hands dirty!

Step 1. Create the below app.py script(py is the extension to indicate Python script) where we import the flask module. Notice how we create flask instance.

from flask import Flask 

from flask_restplus import Api, Resource, fields

app = Flask(__name__)

Step 2.  Setup the MySQL database configurations for connecting to database. We need to configure database connection with flask module and that’s why we have imported app module and setup the MySQL configuration with flask module.

from flask_mysqldb import MySQL

app.config[‘MYSQL_USER’] = ‘root’

app.config[‘MYSQL_PASSWORD’] = ”

app.config[‘MYSQL_HOST’] = ‘localhost’

app.config[‘MYSQL_DB’] = ‘crud’

app.config[‘MYSQL_CURSORCLASS’] = ‘DictCursor’

mysql = MySQL(app)

Step 3. Next we will define all the models required for the request format. This we can integrate with the api and swagger. This will tell the user what API is expecting. 

<script src=”https://cdn.snipit.io/e.js” data-sid=”41583″></script>

Step 4. Next we will define all REST URL for performing CRUD operations. It will also connect to MySQL database server and query the database to read, insert, update and delete.

<script src=”https://cdn.snipit.io/e.js” data-sid=”41582″></script>

Let’s see the things in Action 

To run the python Script we need to execute to the following command in the directory where python script is present.

Command – python app.py

The server will get start at http://127.0.0.1:5000/

 

Swagger Url – http://127.0.0.1:5000/

Flask Restplus CRUD

Post API

Post API

GET API

GET API

 

Share this post