Loading

Rest API Using Flask and Python

Rest API Using Flask and Python

Flask is a micro web framework of Python , as it's a microframework it does not require particular tools or libraries.

api.png

Step 1 : Install Flask using pip

             pip install Flask         

Step 2 : Creating Flask App

    from flask import Flask

    app = Flask(__name__)

    @app.route('/', methods=['GET', 'POST'])
    def welcome():
        return "Hello World!"

    if __name__ == '__main__':
        app.run(host='localhost', port=5000) 

Save this in a file as (.py) extension. Go to terminal and type python (i.e. python .py )
After executing the command it should show something like below in the terminal

ter.png

Launch any web browser and go to http://localhost:5000/ to see the app in action.

Now,understanding the code line-by-line:

from flask import Flask→ Import the Flask class

app = Flask(__name__)→ Create an instance of the class

@app.route('/', methods=['GET', 'POST']) → We use the route() decorator to tell Flask which URL should trigger the method. Methods specify which HTTP methods are allowed. The default is ['GET'].

if __name__ == '__main__'__name__ is a special variable in Python which takes the value of the script name. This line ensures that our Flask app runs only when it is executed in the main file and not when ,it is imported in some other file.

app.run(host='localhost', port=5000) → Run the Flask application,host specifies the server on which we want our flask application to run. The default value for host is localhost or 127.0.0.1. "0.0.0.0" -> all IPv4 addresses on the local machine.

Request Params :

    @app.route('/<int:number>/') 
        def incrementer(number):
        return "Incremented number is " + str(number+1)
    @app.route('/<string:name>/')
        def hello(name):
        return "Hello " + name

Open the browser and go to http://localhost:5000/world , you will see the output as "Hello world" and when you go to http://localhost:5000/10 the output will be incremented number is 11.

MySQL Database Connection :

Flask uses flask_mysqldb connector to use MySQL. Run the following command to install the package:

   pip  install flask_mysqldb

Database connection Flask-MySQL as follows:

  from flask_mysqldb import MySQL
   app = Flask(__name__)
    #MYSQL CONFIGURATION
    app.config['MYSQL_HOST'] = 'localhost'
    app.config['MYSQL_USER'] = 'root'
    app.config['MYSQL_PASSWORD'] = ''
    app.config['MYSQL_DB'] = 'flask'
        mysql = MySQL(app)

  #Creating a connection cursor
    cursor = mysql.connection.cursor()

  #Executing SQL Statements
    cursor.execute(''' CREATE TABLE table_name(field1, field2...) ''')
    cursor.execute(''' INSERT INTO table_name VALUES(v1,v2...) ''')
    cursor.execute(''' DELETE FROM table_name WHERE condition ''')

#Saving the Actions performed on the DB
    mysql.connection.commit()

#Closing the cursor
    cursor.close()    

Since MySQL is not an auto-commit DB, we need to commit it manually. Like, save the changes/actions performed by the cursor execute on the DB.

    from flask_mysqldb import MySQL

    app = Flask(__name__)

    app.config['MYSQL_HOST'] = 'localhost'
    app.config['MYSQL_USER'] = 'root'
    app.config['MYSQL_PASSWORD'] = ''
    app.config['MYSQL_DB'] = 'flask'

    mysql = MySQL(app)

    @app.route('/add', methods = ['POST', 'GET'])
      def add():
            if request.method == 'POST':
                  name = "Test"
                  age = 11
    cursor = mysql.connection.cursor()
    cursor.execute(''' INSERT INTO user VALUES(%s,%s)''',(name,age))
    mysql.connection.commit()
    cursor.close()
    return "Done!!"
  app.run(host='localhost', port=5000)    

Add this code, with the existing code. Restart the flask server. But before restart the server, we have to start the MySQL server for that I have used xampp. You can use any other tool like MySQL workbench. To create a database and table to perform the SQL execution.

Launch any web browser and go to http://localhost:5000/add , check the database table it will create a new row in the user table.

app.py

from flask_mysqldb import MySQL

app = Flask(__name__)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'test'

mysql = MySQL(app)

@app.route('/')
def index():
    return "Hello World"


@app.route('/add', methods = ['POST', 'GET'])
def add():
    if request.method == 'POST':
        name = "Test"
        age = 11
        cursor = mysql.connection.cursor()
        cursor.execute(''' INSERT INTO user VALUES(%s,%s)''',(name,age))
        mysql.connection.commit()
        cursor.close()
        return "Done!!"


app.run(host='localhost', port=5000) 


Related Articles

Leave a Reply

Comments