DEV Community

Cover image for A Comprehensive Guide to Setting Up Flask Environment for Backend Development and Connecting It to a React Frontend
TD!
TD!

Posted on

3

A Comprehensive Guide to Setting Up Flask Environment for Backend Development and Connecting It to a React Frontend

It's Day #13 of #100daysofMiva coding challenge. Don't be surprised I jumped to backend, one of my project's MVP is due for submission tomorrow so I sat with it all through today. Initially I used firebase for backend but later changed it to flask. The process and experience is what I documented in this report so you can learn a thing or two also.

In this report, I'll delve into setting up a Flask environment for backend development and integrating it with a React frontend. I'll cover project directory structures, essential commands, and code snippets to illustrate key concepts. Whether you're a beginner or an expert, this guide aims to provide valuable insights into building a robust backend with Flask and connecting it to a modern frontend framework like React. Some of these I just learnt them today myself.

Setting Up Flask for Backend Development

Project Directory Structure

Organizing your project directory is crucial for maintainability. Here's a typical structure for a Flask backend:

my_flask_project/
│
├── app/
│   ├── __init__.py
│   ├── routes.py
│   ├── models.py
│   └── utils.py
│
├── migrations/
│
├── .env
├── config.py
├── requirements.txt
└── run.py
Enter fullscreen mode Exit fullscreen mode
  • app/__init__.py: Initializes the Flask application and sets up configuration.
  • app/routes.py: Defines the application's routes and views.
  • app/models.py: Contains data models and database interactions.
  • app/utils.py: Utility functions used across the application.
  • .env: Environment variables for sensitive data.
  • config.py: Configuration settings for Flask and database.
  • requirements.txt: Lists project dependencies.
  • run.py: Entry point to run the Flask application

Setting Up the Environment

1. Install Flask and Dependencies:

Use the following command to create a virtual environment and install Flask:

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install flask flask_sqlalchemy python-dotenv
Enter fullscreen mode Exit fullscreen mode

2. Create requirements.txt:

Save your dependencies to requirements.txt:

pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode

3. Configure the Flask Application (app/__init__.py):

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from dotenv import load_dotenv
import os

load_dotenv()

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL', 'sqlite:///site.db')
db = SQLAlchemy(app)

from app import routes
Enter fullscreen mode Exit fullscreen mode

4 Define Routes (app/routes.py):

from app import app, db
from flask import request, jsonify

@app.route('/api/clients', methods=['POST'])
def add_client():
    data = request.json
    # Implement your client addition logic here
    return jsonify({'message': 'Client added successfully!'}), 201
Enter fullscreen mode Exit fullscreen mode

5 Run the Application (run.py):

from app import app

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Debugging and Testing

Run the Flask App:

python run.py
Enter fullscreen mode Exit fullscreen mode

Test Endpoints:

Use tools like Postman or curl to test your API endpoints:

curl -X POST http://localhost:5000/api/clients -H "Content-Type: application/json" -d '{"name": "John Doe"}'
Enter fullscreen mode Exit fullscreen mode

Connecting Flask Backend to React Frontend

Project Directory Structure

For a React frontend connected to a Flask backend, your project directory might look like this:

my_project/
│
├── frontend/
│   ├── src/
│   ├── public/
│   ├── package.json
│   └── .env
│
├── backend/
│   ├── app/
│   ├── migrations/
│   ├── .env
│   ├── config.py
│   ├── requirements.txt
│   └── run.py
│
└── README.md
Enter fullscreen mode Exit fullscreen mode
  • frontend/src/: Contains React components and logic.
  • frontend/package.json: Lists React project dependencies.
  • frontend/.env: Environment variables for React, such as API base URL.
  • backend/: Contains Flask project files as described earlier.

Setting Up React

Create a React App:

Use Create React App to set up your frontend:

npx create-react-app frontend
cd frontend
Enter fullscreen mode Exit fullscreen mode

Install Axios for API Requests:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Configure Environment Variables (frontend/.env):

REACT_APP_API_BASE_URL=http://localhost:5000
Enter fullscreen mode Exit fullscreen mode

Create a Component to Handle API Requests (frontend/src/MyMeasurement.js):

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

const MyMeasurement = () => {
  const [client, setClient] = useState({ name: '' });

  const handleChange = (e) => {
    setClient({ ...client, [e.target.name]: e.target.value });
  };

  const handleSubmit = async () => {
    try {
      const response = await axios.post(`${process.env.REACT_APP_API_BASE_URL}/api/clients`, client);
      console.log(response.data);
    } catch (error) {
      console.error('Error adding client:', error);
    }
  };

  return (
    <div>
      <input type="text" name="name" value={client.name} onChange={handleChange} />
      <button onClick={handleSubmit}>Add Client</button>
    </div>
  );
};

export default MyMeasurement;
Enter fullscreen mode Exit fullscreen mode

Start the React Application:

npm start
Enter fullscreen mode Exit fullscreen mode

Debugging and Testing

  • Check Console Logs: Use browser developer tools to monitor network requests and debug issues.

  • Cross-Origin Resource Sharing (CORS): Ensure that your Flask backend is configured to allow requests from your React frontend. Install and configure Flask-CORS:

A screenshot of vs code showing running backend and frontend

Billboard image

Synthetic monitoring. Built for developers.

Join Vercel, Render, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay