Thursday, December 26, 2024
Google search engine
HomeLanguagesHow to connect ReactJS with flask API ?

How to connect ReactJS with flask API ?

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 working, which makes it beginner-friendly and many people choose this framework. Flask is generally used for building a REST API. To know more about how you can build REST API in flask please refer to this article

In this article, we will learn how one can connect flask API with Reactjs to show the data on the web page.

Setting up the project: Make sure to make 2 separate folders for clean understanding, one for flask backend and one for 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.

server.py

Python3




# 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:

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.

App.js

Javascript




// 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:

RELATED ARTICLES

Most Popular

Recent Comments