Python API with Flask

 Python API with Flask


  • Install python from below link
        https://www.python.org/downloads/
        


  • You can check if the python installation is success or not by running below command in command prompt
        python --version

  • Then you have to set up the environment to run the python application. In command prompt run below command. Note that you have mention the python version
        py -2 -m pip install virtualenv

  • Create a python file and name it as app.py
  • Add below code as the first step and first sample API in the app.py file
    


  • Now if you are added the environment properly you can see play icon in right side of the vs code. Click that and application will run on port 5000.


  • Browse the url



  • This will return the array as a html type (check network of inspect). If you want to return it as a json you want to change the code as below


  • The result will be like below


  • Now create a sample text file and insert sample json code. Define another route for the new API



    CRUD operation using MySQL

  • Install MySQL library (you have to set the Script path of python in environmental variables to run the pip commands)
        pip install flask_mysqldb

  • Import relevant libraries to the app.py
        from flask import Flask, render_template, request, jsonify         from flask_mysqldb import MySQL

  • Now let's connect the database
        


  • Just with the above set-up, we can’t interact with DB tables. For that, we need something called a cursor.
  • To create the connection with cursor,
        cursor = mysql.connection.cursor()

  • To create tables and run SQL queries,
        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 ''')

  • To save the action performed in the Database,
        mysql.connection.commit()

  • To close the cursor,
        cursor.close()


    Sample Login Application

  • Create a table in MySQL called info_table
  • Create a simple html page and design a form in it


  • Connect the database and insert user data into the table using cursor in app.py


  • Run the program and check

  • We can do this operation using pymysql also. To do that import pymysql and make the connection. Then using cursor you can do run the queries you want.

  • Well Done!!!


Comments

Popular posts from this blog

Load balance with NGINX

First Step to Laravel

Send Email through Laravel