Building a simple REST API using Python & Flask | Daily Python #14

Ajinkya Sonawane
Daily Python
Published in
5 min readJan 19, 2020

This article is a tutorial on how to create a Rest API using Python and Flask.

This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.

I have previously covered how to utilize various APIs using Python. This article will cover the creation of an API to access the MYSQL database. You can create an API and use it in different projects. If you want to utilize a database in multiple projects, then simply create an API that can make this easy.

Requirements:

  1. Python 3.0
  2. Pip
  3. MySQL Server

Install the following packages:

  1. flask — Lightweight WSGI web application framework.
  2. mysql-connector — MySQL driver to access the MySQL database.
pip install Flask mysql-connector

What is a Rest API?

Let’s say you’re trying to find videos about Python on Youtube. You open up Youtube, type “Python” into the search field, hit enter, and you see a list of videos on Python. A REST API works in a similar way — You search for something, and you get a list of results back from the service you’re requesting from.

An API is an application programming interface. It is a set of rules that allow programs to talk to each other. The developer creates the API on the server and allows the client to talk to it.

REST determines how the API looks like. It stands for “Representational State Transfer”. It is a set of rules that developers follow when they create their API. One of these rules states that you should be able to get a piece of data (called a resource) when you link to a specific URL.

Let’s start by creating a database using MySQL

Run the MySQL Command Line Client

After connecting to the MySQL server using this command-line client, create a database with a name of your choice.

Now, create a table in this database.

We will be using the ‘articles’ table to fetch data using our API.

Insert some data into this table.

Let’s see how the data looks

Let’s start building our API to fetch these articles from the database

Import the required modules

from flask import Flask, jsonify
import mysql.connector

Let’s write a function to establish a connection with MySQL Server

mydb = None
def createConnection():
global mydb
mydb = mysql.connector.connect(
host="127.0.0.1",
user="YOUR_MYSQL_USERNAME",
passwd="YOUR_MYSQL_PASSWORD",
database="dailypy"
)
print(mydb)
createConnection()

Now, we write a function to fetch articles based on a keyword

def get_articles(keyword=''):
cursor = mydb.cursor()
cursor.execute("Select * from articles where name like '%"+keyword+"%'")
articles = cursor.fetchall()
jsonResult = []
for article in articles:
jsonResult.append({
'ArticleName':article[0],
'ArticleLink':article[1]
})
return jsonResult
from pprint import PrettyPrinter
pp = PrettyPrinter()
pp.pprint(get_articles())
Snip of the Output of above code snippet

Now, we create a Flask app by simply creating an instance of the Flask module

app = Flask(__name__)

We need to define a function which produces some output for requested URL

@app.route('/')
def pageLoad():
return jsonify({"Welcome Message " :"Hello There, visit 127.0.0.1:1234/articles"})
@app.route('/articles')
def loadAllArticles():
response = get_articles()
if len(response) == 0:
return jsonify({"Error":"Sorry could not find any articles"})
else:
return jsonify(response)
@app.route('/articles/<keyword>')
def loadArticlesByKeyword(keyword):
response = get_articles(keyword)
print(response)
if len(response) == 0:
return jsonify({"Error":"Sorry could not find any articles with keyword "+keyword})
else:
return jsonify(response)

The ‘/’ route is mapped with the pageLoad function which displays the welcome message when the URL is requested. The ‘/articles’ route is mapped with loadAllArticles which loads all the articles and the ‘/articles/<keyword>’ is mapped with loadArticlesByKeyword function which will fetch articles related to the given keyword.

Let’s run the app and see how the API works:

if __name__ == '__main__':
app.run(port=1234,debug=True)
App is active

Home Page — http://127.0.0.1:1234/

Welcome Message

All Articles — http://127.0.0.1:1234/articles

All articles

Articles by keyword — — http://127.0.0.1:1234/articles/LinkedIn

Articles by keyword

Requests using cURL:

Welcome Message
All articles
Articles by keyword

This was a simple tutorial on building an API using Python and Flask. You can modify this code and create something useful for your project.

I hope this article was helpful, do leave some claps if you liked it.

Follow the Daily Python Challenge here:

--

--