Skip to main content

In depth: Store resources

The Store Resource has:

  • get(name): clients can use this to retrieve information about one store;
  • post(name): clients can use this to create a store;
  • delete(name): clients can use this to delete a store.

There's also an StoreList Resource that has:

  • get(): clients can use this to retrieve data about all stores in our collection and their items.

Code for resources/store.py

from flask_restful import Resource
from models.store import StoreModel


class Store(Resource):
def get(self, name):
store = StoreModel.find_by_name(name)
if store:
return store.json()
return {"message": "Store not found."}, 404

def post(self, name):
if StoreModel.find_by_name(name):
return (
{"message": "A store with name '{}' already exists.".format(name)},
400,
)

store = StoreModel(name)
try:
store.save_to_db()
except:
return {"message": "An error occurred while creating the store."}, 500

return store.json(), 201

def delete(self, name):
store = StoreModel.find_by_name(name)
if store:
store.delete_from_db()

return {"message": "Store deleted."}


class StoreList(Resource):
def get(self):
return {"stores": [x.json() for x in StoreModel.find_all()]}

Now that you've learned about the Item resource, understanding the Store resource is very straightforward, because:

  • It's a much simpler resource with no argument parsing and only using the URL parameter, name.
  • It does not use Flask-JWT-Extended so there are no JWT requirements.
  • There is very little logic, it's mainly a resource that accepts and retrieves data from the database by using models.

Creating a store before an item

An important question is: must you create a store before you create your first item?

If you're asking this question, good on you!

An item needs a store_id property, which means that if there are no stores before you create an item, you should not be able to give items a valid store_id (as there are no stores with an id).

If you run this application using a fully-fledged database, such as PostgreSQL or MySQL, you'll find that you need to create a store before you can create an item–so that the id of the store and the store_id of the item match.

However, if you run this using SQLite (as we do in our tests), this restriction does not apply. You could give an item a store_id of a store that doesn't exist, and SQLite would accept it. It's just one of those things about using a "lite" SQL database.

warning

SQLite does not enforce foreign keys, such as store_id, to have a valid primary key counterpart. This is worth remembering if you test your application with a different database system than it will run in production (which is often not recommended!).

For maximum confidence in your application, at least run it using the same database you'll use in production before deploying. Even if you develop using SQLite, make sure to do a trial run on your production database system before going live!