The open blogging platform. Say no to algorithms and paywalls.

Create a Shopping Cart Application with Python, Flask, and React

Understand how to connect a simple Flask backend in Python with a frontend in React.

Image Source: https://hotpot.ai/art-generator

Introduction

In the world of web development, the fusion of backend and frontend tools is like bringing music to life. In this guide, weā€™ll embark on an adventure to create a shopping cart app using Python, Flask, and React. Get ready to uncover the behind-the-scenes magic of these technologies, as we build a shopping experience thatā€™s both engaging and practical.

The aim of this short project is to help you understand how to connect a simple Flask backend in python with frontend in React. This project is also aimed at understanding Test Sigmaā€™s automated testing, by making small updates to the UI to check how Test Sigmaā€™s reports and analysis dashboard help you understand the impact to your application. That will be done in a future article.

Agenda

  • Backend with Flask and Python
  • Frontend with React
  • Host these services locally and have them interact
  • Test this integration

Backend with Flask and Python

Create a folder called backend and add a file called app.py. Insert the following code into it:

from flask import Flask, jsonify, request  
from flask_cors import CORS  
  
app = Flask(__name__)  
CORS(app)  
# Sample shopping cart data  
cart_contents = {  
    'apple': 5,  
    'banana': 3,  
    'orange': 2,  
}  
def calculate_total_price():  
    prices = {  
        'apple': 0.5,  
        'banana': 0.3,  
        'orange': 0.25,  
    }  
    total_price = sum(prices[item] * quantity for item, quantity in cart_contents.items())  
    return round(total_price, 2)  
@app.route('/view_cart', methods=['GET'])  
def view_cart():  
    total_price = calculate_total_price()  
    return jsonify({  
        'cart_contents': cart_contents,  
        'total_price': total_price,  
    })  
@app.route('/add_to_cart', methods=['POST'])  
def add_to_cart():  
    data = request.get_json()  
    item = data['item']  
    quantity = data['quantity']  
    cart_contents[item] = cart_contents.get(item, 0) + quantity  
    total_price = calculate_total_price()  
    return jsonify({  
        'cart_contents': cart_contents,  
        'total_price': total_price,  
    })  
if __name__ == '__main__':  
    app.run(debug=True)

What does this code do?

This Python code is an example of a simple shopping cart API using the Flask web framework. It provides endpoints to view the contents of a shopping cart and add items to the cart. The code uses Flask-CORS to handle cross-origin resource sharing, allowing the API to be accessed from different domains.

Hereā€™s how the code works:

Import Necessary Modules

  • Flask: The main Flask class used to create the web application.
  • jsonify: A function from Flask that converts Python dictionaries to JSON responses.
  • request: An object from Flask that allows you to access incoming HTTP request data.
  • CORS: A class from Flask-CORS that enables Cross-Origin Resource Sharing.

Create the Flask App and Enable CORS

  • Create a Flask application instance named app.
  • Initialize CORS with CORS(app) to allow cross-origin requests.

Define Sample Cart Data

  • Create a dictionary cart_contents representing the items in the shopping cart and their quantities.

Define a Function to Calculate Total Price

  • Create a function calculate_total_price() that calculates the total price of items in the cart based on predefined prices.

Define API Endpoints

  • view_cart: A route that handles GET requests to view the contents of the shopping cart.
  • Calculate the total price using the calculate_total_price() function.
  • Return a JSON response with the cart contents and total price.
  • add_to_cart: A route that handles POST requests to add items to the shopping cart.
  • Extract item and quantity data from the JSON request.
  • Update the cart_contents dictionary with the new item and quantity.
  • Calculate the total price using the calculate_total_price() function.
  • Return a JSON response with the updated cart contents and total price.

Run the Application

  • Use the if __name__ == '__main__': block to ensure that the app is only run when executed directly, not when imported as a module.
  • Start the Flask development server using app.run(debug=True).

This code sets up a basic shopping cart API with Flask, allowing clients to view the cart contents and add items to the cart. The cart data is stored in memory, and the total price is calculated based on predefined item prices.


Build a frontend with React

Create a folder called frontend and cd into that directory. Next, create a React app. In a separate directory, create a new React app:

npx create-react-app shopping-cart-ui  
cd shopping-cart-ui

Install Axios: Axios is a popular library for making API requests. Install it in the React app:

npm install axios

Replace the src/App.js content with the following:

import React, { useState, useEffect } from "react";  
import axios from "axios";  
import "./App.css";  
 
function App() {  
 const [cartContents, setCartContents] = useState({});  
 const [totalPrice, setTotalPrice] = useState(0);  
 const [itemToAdd, setItemToAdd] = useState("");  
 const [quantityToAdd, setQuantityToAdd] = useState(0);  
 
 useEffect(() => {  
   fetchData();  
 }, []);  
 
 const fetchData = async () => {  
   try {  
     const response = await axios.get(  
       "https://pythoncodenemesis.pythonanywhere.com/view_cart"  
     );  
     setCartContents(response.data.cart_contents);  
     setTotalPrice(response.data.total_price);  
   } catch (error) {  
     console.error("Error fetching data:", error);  
   }  
 };  
 
 const handleAddToCart = async () => {  
   try {  
     await axios.post(  
       "https://pythoncodenemesis.pythonanywhere.com/add_to_cart",  
       {  
         item: itemToAdd,  
         quantity: quantityToAdd,  
       }  
     );  
     fetchData();  
   } catch (error) {  
     console.error("Error adding to cart:", error);  
   }  
 };  
 
 return (  
   <div className="app">  
     <h1>Shopping Cart</h1>  
     <div className="cart">  
       <h2>Cart Contents:</h2>  
       <ul>  
         {Object.entries(cartContents).map(([item, quantity]) => (  
           <li key={item}>{`${quantity} ${item}(s)`}</li>  
         ))}  
       </ul>  
       <h2>Total Price: ${totalPrice}</h2>  
     </div>  
     <div className="add-to-cart">  
       <h2>Add to Cart:</h2>  
       <input  
         type="text"  
         placeholder="Item"  
         value={itemToAdd}  
         onChange={(e) => setItemToAdd(e.target.value)}  
       />  
       <input  
         type="number"  
         placeholder="Quantity"  
         value={quantityToAdd}  
         onChange={(e) => setQuantityToAdd(parseInt(e.target.value))}  
       />  
       <button onClick={handleAddToCart}>Add to Cart</button>  
     </div>  
   </div>  
 );  
}  
 
export default App;

Code Explanation

This code is a React.js application that simulates a shopping cart interface. It uses React hooks, useState and useEffect, to manage the state of the shopping cart contents and to interact with a backend API to view and update the cart.

Letā€™s break down the code step by step:

  1. Import React, useState, useEffect, and the axios library (for making HTTP requests), and the styles from "App.css".
  2. Define the App component function. This is the main component that renders the shopping cart interface.
  3. Within the App component, initialize several state variables using the useState hook:
  • cartContents: An object that represents the items in the shopping cart and their quantities.
  • totalPrice: A number representing the total price of items in the cart.
  • itemToAdd: A string representing the name of the item to be added to the cart.
  • quantityToAdd: A number representing the quantity of the item to be added.
  1. Use the useEffect hook to fetch initial cart data from the backend API when the component mounts. The fetchData function is defined to make an asynchronous API request to retrieve the cart contents and total price. The fetched data is then used to update the state variables cartContents and totalPrice.

  2. Define the handleAddToCart function, which is called when the "Add to Cart" button is clicked. This function makes a POST request to the backend API to add an item to the cart. The itemToAdd and quantityToAdd values are sent in the request payload. After successfully adding the item to the cart, the fetchData function is called again to update the cart's data.

In the JSX code, the componentā€™s rendering logic is defined:

  • The shopping cart contents are displayed in an unordered list using the map function on Object.entries(cartContents).
  • The total price is displayed.
  • Below the cart contents, there is an ā€œAdd to Cartā€ section with input fields for the item and quantity, and a button to trigger the handleAddToCart function.
  1. Finally, the App component is exported as the default export of the module.

This code provides a basic example of a shopping cart interface using React.js. It demonstrates how to use hooks for state management (useState), fetching data from an API (useEffect), and updating the UI based on user interactions. The app interacts with a backend API to view and modify the cart's contents.

