Introduction

We will create an example on how to use query parameter in REST API GET request with Python Flask. HTTP GET method is used to fetch data from the server. So here we will use GET method to fetch data from server and send to the client.

Query parameter is used with GET method to fetch data from server based on such query parameter’s value. Actually when you need to search or filter data from server side instead of fetching all data then you can use such query parameter.

Prerequisites

Python 3.7.4, MySQL 8.0.17, Flask 1.1.1

Example

Let’s say we want to fetch data from MySQL database and we have a table user in the MySQL server.

So we will use query parameter to fetch single user from the MySQL table user.

Creating Table

Let’s create a MySQL table user with the following structure.

CREATE TABLE `user` (
  `user_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(45) DEFAULT NULL,
  `user_email` varchar(45) DEFAULT NULL,
  `user_password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Table Data

Let’s say we have the following entry into the MySQL table:

insert into `user`(`user_id`,`user_name`, `user_email`, `user_password`) 
values (4, 'Soumitra', '[email protected]', ' pbkdf2:sha256:150000$UDhO5tWt$75afe6b64ad7e24ed221569aafa9a350d71f005156fe7b81b34b33bea4e30fd8');

Creating Project Directory

Create a project root directory called python-flask-rest-api-query-param.

We will put all our Python files under the root directory. In the below sections we may not specify the project root directory but we will speak with respect to the root directory.

Configuring Flask API

Flask is a light-weight and very good framework for building web based applications.

Configuring the flask API globally as shown below we can use app variable throughout the application.

Put the below code into app.py file.

from flask import Flask

app = Flask(__name__)

Configuring Flask and MySQL

We are going to fetch data from MySQL table, so we need to configure flask and MySQL to work together.

Creating a file called db.py to include the below configurations.

from app import app
from flaskext.mysql import MySQL

mysql = MySQL()
 
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'roytuts'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

Configuring REST Endpoint

Create a file called rest.py where we will write our REST andpoint to fetch user information from the MySQL table.

We will create only one endpoint to fetch data from MySQL database. Here we will use query parameter to fetch the user information based on user’s id.

import pymysql
from app import app
from db import mysql
from flask import jsonify, request

@app.route('/user')
def get_user():
	conn = None;
	cursor = None;
	try:
		id = request.args.get('id')
		if id:
			conn = mysql.connect()
			cursor = conn.cursor(pymysql.cursors.DictCursor)
			cursor.execute("SELECT user_id id, user_name name, user_email email, user_password pwd FROM user WHERE user_id=%s", id)
			row = cursor.fetchone()
			resp = jsonify(row)
			resp.status_code = 200
			return resp
		else:
			resp = jsonify('User "id" not found in query string')
			resp.status_code = 500
			return resp
	except Exception as e:
		print(e)
	finally:
		cursor.close() 
		conn.close()

In the above file we are importing the required modules to work on our REST API.

We have the endpoint as /user with query parameter id. So the actual endpoint is /user?id=<int value>. The full URL is http://localhost:500/user?id=<int value>, i.e., http://localhost:5000/user?id=4. Here we are running the server on localhost and default port is 5000.

Related Posts:

We are fetching query parameter’s value using the below code snippets:

id = request.args.get('id')

Then we execute SQL statement for the given id and if user found then we send the retrieved user information as a JSON to the client.

Running the Application

Navigate to the project’s root folder and type command python rest.py, your server will start at http://localhost:5000.

Testing the Application

Once your server gets started and up, you can test the GET request with query parameter.

We are using Postman to test our REST API. You can use any REST client tool or curl command to consume your service.

By executing the GET request with query parameter you will see the output as shown in the below image:

query parameter in rest api get request with python flask

Hope you got an idea on query parameter used in the above REST API.

Source Code

You can download source code.

Thanks for reading.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *