React/ReactJS: Connecting to Python Flask API
Flask is a lightweight Python microframework, based on the WSGI library Werkzeug and the Jinja templating engine. Flask has become one of the most popular Python framework, only next to Django.
In this tutorial, we will try to connect to a simple Flask API from a React application, using JavaScript's window.fetch()
method.
Download the latest version of Python and install it.
Check the installed Python version.

Along with the installed Python, the pip package manager is included by default. You can check its latest version by typing the below command:

Next, we install the
pipenv
package, a Python virtual management tool. It adds/removes packages
from your Pipfile
and also generates the
Pipfile.lock
which produces deterministic
builds.
pip3 install --user pipenv
We see that during installation we are accompanied by a warning message:

To resolve this, we have to modify the
.zshrc
file. Go to the root directory and
open up the .zshrc
file.
nano .zshrc
Add the installed path in the warning message
"/Users/admin/Library/Python/3.12/bin" as "export
PATH=/Users/admin/Library/Python/3.12/bin:$PATH" in the
.zshrc
file and save it.
Now if you check just the .zshrc
file,
you will find the newly added PATH.
cat .zshrc

If you try to execute the
pipenv --version
command on the terminal
, it will show
pipenv, version 2024.0.2
This concludes the installation of Python and related tools necessary for development of our first API with Flask.
Create .venv
& Install Flask
To start our Flask project, create a new folder called
api
. Inside the
api
folder, create a new Python file
main.py
and a new folder
.venv
.

We will create a simple API with Flask, a lightweight WSGI micro web framework written in Python.

We first install Flask. Type in the below command.
pipenv install flask
Post installation, you will see two new files
Pipfile
and
Pipfile.lock
installed alongside
main.py
inside the
api
folder, which are similar to the
package.json
and
package-lock.json
files. And once you
expand the .venv
folder, you will see a bunch of subfolders and files.

We write a small program in our
main.py
which just returns a "Hello,
World!"
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, World!"

Activate the virtualenv by running the
pipenv shell
command.
In the next command, type in
env FLASK_APP=main.py flask run

Your Flask application runs on
http://127.0.0.1:5000
and if you type it
on the URL, it will load:

Let us retrieve some meaningful data. We append some more code so
that when we made a request to another path (say,
/users
) it will give a JSON response of
a couple of sample users.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, World!"
@app.route("/users")
def users():
users = [{'name': 'Joe', 'age': 29},
{'name': 'Brendan', 'age': 34}]
return jsonify({'users': users})
On requesting the page
http://127.0.0.1:5000/users
, the
following response will be given.

We write some code to consume this API in React. We use a simple
fetch()
method inside the
useEffect()
hook.
import { useEffect, useState } from "react";
function App() {
const [users, setUsers] = useState([])
useEffect(() => {
fetch('http://127.0.0.1:5000/users')
.then(response => response.json())
.then(data => setUsers(data.users))
.catch(error => console.error(error));
}, []);
return (
<div>
{users && users.map((itm,idx) => (
<div key={idx}>
{itm.name}, {itm.age}
</div>
))}
</div>
);
}
export default App;
On executing the code, we are bound to get few errors.

To fix all these errors, we install the package
flask-cors
pip3 install -U flask-cors
and add a couple of lines to the existing code.
from flask import Flask, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app=app, resources={r"/*": {"origins": "*"}})
@app.route("/")
def hello():
return "Hello, World!"
@app.route("/users")
def users():
users = [{'name': 'Joe', 'age': 29},
{'name': 'Brendan', 'age': 34}]
return jsonify({'users': users})
On re-executing the code, you will see that it runs without errors.
