Open In App

How to connect ReactJS with flask API ?

Last Updated : 24 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Reactjs is one of the best frontend libraries for building frontend single-page applications. It is been developed and maintained by Facebook with a large community. 

Flask is a backend micro-framework written in Python for the rapid development process. It is famous for its simplicity and independence. It does not need any external library for work, which makes it beginner-friendly, and many people choose this framework. Flask is generally used for building a REST API.

Let’s see a Step-by-step guide to connect Flask API with React JS to show the data on the web page.

Steps to connect React with Flask API and set up the Project :

Note : Make sure to make 2 separate folders for clean understanding, one for the Flask backend and one for the React frontend. The project structure should look like

Step 1: Setting up a flask server 

Make a folder named backend and file server.js with the following command:

mkdir backend
cd backend
touch server.py

Build a basic flask server. Write down the following code in server.py file.

Python3




# Filename - server.py
 
# Import flask and datetime module for showing date and time
from flask import Flask
import datetime
 
x = datetime.datetime.now()
 
# Initializing flask app
app = Flask(__name__)
 
 
# Route for seeing a data
@app.route('/data')
def get_time():
 
    # Returning an api for showing in  reactjs
    return {
        'Name':"geek",
        "Age":"22",
        "Date":x,
        "programming":"python"
        }
 
     
# Running app
if __name__ == '__main__':
    app.run(debug=True)


Step to run the application: Use the following command to run the server:

python server.py

Output: This output will be visible on the http://localhost:5000/ on the browser window..

Step 2: Setting up the Reactjs project

Make a react project using the following command:

yarn create react-project frontend // OR
npx create-react-app frontend

Move After creating the app, move into the app using the following command:

cd frontend

After that open package.json and add the proxy.

"proxy":"http://localhost:5000/"

Now, we provide the proxy in react package.json file because we need to access the flask URL in order to get the API from our react app. In general what proxy does is, when we request into the javascript web server which serves the react frontend will automatically be redirected to the proxy key. In this case, it will be our flask server. 

Step 3: Fetching the API

For fetching the API useState and useEffect hooks are used in react app. 

  • useState: It is used for setting a data from the API and providing into the jsx for showing the data.
  • useEffect: It is used for rendering a fetch method on a single reload.

Javascript




// Filename - App.js
 
// Importing modules
import React, { useState, useEffect } from "react";
import "./App.css";
 
function App() {
    // usestate for setting a javascript
    // object for storing and using data
    const [data, setdata] = useState({
        name: "",
        age: 0,
        date: "",
        programming: "",
    });
 
    // Using useEffect for single rendering
    useEffect(() => {
        // Using fetch to fetch the api from
        // flask server it will be redirected to proxy
        fetch("/data").then((res) =>
            res.json().then((data) => {
                // Setting a data from api
                setdata({
                    name: data.Name,
                    age: data.Age,
                    date: data.Date,
                    programming: data.programming,
                });
            })
        );
    }, []);
 
    return (
        <div className="App">
            <header className="App-header">
                <h1>React and flask</h1>
                {/* Calling a data from setdata for showing */}
                <p>{data.name}</p>
                <p>{data.age}</p>
                <p>{data.date}</p>
                <p>{data.programming}</p>
 
            </header>
        </div>
    );
}
 
export default App;


Step to run the application: Use the following command to run the server:

npm start 
// OR
yarn start

Output: This output will be visible on the http://localhost:3000/ on the browser window.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads