18
loading...
This website collects cookies to deliver better user experience
Flask
framework and the inbuilt jinja template is cool but hooking your backend to a react frontend(which I believe we all love 😉) is much more interesting. In this tutorial, you are going to be taken through the easy steps you need to take to connect your Flask
backend to a React
frontend. ReactJs
. You will be making use of the useState
hook and also fetching data from API using axios
.mkdir project
cd project
npx create-react-app flask_react
flask_react
directorycd flask_react
npm start
http://localhost:3000
mkdir backend
cd backend
Building a web application with Flask
series you should know the next thing that needs to be created. Yes, a virtual environment. Did you happen to get that right? 😀For mac/unix users: python3 -m venv env
For windows users: py -m venv env
For mac/unix users: source env/bin/activate
For windows users: .\env\Scripts\activate
pip install flask
pip install python-dotenv
.flaskenv
file in the backend
directory created above.touch .flaskenv
.
is very important. If you name your file just flaskenv
, any environment variable you'll put in it won't be read..flaskenv
file:FLASK_APP=base.py
FLASK_ENV=development
export FLASK_APP=base.py
and export FLASK_ENV=development
whenever you restart your terminal window.base.py
in the backend
directory where the .flaskenv
directory is also located.touch base.py
from flask import Flask
api = Flask(__name__)
@api.route('/profile')
def my_profile():
response_body = {
"name": "Nagato",
"about" :"Hello! I'm a full stack developer that loves python and javascript"
}
return response_body
response_body
dictionary.GET
http method is not specified here. This is because, by default, view
functions in flask accept GET requests only.response_body
dictionary being returned at the end of the function is not being passed as an argument to the popular jsonify
function like this jsonify(response_body)
. This is because view functions in Flask can return a dictionary, which Flask then turns to JSON format.flask run
http://127.0.0.1:5000/profile
.You should see the dictionary response_body
rendered in JSON format.env
and __pycache__
folders to the gitignore
file in the base directory.backend/env
backend/__pycache__
cd ..
axios
or fetch
to make HTTP requests. However, in this article, the axios
library will be used to make requests to the API endpoints you built earlier on.npm install axios
"name": "flask_react",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:5000", //newline
http://localhost:5000/profile
you can simply make use of /profile
.http://127.0.0.1:5000
but http://localhost:5000
was used above as the value to the proxy key. Don't be confused, they are both the same. You can read more on that herepackage.json
file yet. There is something cool you can add as well. You know that whenever your react server is started and you make any change in a file and you save it, the server restarts so that the new change can reflect right?. You can also add that feature to your flask backend application. This is another advantage of connecting react to flask 😎.scripts
section add another key and value. "start-backend": "cd backend && env/bin/flask run --no-debugger",
so it ends up looking like 👇"scripts": {
"start": "react-scripts start",
"start-backend": "cd backend && env/bin/flask run --no-debugger", //new line
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
npm run start-backend
. This executes the command passed as its value in the package.json file. It navigates into the env
directory in your backend
directory and executes the flask run
command.--no-debugger
option is also passed here to disable the browser-based debugger as the Flask backend only serves as a server that holds the API endpoint.import { useState } from 'react'
import axios from "axios";
import logo from './logo.svg';
import './App.css';
function App() {
// new line start
const [profileData, setProfileData] = useState(null)
function getData() {
axios({
method: "GET",
url:"/profile",
})
.then((response) => {
const res =response.data
setProfileData(({
profile_name: res.name,
about_me: res.about}))
}).catch((error) => {
if (error.response) {
console.log(error.response)
console.log(error.response.status)
console.log(error.response.headers)
}
})}
//end of new line
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
{/* new line start*/}
<p>To get your profile details: </p><button onClick={getData}>Click me</button>
{profileData && <div>
<p>Profile name: {profileData.profile_name}</p>
<p>About me: {profileData.about_me}</p>
</div>
}
{/* end of new line */}
</header>
</div>
);
}
export default App;
useState
hook and axios module are both imported.App
the useState hook is used to control the state of the profileData
variable.getData
function handles the API calls. It contains the axios
module which is used to send a GET
request to the API endpoint(\profile) on the backend which responds with the jsonified
format of the dictionary declared in the view function. setProfileData
function updates the state of profileData
by assigning the data in the json response to profile_name
and about_me
.getData
function is only called when the click me
button is pressed.&&
is used as a conditional operator, to avoid getting an error. profileData
is going to be assigned an initial null
state when the application first loads so if you try to access profileData.profile_name
or profileData.about_me
you get an error message.TypeError: Cannot read properties of null (reading 'profile_name')
&&
conditional operator, so that the application only knows of the existence of the profileData.profile_name
and profileData.about_me
codes when the value of profileData
has changed from null
to containing the response data
from the API call.npm run start-backend
npm start
Django
lover, you would definitely love to connect it to React
as well. You can check out my article on How to connect Django to ReactJs to learn how to go about that. Ciao 👋