This blogpost will be the first part of a blog series where we will make a very simple web application using React and Flask.
In this part, we will build a Flask API to fetch excuses from a list of excuses on the backend. We have the option to get a random excuse or an excuse for a specific occasion like being late for work or skipping an occasion.
Set Up Project
- Create a new folder for the project & create 2 sub folders
frontend/
andbackend/
mkdir generic-excuse
cd generic-excuse
mkdir frontend backend
- Go in the backend folder, create a Python Environment and install Flask
cd backend
python -m venv .venv
source .venv/bin/activate
- Install Flask
pip install flask
The Flask Server
- Create a
server.py
file and paste the code below in it. This is a basic Flask boilerplate that will allow you to call the index route('/')
and it will returnHello, Fullstack Almanac!
from flask import Flask
# Create a Flask Instance
app = Flask(__name__)
# Add a route
@app.route('/')
def index():
return "Hello, Fullstack Almanac!"
# If you run this file, start the Flask instance
if __name__ == '__main__':
app.run()
Retrieving An Excuse
- In order to retrieve excuses, we first need to make some! Below I created an array with a few examples and a category that depicts the occasion an excuse can be used.
excuses = [
{
'category': 'late',
'excuse': 'Sorry I\'m late, I was stuck in traffic'
},
{
'category': 'late',
'excuse': 'I swear it wasn\'t my fault my neighbour forced me to stay in bed.'
},
{
'category': 'skip_event',
'excuse': 'I can\'t come, I have to go fishing in the morning.'
},
{
'category': 'homework',
'excuse': 'My dog ate my homework.'
},
{
'category': 'homework',
'excuse': 'I didn\'t do my homework because this isn\'t the homework you\'re looking for'
}
]
- Next up we’ll create a flask route that will select a random excuse from the list and return it to the user.
@app.route('/api/v1/excuse', methods=['GET'])
def get_excuse():
return random.choice(excuses)
- If we run our code again and go to
localhost:5000/api/v1/excuse
in the browser or call the URL with curl it will return a random excuse.
Filter By Category
- Next up we want to be able to filter by category. You might want to make a chatbot that gives you an excuse if you are late for work again.
- First, we want to be able to use route parameters. This will allow us to call
/api/v1/excuse/homework
or/api/v1/excuse/late
and use homework and late as a parameter for our function. We’ll default the parameter to random if none is given.
@app.route('/api/v1/excuse', methods=['GET'])
@app.route('/api/v1/excuse/<category>', methods=['GET'])
def get_excuse(category='random'):
# ... Your logic will go here ...
- When the category is random we just want to select a random excuse like before. But if the category is something else we’ll first create a smaller list of all the excuses in the same category
@app.route('/api/v1/excuse', methods=['GET'])
@app.route('/api/v1/excuse/<category>', methods=['GET'])
def get_excuse(category='random'):
if category == 'random':
return jsonify(random.choice(excuses))
else:
return jsonify(random.choice([excuse for excuse in excuses if excuse['category'] == category]))
- The line
random.choice([excuse for excuse in excuses if excuse['category'] == category])
might be a bit confusing. It adds an excuse to an array for every excuse in excuses that has the same category. You could write it out more like this:
filtered_excuses = []
for excuse in excuses:
if (excuse['category'] == category):
filtered_excuses.append(excuse)
return jsonify(random.choice(filtered_excuses))
- Now if you run the code you will be able to get a random excuse for every category.
This is it for the API code, we are now able to fetch excuses from our API based on the occasion. In the next blog post, we will build a React Frontend to consume this API so that users can interact with it.
You can find the code below or on Github.
import random
from flask import Flask, jsonify
app = Flask(__name__)
excuses = [
{
'category': 'late',
'excuse': 'Sorry I\'m late, I was stuck in traffic'
},
{
'category': 'late',
'excuse': 'I swear it wasn\'t my fault my neighbour forced me to stay in bed.'
},
{
'category': 'skip_event',
'excuse': 'I can\'t come, I have to go fishing in the morning.'
},
{
'category': 'homework',
'excuse': 'My dog ate my homework.'
},
{
'category': 'homework',
'excuse': 'I didn\'t do my homework because this isn\'t the homework you\'re looking for'
}
]
@app.route('/api/v1/excuse', methods=['GET'])
@app.route('/api/v1/excuse/<category>', methods=['GET'])
def get_excuse(category='random'):
if category == 'random':
return jsonify(random.choice(excuses))
else:
return jsonify(random.choice([excuse for excuse in excuses if excuse['category'] == category]))
if __name__ == '__main__':
app.run()