How to create a REST API for managing users using Python Flask and MySQL

Part of the data source: ChatGPT 

introduction

        In modern application development, the database is a very important component. Relational databases (eg MySQL, PostgreSQL) are especially popular for this. Flask is a Python web framework ideal for implementing REST APIs. In this post, we'll walk through how to create a REST API for managing users using Python Flask and MySQL. If you are a newbie, this article will be for you.

In this article, we will:

  • Install required software and tools
  • Create a Python Flask application
  • Implement a REST API

Install required software and tools

Before starting, you need to make sure you have installed the following software:

  • Python (at the time of writing, the latest version is Python 3.8)
  • MySQL database (at the time of writing, the latest version is MySQL 8.0)

You also need to install the following Python libraries:

  • Flask(pip install Flask
  • mysql-connector(pip install mysql-connector-python

Create a Python Flask application

We are now ready to start writing Python code. Open a text editor of your choice (such as Visual Studio Code), create a new file, we will name the file app.py. In this file, we first import the required libraries and modules. Here, we need to import the MySQL driver and the Flask library.

import mysql.connector
from flask import Flask, request, jsonify

Next, we need to connect to the MySQL database. From here, we'll create a database object named , which connects to the database (named management_system) . mydbWe need to specify the username and password of the MySQL server. This will allow us to manipulate MySQL using Python.

mydb = mysql.connector.connect(
    host="localhost",
    user="root",  # 替换为您的MySQL用户名
    password="password",  # 替换为您的MySQL密码
    database="management_system" # 数据库名称
)

Now, we can create a Flask application object. Create a new Flask application object named "app".

app = Flask(__name__)

After this, we need to define two routes. One for creating/adding new users and one for getting all users. Use a decorator @app.route()to define a path for the application. Use methodsparameters to define allowed HTTP methods. For the route to create a user, we use the POST method, and for the route to get all users, we use the GET method.

@app.route('/users', methods=['POST'])
def create_user():
    # 从页面中获取用户信息
    name = request.json['name']
    email = request.json['email']
    phone = request.json['phone']

    # 使用MySQL驱动程序在MySQL数据库中插入新用户
    cursor = mydb.cursor()
    sql = "INSERT INTO user (name, email, phone) VALUES (%s, %s, %s)"
    val = (name, email, phone)
    cursor.execute(sql, val)
    mydb.commit()

    # 返回一个JSON响应以表示用户已成功添加
    return "User created successfully"

@app.route('/users/get', methods=['GET'])
def get_all_users():
    # 从MySQL数据库中获取所有用户信息
    cursor = mydb.cursor()
    sql = "SELECT * FROM user"
    cursor.execute(sql)
    users = cursor.fetchall()

    # 将所有用户信息存储在一个列表中
    user_list = []
    for user in users:
        user_list.append(user)

    # 返回以JSON格式表示所有用户的响应
    return jsonify(user_list)

Now, our Flask application is ready to go. We just need to run it on the command line with:

python app.py

This command will start our Flask application running on port 5000 on localhost. You can now /usersadd new users to the route with a POST request, or request the route with a GET request /users/getto get information about all users.

full code 

import mysql.connector
from flask import Flask, request,jsonify

app = Flask(__name__)

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="password",
    database="management_system"
)


@app.route('/users', methods=['POST'])
def create_user():
    name = request.json['name']
    email = request.json['email']
    phone = request.json['phone']

    cursor = mydb.cursor()
    sql = "INSERT INTO user (name, email, phone) VALUES (%s, %s, %s)"
    val = (name, email, phone)
    cursor.execute(sql, val)
    mydb.commit()

    return "User created successfully"


@app.route('/users/get', methods=['GET'])
def get_all_users():
    cursor = mydb.cursor()
    sql = "SELECT * FROM user"
    cursor.execute(sql)
    users = cursor.fetchall()

    user_list = []
    for user in users:
        user_list.append(user)

    return jsonify(user_list)

if __name__ == '__main__':
    app.run(debug=True)

  

Summarize

        In this article, we learned how to create a REST API using Python Flask and MySQL database to manage users. We first installed the required software and libraries and connected to the MySQL database. We then created a appFlask application object called and defined two routes. One for adding new users and one for getting all user information. Finally, we started the Flask application and tested our REST API. If you're new, this example is a great way to learn how to build your first REST API, especially if it pertains to MySQL.

Guess you like

Origin blog.csdn.net/weixin_43263566/article/details/131119433