banner



What Are The Python Modules Used To Get The Data From Rest Api

RESTFul API is an advance concept of web development that implemented at server and used with HTTP method (Become/ POST/ PUT/ DELETE) to handle the data. The HTTP asking methods and resources are identified using URIs and handled functionality accordingly.

If you're thinking about implementing Python RESTful API, then you're here at correct identify. In our previous tutorial yous have learned about implementing RESTFul API with CodeIgniter. In this tutorial, you lot will learn how to create Python RESTFul API using MYSQL.

Nosotros will comprehend this tutorial with alive case with HTTP methods like (GET/ Post/ PUT/ DELETE) to implement Python RESTFul API with Grime operations.

We hope you have installed Python in Your Windows or Linux with Python and its packages. Here we are using Python 3.x.four version. We will use flask, flask-mysql and flask-cors module.

As well, read:

  • Create RESTful API using CodeIgniter
  • Creating REST API with Golang
  • Create Uncomplicated Balance API with PHP & MySQL

Then allow'south create RESTful API using Python and MySQL. We have project directory restful-api-python and the major files are:

  • config.py
  • app.py
  • main.py

Step1: Create MySQL Database Tabular array

As nosotros volition implement RESTful API to perform CRUD operations, then we will create MySQL database table emp to perform operations. And so first we will create MySQL database residual-api and and so create table emp using beneath table create statement.

CREATE Table `emp` (   `id` int(11) NOT Zip,   `name` varchar(255) Non NULL,   `email` varchar(255) NOT NULL,   `telephone` varchar(16) DEFAULT Null,   `address` text DEFAULT Zilch ) ENGINE=InnoDB DEFAULT CHARSET=latin1;  Alter Tabular array `emp`   ADD PRIMARY KEY (`id`);    Alter Tabular array `emp`  Alter `id` int(xi) NOT Zero AUTO_INCREMENT;        

Step2: Import Flask Modules

Every bit we handle handle Rest API functionality using Flask and MySQL, then nosotros will need both the modules. The module Flask works as web framework while MySQL module require to make connection with MySQL database.

So first we will create project directory restful-api-python and move inside using cd command.

Then we will install flask module by running below command.

pip install Flask        

we will as well install flask-cors extension for handling Cross Origin Resource Sharing (CORS), making cross-origin possible.

pip install -U flask-cors        

So now we volition create the app.py Python script and import the flask module and create the flask instance to apply with MySQL module. We will also import code>flask-cors extension for cross-origin.

from flask import Flask from flask_cors import CORS, cross_origin  app = Flask(__name__) CORS(app)        

Ste3: Create MySQL Connection

We need to install Flask-MySQL extension that allows you to admission a MySQL database. Nosotros will install Flask-MySQL extension using below command.

pip install flask-mysql        

We volition create config.py Python file to initialize MySQL database connectedness details to make connection with MySQL database. We will import the app script to handle MySQL database connectedness with Flask-MySQL module.

As nosotros take already created MySQL database rest-api, so nosotros volition connect by providing connection details.

from app import app from flaskext.mysql import MySQL  mysql = MySQL() app.config['MYSQL_DATABASE_USER'] = 'root' app.config['MYSQL_DATABASE_PASSWORD'] = '' app.config['MYSQL_DATABASE_DB'] = 'residue-api' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app)        

Step4: Create REST API Grime Operation

We volition create main.py script and import the app and config modules. We will connect to MySQL database and implement Grime operations by defining all Remainder URIs.

Here nosotros have used Mail HTTP method to create new employee records to MySQL database. We have used Become HTTP method to get all employee records or individual tape and used PUT HTTP method for employee record update. Too implemented DELETE HTTP method to delete record. If there are no tape found then defined 404 method to handle not found error.

import pymysql from app import app from config import mysql from flask import jsonify from flask import flash, asking  @app.route('/create', methods=['Mail service']) def create_emp():     try:                 _json = request.json         _name = _json['name']         _email = _json['email']         _phone = _json['phone']         _address = _json['address']	         if _name and _email and _phone and _address and request.method == 'Mail service':             conn = mysql.connect()             cursor = conn.cursor(pymysql.cursors.DictCursor)		             sqlQuery = "INSERT INTO emp(name, email, phone, address) VALUES(%s, %s, %due south, %s)"             bindData = (_name, _email, _phone, _address)                         cursor.execute(sqlQuery, bindData)             conn.commit()             respone = jsonify('Employee added successfully!')             respone.status_code = 200             return respone         else:             return showMessage()     except Exception equally due east:         impress(eastward)     finally:         cursor.close()          conn.close()                 @app.road('/emp') def emp():     try:         conn = mysql.connect()         cursor = conn.cursor(pymysql.cursors.DictCursor)         cursor.execute("SELECT id, proper noun, email, phone, address FROM emp")         empRows = cursor.fetchall()         respone = jsonify(empRows)         respone.status_code = 200         return respone     except Exception as due east:         impress(e)     finally:         cursor.shut()          conn.shut()    @app.route('/emp/') def emp_details(emp_id):     attempt:         conn = mysql.connect()         cursor = conn.cursor(pymysql.cursors.DictCursor)         cursor.execute("SELECT id, name, email, phone, accost FROM emp WHERE id =%s", emp_id)         empRow = cursor.fetchone()         respone = jsonify(empRow)         respone.status_code = 200         return respone     except Exception as eastward:         print(eastward)     finally:         cursor.shut()          conn.close()   @app.road('/update', methods=['PUT']) def update_emp():     endeavor:         _json = request.json         _id = _json['id']         _name = _json['proper name']         _email = _json['electronic mail']         _phone = _json['phone']         _address = _json['address']         if _name and _email and _phone and _address and _id and request.method == 'PUT':			             sqlQuery = "UPDATE emp SET name=%s, email=%s, phone=%s, address=%s WHERE id=%due south"             bindData = (_name, _email, _phone, _address, _id,)             conn = mysql.connect()             cursor = conn.cursor()             cursor.execute(sqlQuery, bindData)             conn.commit()             respone = jsonify('Employee updated successfully!')             respone.status_code = 200             return respone         else:             return showMessage()     except Exception every bit eastward:         impress(e)     finally:         cursor.close()          conn.close()   @app.route('/delete/', methods=['DELETE']) def delete_emp(id): 	endeavor: 		conn = mysql.connect() 		cursor = conn.cursor() 		cursor.execute("DELETE FROM emp WHERE id =%s", (id,)) 		conn.commit() 		respone = jsonify('Employee deleted successfully!') 		respone.status_code = 200 		return respone 	except Exception equally e: 		impress(eastward) 	finally: 		cursor.close()  		conn.close()                  @app.errorhandler(404) def showMessage(fault=None):     message = {         'status': 404,         'bulletin': 'Record not found: ' + request.url,     }     respone = jsonify(bulletin)     respone.status_code = 404     return respone          if __name__ == "__main__":     app.run()                              

Step5: Run Application

Now we volition go the project directory restful-api-python and execute the the command python chief.py and the server will start on default port 5000. At present we will utilize Postman to run our Python RESTful API with (POST, GET, PUT or DELETE) methods to test it.

We will run the beneath URL with HTTP Go method to get the all employee and brandish information in JSON format.

http://localhost:5000/emp        

The following JSON data response will be returned:

We volition become the employee record in JSON information with id 1 using below URL with GET HTTP method.

http://localhost:5000/emp/1        

The response will be JSON data:

We will create new employee record with Post HTTP method.

http://localhost:5000/create        

The request torso will exist post-obit:

The response volition JSON information employee add message.

We will update existing employee tape with #i using PUT HTTP method.

http://localhost:5000/update        

The request body will be post-obit:

The response volition employee record update bulletin.

We will delete existing employee with id #three using DELETE HTTP method.

http://localhost:5000/delete/iv        

The response volition employee tape delete message.

Yous accept completed tutorial nearly Python RESTFul API using Flask and MySQL with examples. You can further implement this into your projection according to your requirement. If you have whatever query, you lot can submit your precious comments. Thanks!

Y'all may also like:

  • User Direction System with PHP & MySQL
  • Datatables Add Edit Delete with Ajax, PHP & MySQL
  • Build Helpdesk System with jQuery, PHP & MySQL
  • Build Online Voting Arrangement with PHP & MySQL
  • School Management System with PHP & MySQL
  • DataTables Add together Edit Delete with CodeIgniter
  • Create RESTful API using CodeIgniter
  • Build Reusable Captcha Script with PHP
  • Product Search Filtering using Ajax, PHP & MySQL
  • Image Upload and Crop in Modal with jQuery, PHP & MySQL
  • Build Button Notification System with PHP & MySQL
  • Project Management System with PHP and MySQL
  • Hospital Direction System with PHP & MySQL
  • Build Newsletter System with PHP and MySQL
  • Skeleton Screen Loading Upshot with Ajax and PHP
  • Build Discussion Forum with PHP and MySQL
  • Customer Relationship Management (CRM) Organisation with PHP & MySQL
  • Online Exam System with PHP & MySQL
  • Expense Management System with PHP & MySQL

You can download full the script from the Download link below.

Download

What Are The Python Modules Used To Get The Data From Rest Api,

Source: https://webdamn.com/create-restful-api-using-python-mysql/

Posted by: dupreysomighten.blogspot.com

0 Response to "What Are The Python Modules Used To Get The Data From Rest Api"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel