Skip to content

Instantly share code, notes, and snippets.

@AseemWangoo
Created December 3, 2024 15:29
Show Gist options
  • Save AseemWangoo/df5ae772d88ca8ab7883136ebbaee258 to your computer and use it in GitHub Desktop.
Save AseemWangoo/df5ae772d88ca8ab7883136ebbaee258 to your computer and use it in GitHub Desktop.
Flask Gist
from flask import Flask, jsonify, request
import requests
app = Flask(__name__)
# In-memory
products = []
@app.route("/")
def hello_world():
return "hello"
@app.route("/products", methods=["GET", "POST"])
def productsRequest():
if request.method == "GET":
try:
response = requests.get("https://dummyjson.com/products")
response.raise_for_status()
data = response.json()
products.append(data.get("products"))
return jsonify(products), 200
except requests.exceptions.RequestException as e:
print(f"Error fetching initial products: {e}")
products = []
elif request.method == "POST":
try:
body = request.json
title = body.get("title")
price = body.get("price")
category = body.get("category")
if not title or not price or not category:
return (
jsonify(
{
"error": "Missing required fields: 'title', 'price', or 'category'"
}
),
400,
)
products.append(body)
return jsonify(products), 201
except Exception as e:
return jsonify({"error": "Something went wrong"}), 500
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment