Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Flask Templates
  • Jinja2
  • Flask-REST API
  • Python SQLAlchemy
  • Flask Bcrypt
  • Flask Cookies
  • Json
  • Postman
  • Django
  • Flask Projects
  • Flask Interview Questions
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJs
  • Vue.Js
Open In App
Next Article:
How to Connect Django with Reactjs ?
Next article icon

How to Connect ReactJS with flask API ?

Last Updated : 10 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Connecting React with Flask API allows us to create a full-stack web application with React handling the user interface at frontend and Flask serving the data in backend. Here React makes the HTTP request to interact with the flask API to perform operations with the database.

Approach

To connect React JS with Flask API we will be using the data fetching methods and libraries like fetch and axios. Build the backend API using the flask and make HTTP requests from React frontend using JavaScript fetch method for efficient API communication.

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

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: SetUp the 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.

Example: This example craete a backend server that provides json data when http request is made at /data route.

Python
# 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: Create React Application

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 Data From 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.

Example: This example uses the react hooks to fetche data from a Flask API and displays the name, age, date, and programming language on the webpage.

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.


Next Article
How to Connect Django with Reactjs ?
author
shiv_ka_ansh
Improve
Article Tags :
  • Python
  • Web Technologies
  • ReactJS
  • Geeks Premier League
  • Python Flask
  • React-Questions
Practice Tags :
  • python

Similar Reads

  • How to Connect Django with Reactjs ?
    Connecting Django with React is a common approach for building full-stack applications. Django is used to manage the backend, database, APIs and React handles the User Interface on frontend. Prerequisites:A development machine with any OS (Linux/Windows/Mac).Python 3 installed.Node.js installed (ver
    9 min read
  • How To Connect Node with React?
    To connect Node with React, we use React for the frontend (what users see) and Node.js for the backend (where the server logic lives). The frontend sends requests to the backend, and the backend responds with data or actions. There are many ways to connect React with Node.js, like using Axios or Fet
    4 min read
  • How To Connect MongoDB with ReactJS?
    MongoDB is a popular NoSQL database known for its scalability, flexibility, and high performance. When building modern web applications with ReactJS, it’s common to connect your frontend with a backend server that interacts with a database like MongoDB. PrerequisiteReact JSNode JSMongo DBApproach to
    5 min read
  • How to connect ReactJS with MetaMask ?
    To Connect React JS with MetaMask is important while making Web 3 applications, It will be done with Meta mask wallet which is the most used browser tool for sending and receiving signed transactions . MetaMask is a crypto wallet and a gateway to blockchain DAPP. It is used to connect our app to web
    3 min read
  • How To Create a Website in ReactJS?
    ReactJS is one of the most popular JavaScript libraries for building user interfaces. It allows you to create dynamic, reusable UI components and efficiently manage state and events. In this article, we'll walk through the steps to create a basic website using ReactJS. PrerequisitesNPM & Node.js
    5 min read
  • How to Change Port in Flask app
    In this article, we will learn to change the port of a Flask application. The default port for the Flask application is 5000. So we can access our application at the below URL. http://127.0.0.1:5000/ We may want to change the port may be because the default port is already occupied. To do that we ju
    1 min read
  • How to Create a Flask API with MariaDB on AWS EC2
    In this article, We are going to create an ec2 instance, install a MySQL database using MariaDB on the ec2 instance, and create an API of Login using the flask python framework. Flask is a micro web framework written in Python. MariaDB is one of the most popular open-source relational database manag
    6 min read
  • How to Convert CSV to JSON in ReactJS ?
    Dealing with data in various formats is a common task in web development. CSV (Comma Separated Values) and JSON (JavaScript Object Notation) are two widely used formats for storing and transmitting data. Converting CSV to JSON is often required when working with data in ReactJS applications. Approac
    4 min read
  • How to Connect ReactJS as a Front-end with PHP as a Back-end ?
    Connecting the front end of React with the PHP backend is a classic approach to building a web application with the front end for the user interface and the back end or server side for handling databases, programming logic, and other operations. In this article, we’ll discuss the steps required to c
    4 min read
  • How to authenticate firebase with GitHub in ReactJS ?
    The following approach covers how to authenticate firebase with GitHub in react. We have used the firebase module to achieve so. Creating React Application And Installing Module: Step 1: Create a React app using the following command: npx create-react-app gfgappStep 2: After creating your project fo
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences