Skip to content

Instantly share code, notes, and snippets.

@s2t2
Last active June 3, 2018 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s2t2/73590080926aa532821d8763389b8794 to your computer and use it in GitHub Desktop.
Save s2t2/73590080926aa532821d8763389b8794 to your computer and use it in GitHub Desktop.
products api client
import json
import requests
base_url = "https://nyu-info-2335-products-api-csv.herokuapp.com"
def list_products():
response = requests.get(f"{base_url}/products")
return parsed_response(response)
def show_product(product_id):
response = requests.get(f"{base_url}/products/{product_id}")
return parsed_response(response)
# param dict `new_product_attributes` does not expect to have an "id" attribute
def create_product(new_product_attributes):
response = requests.post(f"{base_url}/products", json=new_product_attributes)
return parsed_response(response)
# param dict `edited_product_attributes` should have an "id" attribute
def update_product(edited_product_attributes):
product_id = edited_product_attributes["id"]
response = requests.put(f"{base_url}/products/{product_id}", json=edited_product_attributes)
return parsed_response(response)
def destroy_product(product_id):
response = requests.delete(f"{base_url}/products/{product_id}")
return parsed_response(response)
def parsed_response(response):
return json.loads(response.text)
if __name__ == '__main__':
print("--------------------")
products = list_products()
print(f"LISTING {len(products)} PRODUCTS:")
print("...", [product["id"] for product in products])
#print("... ids:", [product["id"] for product in products])
#print("... first: ", products[1])
#print("... last: ", products[-1])
print("--------------------")
if len(products) > 0:
id = products[1]["id"]
print(f"DESTROYING PRODUCT #{id}")
results = destroy_product(id)
print("...", results)
else:
print("DESTROYING NOTHING")
print("--------------------")
print("CREATING A PRODUCT")
new_product = create_product({"name": "My New Product", "aisle": "pending", "department": "pending", "price":3.00})
print("...", new_product)
print("--------------------")
print("SHOWING A PRODUCT")
product = show_product(new_product["id"])
print("...", product)
print("--------------------")
print("UPDATING A PRODUCT")
new_product["aisle"] = "updated aisle"
new_product["department"] = "updated dept"
new_product["price"] = 100.00
updated_product = update_product(new_product)
print("...", updated_product)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment