To create an Application Programming Interface (API) for a clothing store that allows third-party vendors to access real-time product information, you can use Python and a framework like Flask to build the API. The API will provide endpoints for fetching products, their attributes, and images. Once created, you can use tools like Postman to test the API.
Step 1: Setup the Environment and Libraries
First, you need to install the required libraries:
pip install flask flask_sqlalchemy marshmallow flask-marshmallow
- Flask: Lightweight web framework to build the API.
- SQLAlchemy: ORM for database interactions.
- Marshmallow: For serializing and deserializing objects.
You’ll also need a database to store product information, which could be a simple SQLite or MySQL/PostgreSQL database.
Step 2: Create the API in Flask
Here’s an example code to build the API.
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
# Initialize the Flask app
app = Flask(__name__)
# Setup the SQLite database URI
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///clothing_store.db'
db = SQLAlchemy(app)
ma = Marshmallow(app)
# Product model
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
price = db.Column(db.Float, nullable=False)
description = db.Column(db.String(200), nullable=False)
image_url = db.Column(db.String(200), nullable=False)
stock_quantity = db.Column(db.Integer, nullable=False)
def __init__(self, name, price, description, image_url, stock_quantity):
self.name = name
self.price = price
self.description = description
self.image_url = image_url
self.stock_quantity = stock_quantity
# Product Schema
class ProductSchema(ma.Schema):
class Meta:
fields = ('id', 'name', 'price', 'description', 'image_url', 'stock_quantity')
# Initialize schema
product_schema = ProductSchema()
products_schema = ProductSchema(many=True)
# Create the database tables
with app.app_context():
db.create_all()
# Get all products
@app.route('/api/products', methods=['GET'])
def get_products():
all_products = Product.query.all()
result = products_schema.dump(all_products)
return jsonify(result)
# Get a single product by ID
@app.route('/api/product/<id>', methods=['GET'])
def get_product(id):
product = Product.query.get(id)
return product_schema.jsonify(product)
# Add a new product (this would be done by store admin)
@app.route('/api/product', methods=['POST'])
def add_product():
name = request.json['name']
price = request.json['price']
description = request.json['description']
image_url = request.json['image_url']
stock_quantity = request.json['stock_quantity']
new_product = Product(name, price, description, image_url, stock_quantity)
db.session.add(new_product)
db.session.commit()
return product_schema.jsonify(new_product)
# Update product details
@app.route('/api/product/<id>', methods=['PUT'])
def update_product(id):
product = Product.query.get(id)
name = request.json['name']
price = request.json['price']
description = request.json['description']
image_url = request.json['image_url']
stock_quantity = request.json['stock_quantity']
product.name = name
product.price = price
product.description = description
product.image_url = image_url
product.stock_quantity = stock_quantity
db.session.commit()
return product_schema.jsonify(product)
# Delete a product
@app.route('/api/product/<id>', methods=['DELETE'])
def delete_product(id):
product = Product.query.get(id)
db.session.delete(product)
db.session.commit()
return product_schema.jsonify(product)
# Run the app
if __name__ == '__main__':
app.run(debug=True)
Explanation of the API Endpoints:
/api/products
: Returns a list of all products in the database (for third-party vendors to display products)./api/product/<id>
: Returns a single product by its ID./api/product
[POST]: Adds a new product to the database (this can be accessed by the store admin)./api/product/<id>
[PUT]: Updates an existing product./api/product/<id>
[DELETE]: Deletes a product from the store.
Testing the API Using Postman
- Install Postman: Download and install Postman from https://www.postman.com/downloads/.
- Test GET Products:
- Open Postman, select GET, and enter
http://127.0.0.1:5000/api/products
. - Click Send to retrieve the list of products.
- Test POST Product:
- Select POST and use the URL
http://127.0.0.1:5000/api/product
. - In Body, select raw, and choose JSON.
- Add the following JSON:
{
"name": "Cowboy Boots",
"price": 199.99,
"description": "High-quality leather boots",
"image_url": "https://example.com/images/boots.jpg",
"stock_quantity": 10
}
- Click Send to create the product.
- Test PUT Product:
- Select PUT and use the URL
http://127.0.0.1:5000/api/product/1
. - Update the product details in Body (use the same format as above).
- Click Send to update the product.
- Test DELETE Product:
- Select DELETE and use the URL
http://127.0.0.1:5000/api/product/1
. - Click Send to delete the product.
Libraries Used:
- Flask: This is the core framework used for routing, handling HTTP requests, and serving the API.
- Flask-SQLAlchemy: This is the ORM (Object-Relational Mapper) that connects the app to the database.
- Flask-Marshmallow: Handles serialization and deserialization of the Product model, making it easy to convert the database objects to JSON format.
How to Deploy the API
To deploy the API for production, you can:
- Host it on platforms like Heroku, AWS, or DigitalOcean.
- Use a more robust server like Gunicorn with Flask.
- Secure the API with authentication mechanisms such as JWT tokens or OAuth if you want to restrict access to authorized third-party vendors only.
This setup provides a basic API for a clothing store.
It enables third-party vendors to access product data and images in real time.
Third-party users can access this data via the provided API endpoints and use it to market products on their websites or apps.
How We Can Help!
All Pro Web Designs can help you achieve these tasks or any other ongoing need for scalable, secure, and responsive digital solutions.
Please request a quote today!
Leave a Reply