In this tutorial, we will develop a simple CRUD (Create, Read, Update, Delete) application using Flask as the backend and React as the frontend. This application will allow us to manage a list of items, such as tasks or notes. The tutorial will be broken down into manageable steps, guiding you through the entire process.
Prerequisites
Before we begin, ensure you have the following installed:
- Python 3.x
- Node.js and npm
- Basic knowledge of Python and JavaScript
- Familiarity with Flask and React (recommended, but not required)
Step 1: Set Up the Flask Backend
1.1. Create a New Directory
First, create a new directory for your project:
mkdir flask-react-crud
cd flask-react-crud
1.2. Set Up a Virtual Environment
Create a virtual environment for the Flask app:
python -m venv venv
source venv/bin/activate # For macOS/Linux
venv\Scripts\activate # For Windows
1.3. Install Flask and Flask-Cors
Install Flask and Flask-CORS to handle cross-origin requests:
pip install Flask Flask-Cors
1.4. Create Project Structure
Create the following files and directories:
mkdir backend
cd backend
touch app.py
1.5. Implement Flask API
Edit app.py
to implement a simple Flask application:
from flask import Flask, jsonify, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
# In-memory storage for items
items = []
@app.route('/items', methods=['GET'])
def get_items():
return jsonify(items), 200
@app.route('/items', methods=['POST'])
def create_item():
item = request.get_json()
items.append(item)
return jsonify(item), 201
@app.route('/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
item = request.get_json()
if 0 <= item_id < len(items):
items[item_id] = item
return jsonify(item), 200
return jsonify({'error': 'Item not found!'}), 404
@app.route('/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
if 0 <= item_id < len(items):
items.pop(item_id)
return jsonify({'result': 'Item deleted!'}), 200
return jsonify({'error': 'Item not found!'}), 404
if __name__ == '__main__':
app.run(debug=True)
1.6. Test the Flask API
Run the Flask application:
python app.py
You can test your API using a tool like Postman or curl. The API endpoints are as follows:
GET /items
– Retrieve all itemsPOST /items
– Create a new itemPUT /items/<id>
– Update an existing itemDELETE /items/<id>
– Delete an item
Step 2: Set Up the React Frontend
2.1. Create React App
In a new terminal window, create a new React application in the root directory:
npx create-react-app frontend
cd frontend
2.2. Install Axios
Install Axios for making HTTP requests from the frontend:
npm install axios
2.3. Project Structure
Delete unnecessary files in the src
folder to keep the project clean. Only keep App.js
, index.js
, and App.css
. Your structure should look like this:
frontend/
└── src/
├── App.js
└── index.js
2.4. Implement the React App
Now, let’s edit App.js
to implement the CRUD operations:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [items, setItems] = useState([]);
const [newItem, setNewItem] = useState('');
const [editIndex, setEditIndex] = useState(null);
const [editValue, setEditValue] = useState('');
const fetchItems = async () => {
const response = await axios.get('http://localhost:5000/items');
setItems(response.data);
};
useEffect(() => {
fetchItems();
}, []);
const handleAddItem = async () => {
const response = await axios.post('http://localhost:5000/items', { name: newItem });
setItems([...items, response.data]);
setNewItem('');
};
const handleEditItem = async (index) => {
const response = await axios.put(`http://localhost:5000/items/${index}`, { name: editValue });
const updatedItems = [...items];
updatedItems[index] = response.data;
setItems(updatedItems);
setEditIndex(null);
setEditValue('');
};
const handleDeleteItem = async (index) => {
await axios.delete(`http://localhost:5000/items/${index}`);
const updatedItems = items.filter((_, i) => i !== index);
setItems(updatedItems);
};
return (
<div className="App">
<h1>CRUD Application</h1>
<input
value={newItem}
onChange={(e) => setNewItem(e.target.value)}
placeholder="Add new item"
/>
<button onClick={handleAddItem}>Add</button>
<ul>
{items.map((item, index) => (
<li key={index}>
{editIndex === index ? (
<>
<input
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
/>
<button onClick={() => handleEditItem(index)}>Update</button>
</>
) : (
<>
{item.name}
<button onClick={() => { setEditIndex(index); setEditValue(item.name); }}>Edit</button>
<button onClick={() => handleDeleteItem(index)}>Delete</button>
</>
)}
</li>
))}
</ul>
</div>
);
}
export default App;
2.5. Update index.js
Ensure that index.js
looks like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
2.6. Start the React App
Run the React application:
npm start
The React app will run on http://localhost:3000
. You can now interact with your Flask API from the React interface.
Step 3: Testing Your Application
Navigate to http://localhost:3000
in your web browser. You should see the title “CRUD Application” with an input field to add new items. The list displays items fetched from the Flask backend. You can add, edit, and delete items using the respective buttons.
3.1. Testing Create Functionality
Type a new item into the text field and click “Add.” The item should appear in the list.
3.2. Testing Read Functionality
Whenever you open the app, existing tasks from the backend will be displayed.
3.3. Testing Update Functionality
Click “Edit” next to an item. Change the text in the input field and click “Update.” The list should reflect the changes.
3.4. Testing Delete Functionality
Click “Delete” next to an item to remove it from the list permanently. The change should be reflected in real-time.
Step 4: Additional Enhancements (Optional)
You can enhance your application by adding styles with CSS. Consider using libraries like Bootstrap or Material-UI to improve the user interface. You might also want to implement better error handling and input validation.
4.1. Adding CSS Styles
Edit the App.css
file to add some basic styles:
.App {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
ul {
list-style: none;
padding: 0;
}
li {
display: flex;
justify-content: space-between;
align-items: center;
margin: 10px 0;
}
button {
margin-left: 10px;
}
Conclusion
In this tutorial, you learned how to build a simple CRUD application using Flask and React. We set up a basic API with Flask and created a frontend interface with React that communicates with our Flask backend. This foundation allows for more complex applications to be built and can be a stepping stone to develop your skills in web development.
Feel free to experiment with the code, add more features, and explore more about Flask and React. Happy coding!
Leave a Reply