[ad_1]
RESTFul API is an advance idea of net improvement that applied at server and used with HTTP methodology (GET/ POST/ PUT/ DELETE) to deal with the info. The HTTP request strategies and sources are recognized utilizing URIs and dealt with performance accordingly.
In the event you’re desirous about implementing Python RESTful API, then you definately’re right here at proper place. In our earlier tutorial you have got discovered about implementing RESTFul API with CodeIgniter. On this tutorial, you’ll learn to create Python RESTFul API utilizing MYSQL.
We are going to cowl this tutorial with dwell instance with HTTP strategies like (GET/ POST/ PUT/ DELETE) to implement Python RESTFul API with CRUD operations.
We hope you have got put in Python in Your Home windows or Linux with Python and its packages. Right here we’re utilizing Python 3.10.4 model. We are going to use flask
, flask-mysql
and flask-cors
module.
Additionally, learn:
So let’s create RESTful API utilizing Python and MySQL. We’ve mission listing restful-api-python
and the main recordsdata are:
Step1: Create MySQL Database Desk
As we’ll implement RESTful API to carry out CRUD operations, so we’ll create MySQL database desk emp
to carry out operations. So first we’ll create MySQL database rest-api
after which create desk emp
utilizing beneath desk create assertion.
CREATE TABLE `emp` ( `id` int(11) NOT NULL, `identify` varchar(255) NOT NULL, `electronic mail` varchar(255) NOT NULL, `telephone` varchar(16) DEFAULT NULL, `tackle` textual content DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `emp` ADD PRIMARY KEY (`id`); ALTER TABLE `emp` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
Step2: Import Flask Modules
As we deal with deal with REST API performance utilizing Flask
and MySQL
, so we’ll want each the modules. The module Flask
works as net framework whereas MySQL
module require to make reference to MySQL database.
So first we’ll create mission listing restful-api-python
and transfer inside utilizing cd
command.
Then we’ll set up flask
module by operating beneath command.
pip set up Flask
we may even set up flask-cors
extension for dealing with Cross Origin Useful resource Sharing (CORS), making cross-origin potential.
pip set up -U flask-cors
So now we’ll create the app.py
Python script and import the flask
module and create the flask
occasion to make use of with MySQL
module. We may even 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 have to set up Flask-MySQL
extension that means that you can entry a MySQL database. We are going to set up Flask-MySQL
extension utilizing beneath command.
pip set up flask-mysql
We are going to create config.py
Python file to initialize MySQL database connection particulars to make reference to MySQL database. We are going to import the app
script to deal with MySQL database reference to Flask-MySQL
module.
As we have now already created MySQL database rest-api
, so we’ll join by offering connection particulars.
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'] = 'rest-api' app.config['MYSQL_DATABASE_HOST'] = 'localhost' mysql.init_app(app)
Step4: Create REST API CRUD Operation
We are going to create principal.py
script and import the app
and config
modules. We are going to connect with MySQL database and implement CRUD operations by defining all REST URIs.
Right here we have now used POST
HTTP methodology to create new worker data to MySQL database. We’ve used GET
HTTP methodology to get all worker data or particular person file and used PUT
HTTP methodology for worker file replace. Additionally applied DELETE
HTTP methodology to delete file. If there aren’t any file discovered then outlined 404 methodology to deal with not discovered error.
import pymysql from app import app from config import mysql from flask import jsonify from flask import flash, request @app.route('/create', strategies=['POST']) def create_emp(): attempt: _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.methodology == 'POST': conn = mysql.join() cursor = conn.cursor(pymysql.cursors.DictCursor) sqlQuery = "INSERT INTO emp(identify, electronic mail, telephone, tackle) VALUES(%s, %s, %s, %s)" bindData = (_name, _email, _phone, _address) cursor.execute(sqlQuery, bindData) conn.commit() respone = jsonify('Worker added efficiently!') respone.status_code = 200 return respone else: return showMessage() besides Exception as e: print(e) lastly: cursor.shut() conn.shut() @app.route('/emp') def emp(): attempt: conn = mysql.join() cursor = conn.cursor(pymysql.cursors.DictCursor) cursor.execute("SELECT id, identify, electronic mail, telephone, tackle FROM emp") empRows = cursor.fetchall() respone = jsonify(empRows) respone.status_code = 200 return respone besides Exception as e: print(e) lastly: cursor.shut() conn.shut() @app.route('/emp/') def emp_details(emp_id): attempt: conn = mysql.join() cursor = conn.cursor(pymysql.cursors.DictCursor) cursor.execute("SELECT id, identify, electronic mail, telephone, tackle FROM emp WHERE id =%s", emp_id) empRow = cursor.fetchone() respone = jsonify(empRow) respone.status_code = 200 return respone besides Exception as e: print(e) lastly: cursor.shut() conn.shut() @app.route('/replace', strategies=['PUT']) def update_emp(): attempt: _json = request.json _id = _json['id'] _name = _json['name'] _email = _json['email'] _phone = _json['phone'] _address = _json['address'] if _name and _email and _phone and _address and _id and request.methodology == 'PUT': sqlQuery = "UPDATE emp SET identify=%s, electronic mail=%s, telephone=%s, tackle=%s WHERE id=%s" bindData = (_name, _email, _phone, _address, _id,) conn = mysql.join() cursor = conn.cursor() cursor.execute(sqlQuery, bindData) conn.commit() respone = jsonify('Worker up to date efficiently!') respone.status_code = 200 return respone else: return showMessage() besides Exception as e: print(e) lastly: cursor.shut() conn.shut() @app.route('/delete/ ', strategies=['DELETE']) def delete_emp(id): attempt: conn = mysql.join() cursor = conn.cursor() cursor.execute("DELETE FROM emp WHERE id =%s", (id,)) conn.commit() respone = jsonify('Worker deleted efficiently!') respone.status_code = 200 return respone besides Exception as e: print(e) lastly: cursor.shut() conn.shut() @app.errorhandler(404) def showMessage(error=None): message = { 'standing': 404, 'message': 'Report not discovered: ' + request.url, } respone = jsonify(message) respone.status_code = 404 return respone if __name__ == "__main__": app.run()
Step5: Run Utility
Now we’ll go the mission listing restful-api-python
and execute the the command python principal.py
and the server will begin on default port 5000. Now we’ll use Postman to run our Python RESTful API with (POST, GET, PUT or DELETE) strategies to check it.
We are going to run the beneath URL with HTTP GET
methodology to get the all worker and show knowledge in JSON format.
http://localhost:5000/emp
The next JSON knowledge response shall be returned:
We are going to get the worker file in JSON knowledge with id 1 utilizing beneath URL with GET
HTTP methodology.
http://localhost:5000/emp/1
The response shall be JSON knowledge:
We are going to create new worker file with POST
HTTP methodology.
http://localhost:5000/create
The request physique shall be following:
The response will JSON knowledge worker add message.
We are going to replace current worker file with #1 utilizing PUT
HTTP methodology.
http://localhost:5000/replace
The request physique shall be following:
The response will worker file replace message.
We are going to delete current worker with id #3 utilizing DELETE
HTTP methodology.
http://localhost:5000/delete/4
The response will worker file delete message.
You might have accomplished tutorial about Python RESTFul API utilizing Flask and MySQL with examples. You possibly can additional implement this into your mission in line with your requirement. When you’ve got any question, you may submit your valuable feedback. Thanks!
You might also like:
You possibly can obtain full the script from the Obtain hyperlink beneath.
[ad_2]
Source_link