Getting Started

This section outlines the project layout for the Flask-based REST API. You’ll find core application files, database setup, ORM models, resource endpoints, security helpers, Postman assets, and the tutorial README. Understanding this structure helps you navigate and extend the service quickly.

Directory Structure

The entire application resides under the PYTHON/ folder:

PYTHON/
├── app.py
├── db.py
├── models/
│   ├── book.py
│   ├── store.py
│   └── user.py
├── resources/
│   ├── book.py
│   ├── store.py
│   └── user.py
├── security.py
├── postman-collections/
│   └── Python Rest API.postman_collection.json
└── readme.md

Core Application Files

These files bootstrap and configure the Flask app.

app.py 🚀

Entry point for the application. It:

  • Creates the Flask app and wraps it with Flask-RESTful’s Api.
  • Configures the SQLite database URI and SQLAlchemy options.
  • Registers the JWT authentication handler at /auth.
  • Registers all resource endpoints.
  • Initializes the database before the first request.
from flask import Flask
from flask_restful import Api
from flask_jwt import JWT
from security import authenticate, identity
from resources.user import UserRegister
from resources.book import Book, BookList
from resources.store import Store, StoreList

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['PROPAGATE_EXCEPTIONS'] = True
app.secret_key = 'SapanCrackle'

api = Api(app)

@app.before_first_request
def create_tables():
    db.create_all()

jwt = JWT(app, authenticate, identity)  # /auth

api.add_resource(Store, '/store/<string:name>')
api.add_resource(StoreList, '/stores')
api.add_resource(Book, '/book/<string:title>')
api.add_resource(BookList, '/books')
api.add_resource(UserRegister, '/register')

if __name__ == '__main__':
    from db import db
    db.init_app(app)
    app.run(port=5000, debug=True)

Key responsibilities are laid out here.

db.py 📦

Holds the global SQLAlchemy instance. All models import this to define tables and relationships.

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

Used to connect models to the Flask app.

security.py 🔒

Provides JWT authentication callbacks:

  • authenticate(username, password): Verifies credentials and returns a user.
  • identity(payload): Fetches a user by JWT payload identity.
from werkzeug.security import safe_str_cmp
from models.user import UserModel

def authenticate(username, password):
    user = UserModel.find_by_username(username)
    if user and safe_str_cmp(user.password, password):
        return user

def identity(payload):
    user_id = payload['identity']
    return UserModel.find_by_id(user_id)

Enables Flask-JWT login flow.

Models

SQLAlchemy ORM models map Python classes to database tables.

File Model Purpose
models/book.py BookModel Defines book fields (title, author, isbn, release_date, price, store_id), JSON serialization, and CRUD helpers.
models/store.py StoreModel Defines store fields (name), one-to-many relationship to books, JSON output, and persistence helpers.
models/user.py UserModel Defines user fields (username, password) and lookup helpers for registration and JWT.

Resources

Flask-RESTful resource classes expose HTTP endpoints for CRUD operations.

resources/book.py 📚

Handles /book/<title> and /books:

  • GET /book/<title>: Retrieve a book (JWT required).
  • POST /book/<title>: Create a book.
  • DELETE /book/<title>: Remove a book.
  • PUT /book/<title>: Upsert a book.
  • GET /books: List all books.

Key classes: Book, BookList with request parsing and JSON serialization.

resources/store.py 🏬

Handles /store/<name> and /stores:

  • GET /store/<name>: Retrieve a store and its books.
  • POST /store/<name>: Create a store.
  • DELETE /store/<name>: Remove a store.
  • GET /stores: List all stores.

Classes: Store, StoreList.

resources/user.py 👤

Handles user registration at /register:

  • POST /register: Create a new user with unique username.

Class: UserRegister.

Postman Collection

A Postman v2.1 JSON collection with ready-made requests for all endpoints, including JWT token management via globals.

postman-collections/Python Rest API.postman_collection.json

It covers /books, /stores, /book/<name>, /store/<name>, /auth, and /register.

README

readme.md provides a tutorial-style guide:

  • Environment setup (Python 3.8, virtualenv).
  • Library installation.
  • Running the app (python app.py).
  • Endpoint overview and example requests/responses.
{
    "title": "Tip",
    "content": "Ensure you call `db.init_app(app)` before running to bind your models to the Flask app."
}

With this layout, you can quickly locate and modify any aspect of the service, from database models to authentication flows.