https://github.com/snaapi/snaapi
Rapid API development platform without writing code
https://github.com/snaapi/snaapi
ai-tools api deno no-code openapi typescript
Last synced: about 12 hours ago
JSON representation
Rapid API development platform without writing code
- Host: GitHub
- URL: https://github.com/snaapi/snaapi
- Owner: snaapi
- License: other
- Created: 2025-02-17T22:39:14.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2026-03-26T15:08:30.000Z (7 days ago)
- Last Synced: 2026-03-26T21:48:25.825Z (7 days ago)
- Topics: ai-tools, api, deno, no-code, openapi, typescript
- Language: TypeScript
- Homepage: https://snaapi.dev
- Size: 5.84 MB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 7
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
- Cla: CLA.md
Awesome Lists containing this project
README
# Snaapi
A production-ready platform that enables rapid API development without writing
code. Easily define resources, configure permissions, and instantly get an API
with built-in authentication, documentation, role-based access control,
webhooks, and event streaming.

## Overview
Snaapi transforms API development from weeks to minutes. Define your data models
through a web console or YAML configuration, set up role-based permissions, and
immediately get fully-functional API endpoints with authentication, validation,
and audit trails built in.
- **10x Faster Development**: Launch APIs in minutes instead of weeks
- **Enterprise-Grade Security**: Built-in RBAC with field-level and row-level
access control
- **Zero Infrastructure Management**: Complete backend platform in a single
deployment
- **Event-Driven Architecture**: Real-time webhooks and async job processing
included
- **Audit & Compliance**: Full event logging with session context and
distributed tracing
## Key Features
### Automatic API
- Define resources through web console or YAML
- Instant REST endpoints with full CRUD operations
- 10 field types: string, text, number, boolean, datetime, timestamp, json,
uuid, enum, relation
- Automatic schema validation
- OpenAPI spec generation (JSON and YAML) at global and per-resource levels
### Enterprise Security
- **Authentication**: Email/password, SSO, API keys with rate limiting (1000
req/min)
- **RBAC**: Role-based access control with granular permissions
- **Field-Level Security**: Control which fields are accessible per role
- **Row-Level Security**: Filter data based on user context via JWT claims
- **Auto-Injection**: Automatically populate fields (e.g., owner_id) based on
user context
- **API Key Management**: Hashed keys with expiration, rate limits, and usage
tracking
### Resource Management
- Dynamic resource definitions stored in registry
- Reusable field library across resources
- Soft delete support for data retention
- Resource enable/disable without data loss
- Import/Export configuration as YAML, GraphQL SDL (`.graphql`/`.gql`), or
Excel/CSV
- Automatic database table creation
### Event System & Webhooks
- Capture all lifecycle events (created, updated, deleted)
- Detailed change tracking with old/new state comparison
- Session variables (userId, role, IP, userAgent)
- Distributed tracing (traceId, spanId, requestId, correlationId)
- Webhook subscriptions with pattern matching (wildcards supported)
- Automatic retry with exponential backoff
- Delivery status tracking
### Real-Time Streaming
- Server-Sent Events (SSE) for real-time resource event streaming
- Subscribe to lifecycle events: created, updated, deleted
- Filter events by type and select specific fields
- Role-based access control applied to streamed data
- Automatic heartbeat every 30s to keep connections alive
- Auto-reconnect with 3s retry directive
### Background Job Processing
- Event-driven job execution system
- Pattern-based job routing (glob matching)
- Configurable retry policies with exponential backoff
- Execution locking prevents concurrent processing
- Detailed invocation tracking per attempt
- Built-in processors: resource table creation, webhook delivery
### Admin Console
- Full-featured web UI built with Fresh and Preact
- Resource creation wizard
- Permission builder with visual constraint editor
- User and role management
- AI Chat Assistant (`/console/chat`) for natural-language resource management
- Analytics Dashboard (`/console/analytics`) with real-time metrics
- AI Content Generation for seeding resources with sample data
- Getting Started wizard for guided initial setup
- Event log viewer for audit trails
- Webhook configuration and monitoring
- Light/dark theme support
## Technical Architecture
### Technology Stack
**Backend:**
- **Runtime**: Deno with TypeScript
- **Framework**: Fresh (full-stack web framework)
- **Database**: PostgreSQL with JSONB storage
- **Authentication**: Better Auth with JWT sessions
- **Validation**: Valibot (TypeScript-native schema validation)
- **Observability**: OpenTelemetry integration
**Frontend:**
- **UI Framework**: Preact with server-side rendering
- **State Management**: Preact Signals
- **Styling**: Tailwind CSS + DaisyUI components
- **Build Tool**: Vite
### Data Flow
1. **Request** → Fresh app receives HTTP request
2. **Authentication** → Validates session/API key via Better Auth
3. **Resource Resolution** → Loads resource definition and permissions
4. **Validation** → Request validated against resource schema
5. **Field Filtering** → Only permitted fields processed
6. **Store Operation** → CRUD operation executed on PostgreSQL
7. **Event Emission** → Resource changes trigger events
8. **Webhook Dispatch** → Events sent to registered endpoints
9. **Job Processing** → Background jobs process events asynchronously
10. **Response** → Filtered response returned to client
## Getting Started
### Prerequisites
- Deno 2.6+ installed
- PostgreSQL 14+ database
- Environment variables configured (see Configuration section)
### Installation
```bash
# Clone repository
git clone https://github.com/snaapi/snaapi.git
cd snaapi
# Configure environment
cp .env.example .env
# Edit .env with your database URL and settings
# Start server
deno task dev
```
### Initial Setup
1. Navigate to `http://localhost:5173/install`
2. Enter installation token (from logs or set the `SNAAPI_INSTALL_TOKEN`
environment variable)
3. Create admin user with email and password
4. Initial API key generated automatically
5. Access admin console at `http://localhost:5173/console`
### Quick Example: Create Your First API
**Via Web Console:**
1. Navigate to `/console/resources/create`
2. Define resource (e.g., "posts")
3. Add fields (title, body, author_id)
4. Configure permissions (admin: full access, user: read-only)
5. Click Create → API endpoints instantly available
**Via YAML Import:**
```yaml
resources:
- name: posts
description: Blog posts
enabled: true
fields:
- name: title
type: string
required: true
- name: body
type: text
required: true
- name: author_id
type: uuid
required: true
permissions:
- role: admin
action: "*"
- role: user
action: read
```
Upload via `/console/resources` or POST to `/v1/_registry/import`
### API Usage
Once a resource is created, use these endpoints:
```bash
# List all records
GET /v1/posts
# Create record
POST /v1/posts
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY
{
"title": "Hello World",
"body": "My first post",
"author_id": "uuid-here"
}
# Get single record
GET /v1/posts/:id
# Update record
PATCH /v1/posts/:id
# Delete record
DELETE /v1/posts/:id
# Get resource OpenAPI spec
GET /v1/posts/openapi.json
```
## API Reference
### Resource Endpoints
| Method | Endpoint | Description |
| --------- | ---------------------------- | ------------------------------------------------------ |
| GET | `/v1/:resource` | List all records (with pagination, sorting, filtering) |
| POST | `/v1/:resource` | Create new record |
| GET | `/v1/:resource/:id` | Get single record by ID |
| PUT/PATCH | `/v1/:resource/:id` | Update record |
| DELETE | `/v1/:resource/:id` | Delete record |
| GET | `/v1/:resource/stream` | Stream real-time events via SSE |
| GET | `/v1/:resource/openapi.json` | Get resource OpenAPI spec (JSON) |
| GET | `/v1/:resource/openapi.yaml` | Get resource OpenAPI spec (YAML) |
### OpenAPI Spec Generation
Snaapi automatically generates OpenAPI 3.x specifications for your resources,
enabling integration with API documentation tools like Swagger UI, Redoc, and
Postman.
**Global Endpoints** — return a combined spec for all resources:
| Method | Endpoint | Description |
| ------ | --------------- | ------------------------ |
| GET | `/openapi.json` | Full OpenAPI spec (JSON) |
| GET | `/openapi.yaml` | Full OpenAPI spec (YAML) |
**Per-Resource Endpoints** — return the spec for a single resource:
| Method | Endpoint | Description |
| ------ | ---------------------------- | ---------------------------- |
| GET | `/v1/:resource/openapi.json` | Resource OpenAPI spec (JSON) |
| GET | `/v1/:resource/openapi.yaml` | Resource OpenAPI spec (YAML) |
By default, OpenAPI endpoints require authentication. Set
`SNAAPI_OPENAPI_PUBLIC=true` to make them publicly accessible without a token
(see [Configuration](#configuration)).
### Registry Endpoints (Admin Only)
| Method | Endpoint | Description |
| ------ | ------------------------------------- | -------------------------- |
| GET | `/v1/_registry/resources` | List all resources |
| POST | `/v1/_registry/resources` | Create new resource |
| GET | `/v1/_registry/resources/:id` | Get resource details |
| PUT | `/v1/_registry/resources/:id` | Update resource |
| DELETE | `/v1/_registry/resources/:id` | Delete resource |
| PUT | `/v1/_registry/resources/:id/enable` | Enable resource |
| PUT | `/v1/_registry/resources/:id/disable` | Disable resource |
| POST | `/v1/_registry/import` | Import resources from YAML |
| GET | `/v1/_registry/export` | Export resources as YAML |
**Import Formats:**
Snaapi supports multiple import formats for defining resources:
| Format | Method | Description |
| ------------------------------- | -------------- | ------------------------------------------------------------------------------- |
| YAML | API or Console | Full resource definitions with fields, permissions, settings |
| GraphQL SDL (`.graphql`/`.gql`) | Console UI | Schema-first import — types map to resources, fields infer types automatically |
| Excel/CSV | Console UI | Spreadsheet import — columns become fields with type inference from sample data |
The **Console Import/Export page** at `/console/registry/import-export` provides
a unified UI for all import formats with preview, field editing, and
conflict-resolution before committing changes.
### Webhook Endpoints (Admin Only)
| Method | Endpoint | Description |
| ------ | ------------------- | --------------------------- |
| GET | `/v1/_webhooks` | List all webhooks |
| POST | `/v1/_webhooks` | Create webhook subscription |
| GET | `/v1/_webhooks/:id` | Get webhook details |
| PUT | `/v1/_webhooks/:id` | Update webhook |
| DELETE | `/v1/_webhooks/:id` | Delete webhook |
### Query Parameters
**Filtering:**
```
?field__operator=value
Examples:
?status__eq=active
?age__gte=18
?name__like=%john%
?status__in=["active","pending"]
```
**Field Selection:**
```
?fields=field1,field2 # Select specific fields in response
Examples:
?fields=id,title,status
?fields=name,email
```
**Sorting:**
```
?_sort=field # Ascending
?_sort=-field # Descending
```
**Pagination:**
```
?_limit=50 # Records per page (max 1000)
?_offset=0 # Starting position
```
### User Query Filter Operators
These operators are available for filtering in API query parameters
(`?field__operator=value`):
| Operator | Description | Example |
| ------------------------ | ------------------------------------------ | --------------------------------- |
| `eq` | Equal | `status__eq=active` |
| `neq` | Not equal | `status__neq=draft` |
| `gt`, `gte` | Greater than (or equal) | `age__gte=18` |
| `lt`, `lte` | Less than (or equal) | `price__lt=100` |
| `in`, `nin` | In/not in array | `status__in=["active","pending"]` |
| `is_null`, `is_not_null` | Null check | `deleted_at__is_null=true` |
| `like`, `ilike` | Pattern match (case-sensitive/insensitive) | `name__ilike=%john%` |
### Real-Time Streaming (SSE)
Connect to the stream endpoint to receive real-time resource events via
Server-Sent Events. The stream respects role-based access control and field
permissions. See `src/resources/handlers.ts` streamHandler and
`src/resources/stream_handler.ts` for implementation details.
```bash
# Stream all events for a resource
curl -N -H "Authorization: Bearer YOUR_API_KEY" \
"https://your-app.com/v1/posts/stream"
# Filter by event type and fields
curl -N -H "Authorization: Bearer YOUR_API_KEY" \
"https://your-app.com/v1/posts/stream?events=created,updated&fields=title,body"
```
```javascript
// Browser usage with EventSource
// Note: EventSource does not support custom headers.
// Pass the token as a query parameter or use a polyfill library.
const stream = new EventSource(
"/v1/posts/stream?events=created,updated&fields=title,body&token=YOUR_API_KEY",
);
stream.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(`${data.eventType}:`, data.payload);
};
```
**Query Parameters:**
| Parameter | Description | Default |
| --------- | ------------------------------------------- | --------------------------- |
| `events` | Comma-separated event types to subscribe to | `created,updated,deleted` |
| `fields` | Comma-separated fields to include in events | All fields allowed for role |
### Permission Constraint Operators
> **Note:** The following operators are only available in permission constraint
> definitions (configured via the admin console or YAML import). They cannot be
> used in API query parameters.
| Operator | Description | Example |
| ------------------------ | ------------------------------------------ | --------------------------------- |
| `eq` | Equal | `status__eq=active` |
| `neq` | Not equal | `status__neq=draft` |
| `gt`, `gte` | Greater than (or equal) | `age__gte=18` |
| `lt`, `lte` | Less than (or equal) | `price__lt=100` |
| `in`, `nin` | In/not in array | `status__in=["active","pending"]` |
| `is_null`, `is_not_null` | Null check | `deleted_at__is_null=true` |
| `like`, `ilike` | Pattern match (case-sensitive/insensitive) | `name__ilike=%john%` |
| `regex`, `iregex` | Regular expression | `email__regex=.*@example\\.com` |
| `contains` | JSON contains | `tags__contains=["featured"]` |
| `has_key` | JSON has key | `metadata__has_key=published` |
| `exists`, `not_exists` | Relation exists | `author__exists=true` |
| `_and`, `_or`, `_not` | Logical operators | Complex nested conditions |
## Configuration
### Environment Variables
**Database:**
```bash
DATABASE_URL=postgresql://user:pass@localhost:5432/snaapi
```
**Authentication:**
```bash
BETTER_AUTH_URL=http://localhost:8000
SNAAPI_INSTALL_TOKEN=your-install-token-here
SNAAPI_DEFAULT_ROLE=user
ENABLE_EMAIL_PASSWORD_LOGIN=true
REQUIRE_EMAIL_VERIFICATION=false
```
**Application:**
```bash
APP_ENV=development # development | production
SNAAPI_AUTO_MIGRATE=true # Auto-run migrations on startup
SNAAPI_ENABLE_WORKER=true # Enable background job processing
SNAAPI_OPENAPI_PUBLIC=false # Serve OpenAPI specs without authentication
LOG_LEVEL=info # debug | info | warn | error
LOG_FORMAT=pretty # pretty | json
```
**Analytics (Optional):**
```bash
ANALYTICS_PROVIDER=prometheus # prometheus | deno_deploy
PROMETHEUS_URL=http://localhost:9090 # Prometheus server URL
TEMPO_URL=http://localhost:3200 # Tempo tracing URL
DENO_DEPLOY_TOKEN= # Deno Deploy access token (if using deno_deploy provider)
DENO_DEPLOY_PROJECT= # Deno Deploy project ID (if using deno_deploy provider)
```
**Observability (Optional):**
```bash
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
OTEL_SERVICE_NAME=snaapi
```
### Deno Tasks
```bash
deno task dev # Start development server with watch mode
deno task start # Start production server
deno task migrate # Run database migrations
deno task test # Run test suite
deno task test:watch # Run tests in watch mode (re-runs on file changes)
deno task test:integration # Run integration test suite
deno task ok # Run tests with coverage
deno task check # Format, lint, and typecheck in one command
deno task lint # Lint code
deno task fmt # Format code
```
## Use Cases
### Multi-Tenant SaaS Backend
Define resources with tenant_id constraints, use row-level security to isolate
data, and leverage JWT claims for automatic tenant filtering.
### Internal Admin Portals
Rapidly build admin tools for managing production data with full audit trails,
role-based access, and real-time monitoring.
### API Prototyping
Validate product ideas quickly by creating functional APIs in minutes, iterate
based on feedback, then migrate to production.
### Event-Driven Microservices
Use webhook subscriptions to trigger downstream services, leverage background
jobs for async processing, and maintain event sourcing.
### Mobile App Backends
Generate secure REST APIs for mobile apps with authentication, fine-grained
permissions, and offline-sync friendly endpoints.
### IoT Data Collection
Define sensor data resources, use API keys for device authentication, leverage
events for real-time monitoring and alerting.
## Security Best Practices
1. **Use API Keys for Service-to-Service**: Generate dedicated API keys for each
service with rate limits
2. **Enable Row-Level Security**: Use filters to restrict data access based on
user context
3. **Implement Field-Level Permissions**: Only expose necessary fields per role
4. **Use Auto-Injection for Ownership**: Automatically set owner_id using checks
with JWT claims
5. **Enable Email Verification**: Set `REQUIRE_EMAIL_VERIFICATION=true` for
production
6. **Rotate Installation Tokens**: Change after initial setup
7. **Monitor Event Logs**: Review audit trails regularly for suspicious activity
8. **Use HTTPS in Production**: Ensure `APP_ENV=production` for secure cookies
## Observability & Monitoring
### OpenTelemetry Integration
Snaapi includes built-in OpenTelemetry support for distributed tracing:
```bash
# Configure OTLP endpoint
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
OTEL_SERVICE_NAME=snaapi
```
**Trace Context Propagation:**
- All events include traceId, spanId, parentSpanId, requestId, correlationId
- Webhooks propagate trace context to downstream services
- Job executions linked to originating request traces
### Event Logging
Every resource operation generates detailed events:
- Event type (created, updated, deleted)
- Old and new state with field-level changes
- Session variables (userId, role, IP, userAgent)
- Timestamp and unique event ID
Access via Admin Console (`/console/events`) or query directly:
```bash
GET /v1/_events?resourceName__eq=users&eventType__eq=resource.updated
```
### Metrics & Statistics
Admin dashboard provides real-time statistics:
- Resource counts and usage
- User registrations and verifications
- Role and permission distribution
- Webhook delivery success rates
- Event volume by type
## Development
### Testing
```bash
# Run all tests
deno task test
# Run with coverage
deno task ok
# Run specific test file
deno test src/registry/fields_test.ts
```
### Contributing
Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit changes (`git commit -m 'Add amazing feature'`)
4. Push to branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## Performance Characteristics
- **Startup Time**: ~500ms (includes migrations if enabled)
- **Request Latency**: <10ms for simple CRUD operations
- **Database Connections**: Max 20 concurrent (configurable)
- **API Key Rate Limit**: 1000 requests/minute (configurable per key)
- **Event Processing**: Batches of 10 events, 5 concurrent jobs
- **Webhook Retries**: Exponential backoff up to 5 attempts
## License
This project is licensed under the
[GNU Affero General Public License v3.0 (AGPL-3.0)](LICENSE). See the LICENSE
file for full terms.
For enterprises requiring alternative licensing arrangements, commercial
dual-licensing options are available. Contact
[licensing@snaapi.dev](mailto:licensing@snaapi.dev) for details.
## Support
- **Documentation**:
[https://github.com/snaapi/snaapi](https://github.com/snaapi/snaapi)
- **Issues**: [GitHub Issues](https://github.com/snaapi/snaapi/issues)
- **Discussions**:
[GitHub Discussions](https://github.com/snaapi/snaapi/discussions)
## Acknowledgments
Built with:
- [Deno](https://deno.land/) - Modern JavaScript/TypeScript runtime
- [Fresh](https://fresh.deno.dev/) - Next-gen web framework
- [Better Auth](https://better-auth.com/) - Authentication library
- [PostgreSQL](https://www.postgresql.org/) - Reliable database
- [Preact](https://preactjs.com/) - Lightweight React alternative
- [Tailwind CSS](https://tailwindcss.com/) - Utility-first CSS framework
- [DaisyUI](https://daisyui.com) - Tailwind CSS component library
---
**Snaapi** - Build production APIs in minutes, not weeks.