Creating a sustainable fashion recommendation system involves fetching data from an API that provides detailed information about fashion products, including sustainability ratings, brand details, material composition, and images. Below is a comprehensive guide to building such a system using JavaScript, React for the frontend, and Node.js/Express for the backend.
Note: As of my knowledge cutoff in April 2023, there isn't a widely recognized public API dedicated exclusively to sustainable fashion. However, you can use Good On You, which offers sustainability ratings for brands, or use mock data to simulate the API responses. For this example, I will demonstrate using mock data.
Project Overview
- Backend: Node.js and Express to create an API that serves sustainable fashion data.
- Frontend: React to build the user interface, fetching data from the backend and displaying product recommendations.
- Data: Mock data representing products with sustainability ratings, brands, materials, and images.
Step 1: Setting Up the Backend
1. Initialize the Project
First, create a new directory for your project and initialize it with npm.
mkdir sustainable-fashion-recommendation
cd sustainable-fashion-recommendation
npm init -y
2. Install Dependencies
Install Express and CORS.
npm install express cors
3. Create Mock Data
Create a data folder and add a products.json file with sample product data.
data/products.json
[
{
"id": 1,
"name": "Organic Cotton T-Shirt",
"brand": "EcoWear",
"sustainabilityRating": 9,
"materials": ["Organic Cotton"],
"image": "https://via.placeholder.com/150",
"category": "Tops"
},
{
"id": 2,
"name": "Recycled Polyester Jacket",
"brand": "SustainStyle",
"sustainabilityRating": 8,
"materials": ["Recycled Polyester"],
"image": "https://via.placeholder.com/150",
"category": "Outerwear"
},
{
"id": 3,
"name": "Bamboo Fiber Socks",
"brand": "GreenFeet",
"sustainabilityRating": 10,
"materials": ["Bamboo Fiber"],
"image": "https://via.placeholder.com/150",
"category": "Accessories"
}
// Add more products as needed
]
4. Create the Express Server
Create a server.js file in the root directory.
server.js
const express = require('express');
const cors = require('cors');
const app = express();
const port = 5000;
const products = require('./data/products.json');
app.use(cors());
/**
* GET /api/products
* Query Parameters:
* - category: filter by category
* - minRating: filter by minimum sustainability rating
* - material: filter by material composition
* - brand: filter by brand name
*/
app.get('/api/products', (req, res) => {
let filteredProducts = products;
const { category, minRating, material, brand } = req.query;
if (category) {
filteredProducts = filteredProducts.filter(
(product) => product.category.toLowerCase() === category.toLowerCase()
);
}
if (minRating) {
filteredProducts = filteredProducts.filter(
(product) => product.sustainabilityRating >= parseInt(minRating)
);
}
if (material) {
filteredProducts = filteredProducts.filter((product) =>
product.materials.map((m) => m.toLowerCase()).includes(material.toLowerCase())
);
}
if (brand) {
filteredProducts = filteredProducts.filter(
(product) => product.brand.toLowerCase() === brand.toLowerCase()
);
}
res.json(filteredProducts);
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
5. Run the Server
Add a start script to your package.json.
"scripts": {
"start": "node server.js"
}
Start the server:
npm start
Your backend API is now running at http://localhost:5000/api/products.
Step 2: Setting Up the Frontend
1. Initialize the React App
In a separate terminal window/tab, create a React application using Create React App.
npx create-react-app frontend
cd frontend
2. Install Axios
We'll use Axios for making HTTP requests.
npm install axios
3. Create the Recommendation System
Replace the contents of src/App.js with the following code:
src/App.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import './App.css';
function App() {
const [products, setProducts] = useState([]);
const [filters, setFilters] = useState({
category: '',
minRating: '',
material: '',
brand: '',
});
useEffect(() => {
fetchProducts();
}, [filters]);
const fetchProducts = async () => {
try {
const response = await axios.get('http://localhost:5000/api/products', {
params: filters,
});
setProducts(response.data);
} catch (error) {
console.error('Error fetching products:', error);
}
};
const handleChange = (e) => {
setFilters({
...filters,
[e.target.name]: e.target.value,
});
};
return (
<div className="App">
<h1>Sustainable Fashion Recommendations</h1>
<div className="filters">
<h2>Filter Products</h2>
<div className="filter-group">
<label>Category:</label>
<select name="category" value={filters.category} onChange={handleChange}>
<option value="">All</option>
<option value="Tops">Tops</option>
<option value="Outerwear">Outerwear</option>
<option value="Accessories">Accessories</option>
{/* Add more categories as needed */}
</select>
</div>
<div className="filter-group">
<label>Minimum Sustainability Rating:</label>
<input
type="number"
name="minRating"
min="1"
max="10"
value={filters.minRating}
onChange={handleChange}
/>
</div>
<div className="filter-group">
<label>Material:</label>
<input
type="text"
name="material"
placeholder="e.g., Organic Cotton"
value={filters.material}
onChange={handleChange}
/>
</div>
<div className="filter-group">
<label>Brand:</label>
<input
type="text"
name="brand"
placeholder="e.g., EcoWear"
value={filters.brand}
onChange={handleChange}
/>
</div>
</div>
<div className="product-list">
{products.length === 0 ? (
<p>No products match your criteria.</p>
) : (
products.map((product) => (
<div key={product.id} className="product-card">
<img src={product.image} alt={product.name} />
<h3>{product.name}</h3>
<p><strong>Brand:</strong> {product.brand}</p>
<p><strong>Category:</strong> {product.category}</p>
<p>
<strong>Sustainability Rating:</strong> {product.sustainabilityRating}/10
</p>
<p><strong>Materials:</strong> {product.materials.join(', ')}</p>
</div>
))
)}
</div>
</div>
);
}
export default App;
4. Add Basic Styling
Create a src/App.css file to style the application.
src/App.css
.App {
font-family: Arial, sans-serif;
padding: 20px;
}
h1 {
text-align: center;
color: #2e7d32;
}
.filters {
margin-bottom: 30px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
.filter-group {
margin-bottom: 15px;
}
.filter-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.filter-group input,
.filter-group select {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
.product-list {
display: flex;
flex-wrap: wrap;
gap: 20px;
justify-content: center;
}
.product-card {
border: 1px solid #ddd;
border-radius: 10px;
padding: 15px;
width: 200px;
text-align: center;
}
.product-card img {
max-width: 100%;
border-radius: 5px;
}
.product-card h3 {
margin: 10px 0;
color: #388e3c;
}
.product-card p {
margin: 5px 0;
font-size: 14px;
}
5. Run the Frontend
Start the React application.
npm start
Your frontend should now be running at http://localhost:3000 and will communicate with the backend API at http://localhost:5000.
Step 3: Enhancements and Deployment
1. Using a Real API
If you find a suitable public API in the future, replace the mock data in the backend with actual API calls. Ensure to handle API keys and rate limiting as per the API provider's guidelines.
2. User Authentication
To personalize recommendations further, consider adding user authentication and storing user preferences.
3. Advanced Recommendation Algorithms
Implement more sophisticated recommendation algorithms using machine learning techniques based on user behavior and preferences.
4. Deployment
- Backend: Deploy the Node.js server to platforms like Heroku, Vercel, or AWS.
- Frontend: Deploy the React app using Netlify, Vercel, or GitHub Pages.
- Environment Variables: Manage API URLs and keys using environment variables for security.
Final Thoughts
This example provides a foundational structure for a sustainable fashion recommendation system using JavaScript. Depending on your requirements and available data sources, you can expand and refine the system with more features, better data handling, and enhanced user experiences.
Feel free to modify the mock data to better reflect real-world scenarios or integrate with actual sustainability-focused APIs as they become available.