react-python

How to Build a Full-Stack React With Python Flask App – Series

By Rasyue | On April 15, 2020

Now days, you probably have heard MEAN or MERN numerous times already. If you are a beginner, MEAN stands for (MongoDB, Express, Angular, and Node. For MERN, it stands for MongoDB, Express, React and Node.

In simpler terms, it’s a stack that a lot of people have been using to build an app. You either use React or Angular for the front-end and ExpressJs for the backend. MongoDB is obviously the database that you will be using, but you can always use MySQL or Postgres or any database that you like depending on the requirement and needs.

However, to make things more interesting we will build an app using React and Flask(Python). So, let’s get started.

First of all, make sure that you already have the latest Python install on your machine. After you have it install. Open up your command line and run the following command to create a React App. Make sure that you are in the directory that you want to create the project folder.

npx create-react-app react-flask
cd react-flask
npm start

The above command will start your React App at port 3000. It may ask to run on another port if you already have something running on port 3000. But no problem.

react-app-welcome-page

Congratulations, you have succesfully run your first React App, well that is if you are a beginner. Now, stop the App and then run the below command, we are going to create the Flask App now inside the same directory as the React App. Make sure you are still in the same directory in your command line.

C:/react-flask - directory // this is not a command
//command starts here
mkdir api
cd api
python -m venv venv
venv\Scripts\activate
pip install flask python-dotenv flask-restful flask-cors

Now, to explain the command line above, essentially what you are doing is creating a folder called api in the react-flask directory. And then you are installing the venv for python which is the virtual environment. In python, you can use the venv to create a virtual environment.

If you are asking why are we using virtual environment, well think of this, when you use python and you install a lot of python packages, the packages are only install to your machine, if you move the script/api folder somewhere else like a webserver, AWS ec2 and then you have to make sure you have all the packages installed or your script would not be able to run.

By using venv, you are installing the packages in the venv and even if you move the script or folder somewhere else, you just have to start the venv and all the packages will still be available.

Now that you have install the venv, you can start it with venv\Scripts\activate . Then you run the pip-install to install your dependencies/packages that you would like to use. In this case we are using flask. Now, create a new file in your api folder and let’s name it as api.py

Open up your api.py. Copy and paste the following code inside it.

from flask import Flask, jsonify
from flask_restful import Resource, Api
from json import *
from flask_cors import CORS, cross_origin


app = Flask(__name__)

@app.route('/')
@cross_origin()
def hello_world():
    jsonResp = {'hello': 'world'}
    return jsonify(jsonResp)
  

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

    

Now go back to your command line and run the following. Make sure you are in the correct directory which is the api directory (api folder)

python api.py

This will start the flask server on port 5000. If you go to localhost:5000, you should see a JSON data with Hello World.

flask-hello-world-port-5000

Now you have it, you have successfully created both React App and the Flask App. Now, if you notice, we have to run two different command line to run both the React App and Flask App. Meaning that you have to open two commands, one each to run one app

python api.py
npm start

Now there is a way to modify your React App package.json so it will run both React App and Flask App simultaneously but we would not be doing it in this tutorial. I prefer to run the apps separately also since for production, I would suggest that you deploy these two apps in two separate places.

Now that everything is in place, let’s try to make an API call to the Flask app from the React App. To do so, run the below command line so we can start to create pages in React.

npm install --save react-router-dom

Now, open your App.js file, copy and paste the following code. We are going to build just a little bit of things to get this started. I would not too much on the styling.

import React, { Component } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import Error from './components/Error';
import Navigation from './components/Navigation';
 
class App extends Component {
  render() {
    return (      
       <BrowserRouter>
        <div>
          <Navigation />
            <Switch>
            <Route path="/" component={Home} exact/>            
            <Route component={Error}/>
           </Switch>
        </div> 
      </BrowserRouter>
    );
  }
}
 
export default App;

Make a new folder and name it components. Inside the folder create 3 new files namely Error.js, Home.js, Navigation.js. Copy the code and paste it inside the corresponding file.

// for navigation.js

import React from 'react';
 
import { NavLink } from 'react-router-dom';
 
const Navigation = () => {
    return (
       <div>
          <NavLink to="/">Home</NavLink>       
       </div>
    );
}
 
export default Navigation;
// for error.js
import React from 'react';
 
const Error = () => {
    return (
       <div>
          <p>Error: Page does not exist!</p>
       </div>
    );
}
 
export default Error;
import React, { Component } from 'react';


export default class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            output : []
        };
      }
    
    componentDidMount() {
        fetch('http://localhost:5000/').then(res => res.json()).then(data => {
           
            JSON.stringify(data)
            console.log(data)
            this.setState({
               
                output: data
              });
            
          });
      }
    
    render() {
       
        return (
        <div>
             <p>{this.state.output.hello}</p>
        </div>
        );
      }
}

Now, to explain these, the Error.js and Navigation.js are 2 React components that we defined using the function approach or Function-based component. However, for Home.js we are using Class approach or Class-based component.

Now, in the Home.js, in the lifecyle of the component, componentDidMount(). You can see that we are fetching the data from our Flask app. If you refresh your React app, start it if you have not done so, you will see the page returns ‘world‘. Which is the data that you fetched from the Flask app.

react-app

There you have it, you now have a working back-end Flask that you can create more API services to support your front-end React App. The purpose of this tutorial is to show that you can build a website or app using a full-stack of React and Python and looks like we have successfully done so.

In the next tutorial, we will look into how we can connect our Flask App with our database.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*