Add some basic styling to src/App.css:

/* app.css */  
body {  
  margin: 0;  
  padding: 0;  
  font-family: Arial, sans-serif;  
  background-color: #f0f0f0;  
}  
  
.app {  
  max-width: 800px;  
  margin: 0 auto;  
  padding: 20px;  
  background-color: #fff;  
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);  
}  
  
h1 {  
  text-align: center;  
  margin-bottom: 30px;  
  color: #333;  
}  
  
.cart {  
  border: 1px solid #ccc;  
  padding: 20px;  
}  
  
.cart h2 {  
  margin: 0;  
  margin-bottom: 10px;  
  color: #333;  
}  
  
.cart ul {  
  list-style: none;  
  padding: 0;  
  margin: 0;  
}  
  
.cart li {  
  margin-bottom: 5px;  
  color: #555;  
}  
  
.cart h2:last-child {  
  margin-top: 20px;  
}  
  
.add-to-cart {  
  margin-top: 30px;  
  border: 1px solid #ccc;  
  padding: 20px;  
}  
  
.add-to-cart h2 {  
  margin: 0;  
  margin-bottom: 10px;  
  color: #333;  
}  
  
.add-to-cart input {  
  display: block;  
  width: 100%;  
  padding: 10px;  
  margin-bottom: 10px;  
  border: 1px solid #ccc;  
  border-radius: 5px;  
}  
  
.add-to-cart button {  
  display: block;  
  width: 100%;  
  padding: 10px;  
  background-color: #007bff;  
  color: #fff;  
  border: none;  
  border-radius: 5px;  
  cursor: pointer;  
}  
  
.add-to-cart button:hover {  
  background-color: #0056b3;  
}

Before running the React Application, replace the URL https://pythoncodenemesis.pythonanywhere.com with http://localhost:5000/.

Start the React app:

npm start

The React app will be running at http://localhost:3000, and you can interact with the shopping cart UI, which communicates with the hosted Flask app on Heroku.

Make sure to install the required packages:

pip install Flask flask-cors  
npm install axios

With these changes, CORS is enabled for both the backend and frontend, allowing them to communicate with each other. The Flask app will run on http://localhost:5000, and the React app will run on http://localhost:3000.

Running the Backend and Frontend

Now, letā€™s simultaneously run the backend and frontend. This will ensure seamless interaction between Flask and React.

Setting Up the Backend

  • Open a terminal window and navigate to the ā€˜backendā€™ directory within your project.
  • Install the necessary Flask and Flask-CORS packages by executing: pip install Flask flask-cors.
  • Once the installation is complete, launch the Flask app with the command: python app.py.
  • Your Flask backend will now be up and running at http://localhost:5000.

Setting Up the Frontend

  • Open another terminal window and navigate to the ā€˜frontendā€™ directory of your project.
  • Install the required Axios package by running: npm install axios.
  • Start the React app using the command: npm start.
  • You can access the React frontend by visiting http://localhost:3000.

Witnessing the Seamless Blend

  • With both the Flask backend and React frontend operational, open your web browser and navigate to http://localhost:3000.
  • Add items, view the cartā€™s contents, and observe how the frontend and backend seamlessly communicate and respond.

All the code for this article is available here on Github:

GitHub - PythonCodeNemesis/Python_Test_Sigma_Demo

Conclusion

As we wrap up our exploration, the combination of Python, Flask, and React emerges as a dynamic trio that powers modern web apps. From Flaskā€™s backend prowess to Reactā€™s interactive frontend, weā€™ve revealed the inner workings of a functional shopping cart app. With this newfound knowledge, youā€™re all set to embark on your web development journey, armed with the skills to craft your own feature-packed and user-friendly applications.


Thatā€™s it for this article! Feel free to leave feedback or questions in the comments.

Enjoyed the article and found it helpful? If youā€™d like to show your appreciation and support my work, you can buy me a coffee! Your support goes a long way in helping me create more content like this. Thank you in advance! ā˜•ļø

PythonCodeNemesis writes Python Technical Articles and Tutorials on Medium




Continue Learning