Example DBBasic apps (an API, a blog and a microblog) and a template for new DBBasic modules.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-examples.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-examples.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-examples.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add official module template for creating DBBasic packages 17cf88a 1 year, 1 month ago History
README.md

DBBasic REST API Example

A complete REST API built with dbbasic-web demonstrating:

  • JSON API endpoints
  • Bearer token authentication
  • CRUD operations
  • Filtering and pagination
  • Proper HTTP status codes

Features

  • Authentication: Token-based auth (no cookies)
  • Tasks CRUD: Full create, read, update, delete
  • Filtering: Filter by status, search text
  • Pagination: Page through results
  • Security: Per-user data isolation

API Endpoints

Authentication

  • POST /auth/register - Create account
  • POST /auth/login - Get API token
  • POST /auth/logout - Invalidate token

Tasks

  • GET /tasks - List tasks (supports ?status=done&search=foo&page=1&limit=20)
  • POST /tasks - Create task
  • GET /tasks/<id> - Get single task
  • PUT /tasks/<id> - Update task
  • DELETE /tasks/<id> - Delete task

Utility

  • GET / - API documentation
  • GET /health - Health check

Usage

1. Start server

cd api
uvicorn dbbasic_web.asgi:app --reload --port 8000

2. Register

curl -X POST http://localhost:8000/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"secret","name":"User"}'

3. Login (get token)

curl -X POST http://localhost:8000/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"secret"}'

# Response: {"success": true, "token": "eyJ1c2VyX2lkIjog..."}

4. Use token for API requests

TOKEN="eyJ1c2VyX2lkIjog..."  # Your token from login

# Create task
curl -X POST http://localhost:8000/tasks \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"title":"Buy groceries","description":"Milk, eggs, bread","status":"todo"}'

# List tasks
curl http://localhost:8000/tasks \
  -H "Authorization: Bearer $TOKEN"

# Update task
curl -X PUT http://localhost:8000/tasks/TASK_ID \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"status":"done"}'

# Delete task
curl -X DELETE http://localhost:8000/tasks/TASK_ID \
  -H "Authorization: Bearer $TOKEN"

5. Filtering & Pagination

# Get only completed tasks
curl "http://localhost:8000/tasks?status=done" \
  -H "Authorization: Bearer $TOKEN"

# Search tasks
curl "http://localhost:8000/tasks?search=grocery" \
  -H "Authorization: Bearer $TOKEN"

# Paginate (20 per page)
curl "http://localhost:8000/tasks?page=2&limit=20" \
  -H "Authorization: Bearer $TOKEN"

What This Example Shows

1. Bearer Token Authentication

Unlike blog/microblog (cookie-based), this uses Authorization: Bearer <token> headers - standard for REST APIs.

def require_api_auth(request):
    """Get authenticated user from Bearer token"""
    auth_header = None
    for name, value in request.get('headers', []):
        if name.lower() == b'authorization':
            auth_header = value.decode('utf-8')
            break

    if not auth_header or not auth_header.startswith('Bearer '):
        return None, json_error("No token provided", status=401)

    token = auth_header[7:]  # Remove "Bearer " prefix
    user_id = get_session(token)
    # ... validate token ...

2. JSON Body Parsing

All POST/PUT endpoints parse JSON:

try:
    data = json_lib.loads(request.body.decode('utf-8'))
except:
    return json_error("Invalid JSON", status=400)

3. RESTful Routing

Single file handles both collection and item endpoints:

def handle(request):
    user, error = require_api_auth(request)
    if error:
        return error

    task_id = request.path_param(1)

    if task_id:
        # /tasks/<id> - GET, PUT, DELETE
        if request.method == 'GET':
            # ...
        elif request.method == 'PUT':
            # ...
        elif request.method == 'DELETE':
            # ...
    else:
        # /tasks - GET, POST
        if request.method == 'GET':
            # ...
        elif request.method == 'POST':
            # ...

4. Query Parameter Filtering

status_filter = request.GET.get('status')
search = request.GET.get('search')
page = int(request.GET.get('page', 1))
limit = int(request.GET.get('limit', 20))

5. Proper HTTP Status Codes

  • 201 Created - After POST
  • 401 Unauthorized - No/invalid token
  • 403 Forbidden - Not your resource
  • 404 Not Found - Resource doesn't exist
  • 405 Method Not Allowed - Wrong HTTP method

Data Storage

Tasks stored in data/tasks.tsv:

id	user_id	title	description	status	created	updated
1760351773200	1000	Buy groceries	Milk, eggs	todo	2025-10-13 05:36:13	2025-10-13 05:36:13

User accounts in etc/passwd.tsv and etc/shadow.tsv (managed by dbbasic-accounts).

What's Different from Rails/Express?

Simpler:

  • No ORM - direct TSV queries
  • No routes file - filesystem routing
  • No middleware chain - simple auth function
  • No serializers - direct JSON dumps

But Still Has:

  • Authentication
  • Request parsing
  • Query parameters
  • Pagination
  • Filtering
  • Proper REST semantics

This is the Unix way: simple tools, composed well.