How to connect ReactJS with Flask API?

Building modern web applications requires connecting frontend and backend technologies effectively. ReactJS and Flask are popular choices for frontend and backend development respectively.

This article explores how to connect ReactJS with Flask API to create robust web applications. We'll cover setting up a Flask API, enabling CORS, making API requests from ReactJS, displaying data, and handling errors.

Creating a Flask API

First, create a Python script that defines API routes using Flask's @app.route decorator ?

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/data')
def get_data():
    response = {'message': 'Hello from Flask!', 'status': 'success'}
    return jsonify(response)

if __name__ == '__main__':
    app.run(debug=True, port=5000)

This creates a Flask API with a route /api/data that returns JSON data.

Enabling CORS

Cross?Origin Resource Sharing (CORS) is a security feature that prevents web pages from making requests to different domains. To allow ReactJS to communicate with your Flask API, enable CORS ?

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes

@app.route('/api/data')
def get_data():
    response = {'message': 'Hello from Flask!', 'status': 'success'}
    return jsonify(response)

if __name__ == '__main__':
    app.run(debug=True, port=5000)

Install the flask?cors package first: pip install flask-cors

Making API Requests from ReactJS

Use JavaScript's fetch() function to make HTTP requests to your Flask API ?

fetch('http://localhost:5000/api/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

This sends a GET request to the Flask API and logs the response data.

Displaying API Data in ReactJS

Use React hooks to fetch and display data from your Flask API ?

import React, { useState, useEffect } from 'react';

function App() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('http://localhost:5000/api/data')
      .then(response => response.json())
      .then(result => {
        setData(result);
        setLoading(false);
      });
  }, []);

  if (loading) return <div>Loading...</div>;

  return (
    <div>
      <h1>{data.message}</h1>
      <p>Status: {data.status}</p>
    </div>
  );
}

export default App;

The useState hook manages component state, while useEffect handles the API call when the component mounts.

Handling API Errors

Implement proper error handling to manage failed API requests ?

import React, { useState, useEffect } from 'react';

function App() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('http://localhost:5000/api/data')
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then(result => {
        setData(result);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div>
      <h1>{data.message}</h1>
      <p>Status: {data.status}</p>
    </div>
  );
}

export default App;

Complete Example

Here's a working Flask API with POST endpoint ?

from flask import Flask, jsonify, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/api/data', methods=['GET'])
def get_data():
    return jsonify({'message': 'Hello from Flask!', 'status': 'success'})

@app.route('/api/users', methods=['POST'])
def create_user():
    user_data = request.json
    return jsonify({'message': f"User {user_data['name']} created!", 'user': user_data})

if __name__ == '__main__':
    app.run(debug=True, port=5000)

Conclusion

Connecting ReactJS with Flask API enables building modern full?stack applications. Remember to enable CORS, handle errors properly, and use React hooks for state management. This combination provides a powerful foundation for scalable web applications.

Updated on: 2026-03-27T09:13:24+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements