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
-
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
2. Create requirements.txt
:
Save your dependencies to requirements.txt
:
pip freeze > requirements.txt
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
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
5 Run the Application (run.py
):
from app import app
if __name__ == '__main__':
app.run(debug=True)
Debugging and Testing
Run the Flask App:
python run.py
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"}'
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
-
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
Install Axios for API Requests:
npm install axios
Configure Environment Variables (frontend/.env
):
REACT_APP_API_BASE_URL=http://localhost:5000
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;
Start the React Application:
npm start
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:
Top comments (0)