Project Structure – Entry Point (app.py)

Welcome to the Entry Point documentation for the demo RESTful API built with Python’s Flask framework. This section dives into app.py, which bootstraps the entire application: initializing Flask, configuring extensions (SQLAlchemy, JWT), setting up the database, and registering all API resources.

Index

  1. Overview
  2. Imports
  3. Application Configuration
  4. Database Initialization
  5. JWT Authentication
  6. Resource Routing
  7. Running the Application
  8. Architecture Overview
  9. API Endpoints

Overview

The app.py file serves as the entry point of the application. It:

  • Creates the Flask application instance
  • Configures database and exception handling
  • Hooks into Flask’s startup lifecycle to create tables
  • Initializes JWT-based authentication
  • Registers RESTful resources (routes)
  • Launches the development server
# PYTHON/app.py (excerpt)
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

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

Imports

Module / Object Purpose
Flask Core Flask application factory
Api Flask-RESTful wrapper for routing
JWT Flask-JWT extension for token-based authentication
authenticate, identity Security handlers mapping credentials → user & token payload → user (security.py)
UserRegister Resource for user sign-up (resources/user.py)
Book, BookList CRUD resources for individual books & book collections (resources/book.py)
Store, StoreList CRUD resources for stores (resources/store.py)

Imports in app.py:

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

Application Configuration

After creating the Flask app, several configuration keys are set:

Key Value Description
SQLALCHEMY_DATABASE_URI sqlite:///data.db SQLite file database
SQLALCHEMY_TRACK_MODIFICATIONS True Enable event notifications (overhead in production)
PROPAGATE_EXCEPTIONS True Let exceptions propagate for unified error handling
secret_key 'SapanCrackle' Cryptographic key for session & JWT signature
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['PROPAGATE_EXCEPTIONS'] = True
app.secret_key = 'SapanCrackle'

Database Initialization

A SQLAlchemy instance is declared in db.py and bound to the Flask app on startup:

# db.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

In app.py, tables are auto-created before the first request:

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

Then, within the __main__ guard, SQLAlchemy is initialized:

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

This ensures all models (User, Book, Store) generate their corresponding tables in data.db .


JWT Authentication

Flask-JWT is initialized to provide a /auth endpoint:

jwt = JWT(app, authenticate, identity)  # exposes /auth
  • authenticate(username, password): Validates credentials against stored users.
  • identity(payload): Loads a user by ID embedded in a valid token.

These functions reside in security.py and interact with UserModel .


Resource Routing

All REST resources are registered on the Flask-RESTful Api instance:

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')

This maps:

  • Store → /store/<name>
  • StoreList → /stores
  • Book → /book/<title>
  • BookList → /books
  • UserRegister → /register

Running the Application

Execute via:

python app.py
  • Host: localhost
  • Port: 5000
  • Debug Mode: Enabled for live reload & detailed errors

Architecture Overview

graph TD
  subgraph Entry Point (app.py)
    A[Flask App] --> B[Flask-RESTful Api]
    A --> C[SQLAlchemy(db)]
    A --> D[JWT Auth]
    A --> E[create_tables()]
  end

  subgraph Resources
    Store --> StoreModel
    StoreList --> StoreModel
    Book --> BookModel
    BookList --> BookModel
    UserRegister --> UserModel
  end

  subgraph Models & DB
    StoreModel & BookModel & UserModel --> C
  end

  D --> security.py
  security.py --> UserModel

API Endpoints

Below are interactive API blocks for each route defined in app.py. The baseUrl is http://localhost:5000.

{
  "title": "Authenticate User",
  "description": "Obtain a JWT access token using valid credentials",
  "method": "POST",
  "baseUrl": "http://localhost:5000",
  "endpoint": "/auth",
  "headers": [
    {"key": "Content-Type", "value": "application/json", "required": true}
  ],
  "bodyType": "json",
  "requestBody": "{\n  \"username\": \"sapan\",\n  \"password\": \"sapan1234\"\n}",
  "responses": {
    "200": {
      "description": "Token returned",
      "body": "{\n  \"access_token\": \"<jwt_token>\"\n}"
    },
    "401": {
      "description": "Invalid credentials",
      "body": "{\n  \"message\": \"Invalid credentials\"\n}"
    }
  }
}
{
  "title": "Register User",
  "description": "Create a new user account",
  "method": "POST",
  "baseUrl": "http://localhost:5000",
  "endpoint": "/register",
  "headers": [
    {"key": "Content-Type", "value": "application/json", "required": true}
  ],
  "bodyType": "json",
  "requestBody": "{\n  \"username\": \"sapan\",\n  \"password\": \"sapan1234\"\n}",
  "responses": {
    "201": {
      "description": "User created",
      "body": "{\n  \"message\": \"User created successfully.\"\n}"
    },
    "400": {
      "description": "Username already exists",
      "body": "{\n  \"message\": \"A user with that username already exists\"\n}"
    }
  }
}
{
  "title": "Get Store",
  "description": "Retrieve details of a store by name",
  "method": "GET",
  "baseUrl": "http://localhost:5000",
  "endpoint": "/store/{name}",
  "pathParams": [
    {"key": "name", "value": "Name of the store", "required": true}
  ],
  "bodyType": "none",
  "responses": {
    "200": {
      "description": "Store found",
      "body": "{\n  \"name\": \"MyStore\",\n  \"books\": []\n}"
    },
    "404": {
      "description": "Store not found",
      "body": "{\n  \"message\": \"Store not found\"\n}"
    }
  }
}
{
  "title": "Create Store",
  "description": "Create a new store",
  "method": "POST",
  "baseUrl": "http://localhost:5000",
  "endpoint": "/store/{name}",
  "pathParams": [
    {"key": "name", "value": "Name of the new store", "required": true}
  ],
  "bodyType": "none",
  "responses": {
    "201": {
      "description": "Store created",
      "body": "{\n  \"name\": \"NewStore\",\n  \"books\": []\n}"
    },
    "400": {
      "description": "Store already exists",
      "body": "{\n  \"message\": \"A store with name 'NewStore' already exists.\"\n}"
    },
    "500": {
      "description": "Server error",
      "body": "{\n  \"message\": \"An error occurred creating the store.\"\n}"
    }
  }
}
{
  "title": "Delete Store",
  "description": "Delete an existing store",
  "method": "DELETE",
  "baseUrl": "http://localhost:5000",
  "endpoint": "/store/{name}",
  "pathParams": [
    {"key": "name", "value": "Name of the store to delete", "required": true}
  ],
  "bodyType": "none",
  "responses": {
    "200": {
      "description": "Store deleted",
      "body": "{\n  \"message\": \"Store deleted\"\n}"
    }
  }
}
{
  "title": "List Stores",
  "description": "Retrieve a list of all stores",
  "method": "GET",
  "baseUrl": "http://localhost:5000",
  "endpoint": "/stores",
  "bodyType": "none",
  "responses": {
    "200": {
      "description": "List of stores",
      "body": "{\n  \"stores\": [ { \"name\": \"MyStore\", \"books\": [] } ]\n}"
    }
  }
}
{
  "title": "Get Book",
  "description": "Retrieve a book by title (JWT required)",
  "method": "GET",
  "baseUrl": "http://localhost:5000",
  "endpoint": "/book/{title}",
  "headers": [
    {"key": "Authorization", "value": "JWT <token>", "required": true}
  ],
  "pathParams": [
    {"key": "title", "value": "Title of the book", "required": true}
  ],
  "bodyType": "none",
  "responses": {
    "200": {
      "description": "Book found",
      "body": "{\n  \"title\": \"MyBook\",\n  \"price\": 9.99,\n  \"author\": \"Jane Doe\",\n  \"isbn\": \"12345\",\n  \"release_date\": \"2021-01-01\"\n}"
    },
    "404": {
      "description": "Book not found",
      "body": "{\n  \"message\": \"book not found\"\n}"
    }
  }
}
{
  "title": "Create Book",
  "description": "Add a new book by title",
  "method": "POST",
  "baseUrl": "http://localhost:5000",
  "endpoint": "/book/{title}",
  "pathParams": [
    {"key": "title", "value": "Title of the new book", "required": true}
  ],
  "bodyType": "json",
  "requestBody": "{\n  \"price\": 19.99,\n  \"store_id\": 1,\n  \"author\": \"Jane Doe\",\n  \"isbn\": \"67890\",\n  \"release_date\": \"2022-02-02\"\n}",
  "responses": {
    "201": {
      "description": "Book created",
      "body": "{\n  \"title\": \"MyBook\",\n  \"price\": 19.99,\n  \"author\": \"Jane Doe\",\n  \"isbn\": \"67890\",\n  \"release_date\": \"2022-02-02\"\n}"
    },
    "400": {
      "description": "Book already exists",
      "body": "{\n  \"message\": \"An book with title 'MyBook' already exists.\"\n}"
    },
    "500": {
      "description": "Server error",
      "body": "{\n  \"message\": \"An error occurred inserting the book.\"\n}"
    }
  }
}
{
  "title": "Delete Book",
  "description": "Remove a book by title",
  "method": "DELETE",
  "baseUrl": "http://localhost:5000",
  "endpoint": "/book/{title}",
  "pathParams": [
    {"key": "title", "value": "Title of the book to delete", "required": true}
  ],
  "bodyType": "none",
  "responses": {
    "200": {
      "description": "Book deleted",
      "body": "{\n  \"message\": \"Item deleted.\"\n}"
    },
    "404": {
      "description": "Book not found",
      "body": "{\n  \"message\": \"Item not found.\"\n}"
    }
  }
}
{
  "title": "Upsert Book",
  "description": "Update price or create a new book",
  "method": "PUT",
  "baseUrl": "http://localhost:5000",
  "endpoint": "/book/{title}",
  "pathParams": [
    {"key": "title", "value": "Title of the book", "required": true}
  ],
  "bodyType": "json",
  "requestBody": "{\n  \"price\": 25.00,\n  \"store_id\": 1,\n  \"author\": \"Jane Doe\",\n  \"isbn\": \"67890\",\n  \"release_date\": \"2022-02-02\"\n}",
  "responses": {
    "200": {
      "description": "Book updated or created",
      "body": "{\n  \"title\": \"MyBook\",\n  \"price\": 25.00,\n  \"author\": \"Jane Doe\",\n  \"isbn\": \"67890\",\n  \"release_date\": \"2022-02-02\"\n}"
    }
  }
}
{
  "title": "List Books",
  "description": "Retrieve all books",
  "method": "GET",
  "baseUrl": "http://localhost:5000",
  "endpoint": "/books",
  "bodyType": "none",
  "responses": {
    "200": {
      "description": "Collection of books",
      "body": "{\n  \"books\": [\n    { \"title\": \"MyBook\", \"price\": 19.99, \"author\": \"Jane Doe\", \"isbn\": \"67890\", \"release_date\": \"2022-02-02\" }\n  ]\n}"
    }
  }
}

This comprehensive documentation covers how app.py orchestrates the application lifecycle, dependencies, and exposes the full suite of RESTful endpoints. It ties together the Flask core, SQLAlchemy ORM, Flask-JWT authentication, and all resource controllers in a coherent structure.