Apistry CLI
The Apistry CLI (apistry) is the primary interface for running the Contract as a Service runtime locally, testing database connectivity, and performing utility operations on MongoDB collections.
Environment Configuration
The CLI loads environment variables from a .env file. By default it looks for .env in the current working directory. Use -e/--env <dir> to point to a directory that contains the .env file.
Required:
- DB_CONNECTION – MongoDB connection string including database name
Optional:
- LOG_LEVEL – debug | info | warn | error (default: info)
- ENABLE_AUTO_COLLECTION_CREATE – y | yes | true | n | no | false (default: n)
Example .env:
DB_CONNECTION=mongodb://localhost:27017/mydb
LOG_LEVEL=info
Commands
1. serve
Start the API development server from one or more OpenAPI contracts.
apistry serve -c path/to/contract.yaml
Options:
-c, --contract <string>(required) Path to the OpenAPI contract file (YAML or JSON). You can pass relative paths.-h, --host <string>Host interface to bind (default:localhost). Use0.0.0.0to allow external access.-p, --port <number>Port to listen on (default:3000).-ll, --logLevel <string>Log level (debug|info|warn|error) (default:info).-e, --env <string>Directory containing a.envfile.--enableAutoCollectionCreate <value>Automatically create missing MongoDB collections referenced by tags (y|yes|true|n|no|false, default:n).
Behavior:
- Loads environment variables.
- Validates
DB_CONNECTION. - Loads and merges the provided contract(s) (future multi-contract support).
- Validates that tagged MongoDB collections exist; prompts or auto-creates depending on
--enableAutoCollectionCreate. - Starts a Fastify server and registers Swagger UI at
/docs.
Startup Output (info level):
Loading Contract: contracts/dist-wip/cars.v1.yaml
✅ All required collections exist in database
📚 Swagger UI available at /docs
Loaded 14 routes successfully
🚀 Server running on http://localhost:3000
📖 API Documentation: http://localhost:3000/docs
Use --logLevel debug for detailed structured logs (request/response, validation traces).
Examples:
# Basic
apistry serve -c contracts/dist-wip/cars.v1.yaml
# Different host & port
apistry serve -c contracts/dist-wip/cars.v1.yaml -h 0.0.0.0 -p 8080
# Auto-create missing collections
apistry serve -c contracts/dist-wip/cars.v1.yaml --enableAutoCollectionCreate yes
# Custom env directory
apistry serve -c contracts/dist-wip/cars.v1.yaml -e ../..
Common Errors:
Missing DB_CONNECTION environment variable.– Provide.envor export the variable before running.Error starting server: <message>– Contract parsing or Fastify initialization failed.
2. testConnection
Validate connectivity to MongoDB defined by DB_CONNECTION.
apistry testConnection
Options:
-e, --env <string>Directory containing.env.
Behavior:
- Masks password in displayed connection string.
- Connects and performs a ping command.
- Prints database name extracted from URI.
Example Output:
🔍 Testing MongoDB connection...
📍 Connection string: mongodb://user:****@localhost:27017/mydb
⏳ Connecting to MongoDB...
✅ Success! You are connected to MongoDB!
📊 Pinged your deployment successfully.
📂 Database name: mydb
🔌 Connection closed.
Failure Example:
❌ Connection failed: authentication failed
3. clearCollection
Delete all documents from a specified MongoDB collection (with interactive confirmation).
apistry clearCollection -cn cars
Options:
-cn, --collectionName <string>(required) Name of the collection to clear (automatically lowercased).-e, --env <string>Directory containing.env.
Behavior:
- Counts documents.
- Prompts for confirmation.
- Deletes all documents if confirmed.
- Reports number deleted.
Example Output:
🔍 Clearing collection...
📍 Connection string: mongodb://user:****@localhost:27017/mydb
📁 Collection: cars
⏳ Connecting to MongoDB...
📊 Collection "cars" contains 42 document(s)
⚠️ Are you sure you want to delete all 42 document(s) from "cars"? (Y/n) Y
🗑️ Deleting all documents from collection...
✅ Successfully cleared collection "cars"
📊 Deleted 42 document(s)
🔌 Connection closed.
Cancellation:
❌ Operation cancelled.
4. import
Bulk load JSON or CSV fixtures into MongoDB collections. Useful for seeding development data or refreshing demo datasets.
apistry import -i assets/example-data --replace yes
Options:
-i, --inputPath <string>(required) Directory or explicit file containing JSON/CSV payloads.-r, --replace <string>Clear existing documents before loading (y|yes|true|n|no|false, default:n).-m, --maxDocs <integer>Upper bound on documents imported per file; omit to load all rows.-e, --env <string>Directory containing.env.
Behavior:
- Resolves files from
inputPath. Directories are traversed one level deep; each file name maps to the target collection. - When
--replaceis truthy, issues a deleteMany prior to load. - Parses JSON arrays or CSV headers, batching inserts to reduce memory use.
- Logs per-file counts and totals.
Example data:
Examples:
# Import a single JSON document list
apistry import -i assets/example-data/cars.json
# Seed all fixtures, wiping existing data first
apistry import -i assets/example-data --replace yes
# Smoke-test a subset
apistry import -i assets/example-data/videos.csv -m 25
5. export
Dump one or many MongoDB collections to JSON or CSV to share fixtures or snapshot state.
apistry export -o exports --collection cars --format csv
Options:
-o, --outputPath <string>(required) Directory or file path where exports are written. Directories are created if missing.-c, --collection <string>Name of a single collection to export. Omit to export every collection referenced in the current contract.-f, --format <string>Output format:json(default) orcsv.-e, --env <string>Directory containing.env.
Behavior:
- Establishes a Mongo connection using
DB_CONNECTION. - Determines the export scope: specified collection or contract-derived set.
- Streams documents to the requested format to prevent memory spikes.
- Writes one file per collection (e.g.,
cars.json,cars.csv).
Examples:
# Capture a single collection
apistry export -c cars -o dumps
# Export all collections in CSV for spreadsheets
apistry export -o dumps/csv --format csv
# Direct export to a file path
apistry export -c videos -o /tmp/videos.json
Logging Modes
Logging is optimized for readability at info and detail at debug.
info: Minimal human-friendly messages (each on its own line).debug: Includes timestamps, levels, and structured objects (requests, validation details, error stacks).
Set via environment or CLI option:
LOG_LEVEL=debug apistry serve -c contracts/dist-wip/cars.v1.yaml
# or
apistry serve -c contracts/dist-wip/cars.v1.yaml -ll debug
Auto-Collection Creation
When starting the server the tag names in the OpenAPI contract are treated as collection names. If collections are missing you can:
- Be prompted (default behavior)
- Auto-create with --enableAutoCollectionCreate yes
See detailed flow in collection-auto-creation.md.
Security & Safety
- Connection string masking hides the password portion in CLI output.
- Validation errors are summarized; full detail only in
debugmode. - Clear operations require explicit confirmation.
Troubleshooting
| Symptom | Possible Cause | Resolution |
|---|---|---|
Missing DB_CONNECTION |
.env not found or variable unset |
Create .env or export variable |
| Server starts but no routes loaded | Contract path incorrect | Verify -c path exists |
authentication failed during testConnection |
Wrong credentials / authSource | Update connection string with correct user/password and database |
| Logs are one long line | Old config caching / terminal quirk | Restart shell; ensure singleLine disabled |
Swagger not available at /docs |
Plugin load failure | Run with -ll debug and inspect error output |
Help
Show global help:
apistry --help
Show command-specific help:
apistry serve --help
apistry testConnection --help
apistry clearCollection --help
apistry import --help
apistry export --help
Next: Explore the generated API via the Swagger UI at /docs after running serve.