Creating a REST API using Python Flask

Few interesting things about me:
- Software Engineer @ JP Morgan Chase & Co.
- AWS Community Builder 2023
- I love working with technology
- I enjoy playing video games 😄
Search for a command to run...

Few interesting things about me:
No comments yet. Be the first to comment.
In this series, I cover creating an API using Python Flask right from scratch, connecting it to a database and later deploying it.
Welcome to Part 2 of the Flask Series. If you have been following along, you'd have a simple API in Flask which returns your favorite games. If you haven't, simply clone this GitHub repository and install flask and dotenv packages. What we did the la...
If you’re new to machine learning, reinforcement learning, especially, then it’s completely okay to have a hard time understanding these fancy jargons in front of you. Here’s my attempt to simplify these while we work on a little robo-car :) About AW...

Dynamo DB is AWS's NoSQL offering in the vast set of managed databases as a service that they provide. Like most other services, it's fully serverless, flexible and easy to scale. The Data Model As we're working on NoSQL here, there's no real restric...

I was recently a part of a hackathon and was found searching for good Jupyter environments on the cloud to be able to work on my ML Project. Soon enough, I found myself here. However, it took me a while to figure out how powerful it truly can be. F...

I spend 5 days out of a week coding for work, so I'm definitely not motivated to code a lot on weekends. This means that I do not have any software development tools installed on my personal machine. Not even IDEs. However, being the curious little g...

Almost a week to this and not a lot of drama on Indian Twitter, so I thought I could write about it. TLDR: Malicious code with a backdoor was added to one of the core packages of Linux affecting almost all Debian and Redhat distros; was later discove...

Initially as a developer, I always thought there are only two aspects of a full stack application, you have the frontend, you straight up connect it to a database, fire queries and you're good to go.
As I kept learning more about backend technologies and what they offer, I understood the importance of database security, server-side abstraction, etc.
If I have a client side application, I can still directly connect it to a database, say using a MySQL driver in case of an SQL database. And yes, you could do that, it is completely possible. Which brings the question -
When you connect your client-side application directly to a database, your database credentials and the raw queries you fire remain on the client-side, which could be seen by anyone since your application is running on a web browser. Not just that, in case of SQL for instance, running raw SQL queries from the client means that your application would be vulnerable to SQL injection .
For further clarity on why you shouldn't be creating a direct connection to your database from the frontend, I'd suggest reading this article from Academind.
Flask is a lightweight Python web framework which helps you to create basic web applications.
Flask is called a "micro" framework because it doesn't directly provide features like form validation, database abstraction, authentication, and so on.
Having said that, Flask is easy to setup, a lot less complex as compared to other frameworks.
Create a new project folder and create a Python virtual environment inside of it.
mkdir sample-flask-app
cd ./sample-flask-app
# Linux
sudo apt-get install python3-venv # If needed
python3 -m venv .venv
source .venv/bin/activate
# macOS
python3 -m venv .venv
source .venv/bin/activate
# Windows
py -3 -m venv .venv
# Use forward slashes if you are using Git Bash
.venv\scripts\activate
Update pip and install the modules flask and python-dotenv.
python -m pip install --upgrade pip
python -m pip install flask python-dotenv
Now, open this folder in your favorite text editor and create a new file app.py.
Let's get started with this simple hello-world app.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def hello_world():
return jsonify({
'greeting': 'Hello World!'
})
if __name__ == '__main__':
app.run(host='0.0.0.0', debug = True)
Taking a look at this code, it is rather simple, we create a new flask_app variable using the imported flask module. We then use this as a decorator to create a new route '/' (the default route) and write a function under it. We then return a greeting in JSON using the jsonify module.
Before running the app, create a file .flaskenv and add the following -
FLASK_ENV=development
This makes sure that the app runs with debug mode on so that the app restarts the server on every code change and you get a debugger on the browser in case of any errors.
You can run flask run on your command line to start this app.

As you can see, the debug mode is on and our dev server is running on port 5000. You can look this up in your browser.

There you have it, you have your starter API set-up using Flask.
You can go ahead and add more routes to the application, for demonstration I'll just go on and add my favorite games to display.
## games.py
games = [
{"id": 1, "title": "Cyberpunk 2077",},
{"id": 2, "title": "Horizon Zero Dawn",},
{"id": 3, "title": "Battlefield V",}
]
I created a list of dictionaries in a new file games.py and I've imported it in app.py.
Now, app.py looks like this -
from flask import Flask, jsonify
from games import games
app = Flask(__name__)
@app.route('/')
def hello_world():
return jsonify({
'greeting': 'Hello World!'
})
@app.route('/games')
def all_games():
return jsonify({
'games': games,
})
@app.route('/games/<game_id>')
def find_game_by_id(game_id):
for game in games:
if game["id"] == int(game_id):
return jsonify({
"game": game,
})
I've added 2 functions for routes /games and /games/<game_id>.
/games simply returns the entire games list whereas the latter returns the dictionary with the key for 'id' mentioned in the query parameter. This parameter can be fetched in the route by using triangle-braces < and > or whatever you call them.
Here are responses for these specific routes -
/games

/games/1

There you have it, folks, we just wrote our first API using Python Flask. This is just the beginning. We can connect this app to a database for backend operations, but that is probably for a different thread.
Thanks for reading, have a great day :)