Generate OpenAPI 3.1 specifications from Supabase projects with RLS policy introspection, RPC mapping, and Edge Function integration
npm install @safetyscope/supabase-openapi-generatorGenerate OpenAPI 3.1 specifications from your Supabase database schema with complete RLS policy introspection, RPC function mapping, and Edge Function integration.


⨠Complete Schema Introspection
- Tables, columns, views, and enums
- Foreign key relationships
- Primary keys and constraints
- PostgreSQL-specific types (arrays, JSON, ranges, etc.)
š RLS Policy Analysis
- Automatic policy parsing and categorization
- Permission matrix generation
- Complex policy detection
- Security audit reporting
šÆ RPC Function Mapping
- Function parameter introspection
- Return type mapping
- Volatility and security definer attributes
- Comment-based descriptions
ā” Edge Function Integration
- Static code analysis
- TypeScript interface extraction
- JWT authentication detection
- Request/response schema generation
ā
OpenAPI 3.1 Validation
- Structural validation with Ajv
- Reference checking
- Path and schema validation
- Best practices verification
``bash`
npm install -g @safetyscope/supabase-openapi-generator
Or use without installation:
`bash`
npx @safetyscope/supabase-openapi-generator
Before generating your OpenAPI spec, learn how to properly document your Supabase project:
`bash`
npx @safetyscope/supabase-openapi-generator guide
Get detailed guidance for specific topics:
`bashEdge Functions documentation guide
npx @safetyscope/supabase-openapi-generator guide edge-functions
$3
Run the CLI and follow the prompts:
`bash
npx @safetyscope/supabase-openapi-generator
`You'll be asked for:
1. Database URL - Your Supabase PostgreSQL connection string (required)
2. Project URL - Your Supabase project URL (optional, for reference)
3. Schema Selection - Which schemas to include (default:
public)
4. Table Selection - Include/exclude specific tables
5. RPC Functions - Include/exclude specific functions
6. Edge Functions - Optionally include Edge Functions
7. Output Options - Format (YAML/JSON) and file path$3
Save a configuration file for repeated use:
`yaml
supabase-openapi.config.yaml
supabase:
databaseUrl: postgresql://postgres:password@db.project.supabase.co:5432/postgresscope:
schemas:
- public
tables:
- users
- posts
- comments
rpcFunctions:
- get_user_posts
- create_post
output:
path: ./openapi.yaml
format: yaml
generateAuditReport: true
auditReportPath: ./security-audit.md
`Run with config file:
`bash
npx @safetyscope/supabase-openapi-generator --config ./supabase-openapi.config.yaml
`Command Line Options
$3
`
Usage: supabase-openapi generate [options]Generate OpenAPI specification
Options:
-c, --config Load configuration from file
-o, --output Output file path
-f, --format Output format (yaml or json) (default: "yaml")
-v, --verbose Enable verbose output
--skip-prompts Skip interactive prompts (requires config file)
-h, --help Display help for command
`$3
`
Usage: supabase-openapi guide [topic]Display preparation guides for documenting your Supabase project
Topics:
edge-functions Document Edge Functions with full input/output
database Prepare database tables and views
rpc Document RPC (database) functions
rls Row Level Security policies
`Examples:
`bash
Display main guide menu
npx @safetyscope/supabase-openapi-generator guideShow Edge Functions guide
npx @safetyscope/supabase-openapi-generator guide edge-functionsShow database documentation guide
npx @safetyscope/supabase-openapi-generator guide database
`The guide command provides:
- ā
Step-by-step preparation instructions
- š Code examples with best practices
- ā Checklists for complete documentation
- š” Tips for automatic detection
- ā Common mistakes to avoid
Database Connection
Important: This tool connects directly to your PostgreSQL database to introspect the schema. It does not use Supabase API keys (publishable/secret keys).
$3
For local Supabase instances:
`bash
postgresql://postgres:postgres@127.0.0.1:54322/postgres
`$3
Get your connection string from the Supabase dashboard:
1. Go to Settings ā Database
2. Find Connection string section
3. Use the URI format (not "Connection pooler")
4. Copy the connection string and replace
[YOUR-PASSWORD] with your actual database passwordNote:
- The direct database connection string includes your database password, not your API keys
- If you see "Publishable" or "Secret" keys in your dashboard, those are for API access - this tool doesn't use them
- For local development with
supabase start, the connection string is shown in the "Database" sectionGenerated OpenAPI Features
$3
For each selected table, the generator creates:
- GET
/rest/v1/{table} - List records with query parameters
- POST /rest/v1/{table} - Create new record
- PATCH /rest/v1/{table} - Update records
- DELETE /rest/v1/{table} - Delete records
- GET /rest/v1/{table}?select=* - Get single record by ID$3
Functions are mapped to:
`yaml
/rpc/v1/function_name:
post:
operationId: rpcFunctionName
requestBody:
content:
application/json:
schema:
properties:
param1: { type: string }
param2: { type: integer }
`$3
Each operation includes Supabase-specific extensions:
`yaml
x-supabase-rls:
enabled: true
select:
allowed_roles: [authenticated]
condition: "auth.uid() = user_id"
is_complex: false
`$3
Edge Functions are documented with:
`yaml
/functions/v1/function-name:
post:
x-supabase-edge-function:
name: function-name
verifyJwt: true
requestBody:
content:
application/json:
schema:
# Extracted from TypeScript interfaces
`Security Audit Report
When
generateAuditReport is enabled, a markdown report is generated with:- Tables without RLS enabled
- Complex policies requiring review
- Overly permissive configurations
- Recommended security improvements
Example audit report output:
`markdown
Security Audit Report
Tables Without RLS
-
public.analytics - Consider enabling RLS if this table contains user dataComplex Policies Detected
$3
- Expression: (auth.uid() = owner_id) OR (status = 'published' AND created_at > now() - interval '7 days')
- Review Recommendation: Consider simplifying or documenting this policyRecommendations
1. Enable RLS on all tables containing user data
2. Review and simplify complex policies
3. Document custom policy logic
`Type Mapping
PostgreSQL types are automatically mapped to OpenAPI/JSON Schema types:
| PostgreSQL | OpenAPI | Format |
|------------|---------|--------|
|
integer, int4 | integer | int32 |
| bigint, int8 | integer | int64 |
| text, varchar | string | - |
| boolean | boolean | - |
| uuid | string | uuid |
| timestamp, timestamptz | string | date-time |
| date | string | date |
| json, jsonb | object | - |
| array types | array | - |
| Custom enums | string with enum | - |Unknown or custom types are mapped to
string with the original PostgreSQL type preserved in x-postgres-type.Edge Cases Handled
$3
- Empty schemas (no tables)
- Reserved word identifiers
- Circular foreign key references
- Tables with no columns$3
- Tables with RLS enabled but no policies
- NULL policy expressions
- Overly permissive policies (true conditions)
- Complex policies with subqueries$3
- Domain types
- Composite types
- Range and multirange types
- Extension types (ltree, hstore, etc.)All edge cases are logged with warnings during generation.
Troubleshooting
$3
Error:
Authentication failed: Invalid username or password
- Verify your database credentials
- Check that you're using the direct database password, not API keysError:
Connection refused: Database server is not accepting connections
- Ensure your database is running
- Check firewall/network settings
- Verify the hostname and port are correctError:
Database does not exist
- Check the database name in your connection string
- Verify you have access to the specified database$3
Error:
column p.proisagg does not exist
- Your PostgreSQL version is older than 11
- Update PostgreSQL or use a newer Supabase instanceError:
No tables found in schemas
- Verify the schema names are correct
- Check that tables exist in the specified schemas
- Ensure you have SELECT permissions$3
Error:
syntax error near unexpected token or import: unable to open X server
- This occurs when the npm package is installed incorrectly or cached
- Solution: Clear npm cache and reinstall:
`bash
npm uninstall -g @safetyscope/supabase-openapi-generator
npm cache clean --force
npm install -g @safetyscope/supabase-openapi-generator
`
- If the issue persists, use npx instead: npx @safetyscope/supabase-openapi-generator$3
If the generated spec has validation errors:
1. Check the error messages for specific issues
2. Review complex policies that may not parse correctly
3. Verify custom types are properly defined
4. Check for circular references in schemas
Use Cases
$3
Use with Swagger UI or Redoc:
`bash
Generate spec
npx @safetyscope/supabase-openapi-generator -o openapi.yamlServe with Redoc
npx @redocly/cli preview-docs openapi.yaml
`$3
Use with OpenAPI Generator:
`bash
Generate TypeScript client
openapi-generator-cli generate \
-i openapi.yaml \
-g typescript-axios \
-o ./src/clientGenerate Python client
openapi-generator-cli generate \
-i openapi.yaml \
-g python \
-o ./client
`$3
1. Generate OpenAPI spec
2. Import into your API testing tool
3. Test endpoints with pre-populated schemas
$3
Use the generated spec for API contract testing to ensure your backend matches the documentation.
Configuration Reference
$3
`yaml
supabase:
# Direct database URL (required)
databaseUrl: string
# Optional: Supabase project URL for reference
projectUrl: string # e.g., https://xxxxx.supabase.coscope:
# Schemas to introspect (default: ['public'])
schemas: string[]
# Tables to include (empty = all)
tables: string[]
# Tables to exclude
excludeTables: string[]
# RPC functions to include (empty = all)
rpcFunctions: string[]
# RPC functions to exclude
excludeRpcFunctions: string[]
edgeFunctions:
# Enable Edge Function introspection
enabled: boolean
# List of Edge Functions
functions:
- name: string
path: string
entryFile: string
verifyJwt: boolean
files:
- name: string
content: string
output:
# Output file path
path: string
# Format: yaml or json
format: 'yaml' | 'json'
# Generate security audit report
generateAuditReport: boolean
# Audit report output path
auditReportPath: string
# OpenAPI info section
title: string
version: string
description: string
``Contributions are welcome! Please feel free to submit a Pull Request.
MIT License - see LICENSE file for details
- Supabase - Open source Firebase alternative
- PostgREST - REST API for PostgreSQL
- OpenAPI Specification - OpenAPI 3.1
- š Documentation
- š Issue Tracker
- š¬ Discussions
---
Built with ā¤ļø for the Supabase community