Query Parameter in REST API: GET Request with Python Flask

Introduction

I 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 I 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 – 3.9.1, MySQL 8.0.17 – 8.0.22, Flask 1.1.1 – 1.1.2

Example

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

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

MySQL Table

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

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

Table Data

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

insert into `user`(`user_id`,`user_name`, `user_email`, `user_password`) 
values (4, 'Soumitra', 'sou@email.com', ' pbkdf2:sha256:150000$UDhO5tWt$75afe6b64ad7e24ed221569aafa9a350d71f005156fe7b81b34b33bea4e30fd8');

Project Directory

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

I will put all our Python files under the root directory. In the below sections I may not specify the project root directory but I 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 you 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

You are going to fetch data from MySQL table, so you 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 you will write our REST andpoint to fetch user information from the MySQL table.

I will create only one endpoint to fetch data from MySQL database. Here I 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 I am importing the required modules to work on our REST API.

I 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 I am running the server on localhost and default port is 5000.

Related Posts:

I am fetching query parameter’s value using the below code snippets:

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

Then I execute SQL statement for the given id and if user found then I 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.

I am 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

Download

Leave a Reply

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