Build Simple RESTful API using Python and MySQL

REST stands for Representational State Transfer. RESTful Web services are one way of providing interoperability between computer systems on the Internet. Rest API helps to communicate between the client app and the server application. REST is an architecture style for designing networked applications. A REST API defines a bunch of functions in which developers can perform requests and receive responses via HTTP protocols such as GET and POST.
In this tutorial, you will learn how to create CRUD (create, read, update, delete) operation REST API using Python and MySQL. This is a very simple example, you can just copy-paste, and change according to your requirements.
Hope you have installed Python in Windows/Linux with Python and its packages. I am using Python 3.7 version. Using Flask and MySQL module.
Before started to implement the REST API using Python, look files structure:
  • restful-api-using-python
    • config.py
    • app.py
    • main.py
Understanding REST API
REST provides a block of HTTP methods which are used to alter the data. The following are common HTTP methods:
  • GET — is used for reading and retrieving data.
  • POST — is used for inserting data.
  • PUT/PATCH — is used for updating data.
  • DELETE — is used for deleting data.
Step 1: Create MySQL Database and Table
For this tutorial, you need a MySQL database with the following table:
Step 2: Create file named app.py
We import the flask module. Here we are coding flask instance.
Step 3: MySQL Connection
Create MySQL database configurations for connecting to the database
Step 4: Create REST API CRUD
Create a file named main.py and and import the app and config modules
  • Connect to MySQL database and implement CRUD operations
  • create_student() — Add student Record. (using POST methods)
  • update_student — Update student Record. (using PUT methods)
  • student() — Get all student Records. (using GET methods)
  • student(student_id) — Get single student record. (using GET methods)
  • delete_student() — Delete Student Record. (using DELETE methods)
Step 5: Run Application
Now we will go the project directory restful-api-using-python and execute the command python main.py and the server will start on default port 5000. Now we will use Postman to run our Python RESTful APIs.
The output will be like below:
Create student record (using POST method)
Request Body:
JSON Response: “Student created successfully.”;
Update student record (using PUT method)
Request Body:
JSON Response: “Student updated successfully.”;
Display all student (using GET method)
Request Body:
Display single student record (using GET method)
Request Body:
Delete student record (using DELETE method)
JSON Response: “Student deleted successfully.”;