# Add an action to the application Source: https://docs.withsutro.com/api-reference/actions-effects/add-an-action-to-the-application /openapi.yaml post /applications/{applicationId}/actions # Get a list of Actions from an application Source: https://docs.withsutro.com/api-reference/actions-effects/get-a-list-of-actions-from-an-application /openapi.yaml get /applications/{applicationId}/actions # Get Action Effects Source: https://docs.withsutro.com/api-reference/actions-effects/get-action-effects /openapi.yaml get /applications/{applicationId}/actions/{actionId}/effects # Get an action from the Application Source: https://docs.withsutro.com/api-reference/actions-effects/get-an-action-from-the-application /openapi.yaml get /applications/{applicationId}/actions/{actionId} # Get an effect from an Action in the Application Source: https://docs.withsutro.com/api-reference/actions-effects/get-an-effect-from-an-action-in-the-application /openapi.yaml get /applications/{applicationId}/actions/{actionId}/effects/{effectId} # Modify Action Effects Source: https://docs.withsutro.com/api-reference/actions-effects/modify-action-effects /openapi.yaml post /applications/{applicationId}/actions/{actionId}/effects # Remove an action from the Application Source: https://docs.withsutro.com/api-reference/actions-effects/remove-an-action-from-the-application /openapi.yaml delete /applications/{applicationId}/actions/{actionId} # Remove an effect from an Action in the Application Source: https://docs.withsutro.com/api-reference/actions-effects/remove-an-effect-from-an-action-in-the-application /openapi.yaml delete /applications/{applicationId}/actions/{actionId}/effects/{effectId} # Update an action in the Application Source: https://docs.withsutro.com/api-reference/actions-effects/update-an-action-in-the-application /openapi.yaml patch /applications/{applicationId}/actions/{actionId} # Update an Effect in an Action Source: https://docs.withsutro.com/api-reference/actions-effects/update-an-effect-in-an-action /openapi.yaml patch /applications/{applicationId}/actions/{actionId}/effects/{effectId} # Delete a message Source: https://docs.withsutro.com/api-reference/ai-assistant/delete-a-message /openapi.yaml delete /projects/{projectId}/messages/{messageId} Soft deletes a message by setting its deleted_at timestamp # Get a specific message Source: https://docs.withsutro.com/api-reference/ai-assistant/get-a-specific-message /openapi.yaml get /projects/{projectId}/messages/{messageId} # Get all messages for a project Source: https://docs.withsutro.com/api-reference/ai-assistant/get-all-messages-for-a-project /openapi.yaml get /projects/{projectId}/messages # Send a message to the assistant Source: https://docs.withsutro.com/api-reference/ai-assistant/send-a-message-to-the-assistant /openapi.yaml post /projects/{projectId}/messages Sends a user message to the assistant, which will process it asynchronously and may trigger changes to the application. The user message is stored in the conversation history. The response includes a job ID for tracking the processing status. The components that can be modified (frontend, backend, or both) are determined by the project's components configuration set at project creation. This cannot be overridden. # Create a new API Client Source: https://docs.withsutro.com/api-reference/api_clients/create-a-new-api-client /uapi.yaml post /api_clients # Delete an API Client Source: https://docs.withsutro.com/api-reference/api_clients/delete-an-api-client /uapi.yaml delete /api_clients/{apiClientId} # Get a list of API Clients Source: https://docs.withsutro.com/api-reference/api_clients/get-a-list-of-api-clients /uapi.yaml get /api_clients Returns a list of all of the API Clients defined for a Customer # Get an API Client Source: https://docs.withsutro.com/api-reference/api_clients/get-an-api-client /uapi.yaml get /api_clients/{apiClientId} # Remove the mTLS certificate from an API Client Source: https://docs.withsutro.com/api-reference/api_clients/remove-the-mtls-certificate-from-an-api-client /uapi.yaml delete /api_clients/{apiClientId}/certificate # Set the mTLS certificate for an API Client Source: https://docs.withsutro.com/api-reference/api_clients/set-the-mtls-certificate-for-an-api-client /uapi.yaml post /api_clients/{apiClientId}/certificate # Create a new application Source: https://docs.withsutro.com/api-reference/applications/create-a-new-application /openapi.yaml post /projects/{projectId}/applications # Create a new version of this Application. Source: https://docs.withsutro.com/api-reference/applications/create-a-new-version-of-this-application /openapi.yaml post /applications/{applicationId}/versions This approach generates a new version based on the previous version # Delete an application Source: https://docs.withsutro.com/api-reference/applications/delete-an-application /openapi.yaml delete /applications/{applicationId} # Edit an application using natural language Source: https://docs.withsutro.com/api-reference/applications/edit-an-application-using-natural-language /openapi.yaml post /applications/{applicationId}/slang-edit # Generate Application Source: https://docs.withsutro.com/api-reference/applications/generate-application /openapi.yaml post /applications/{applicationId}/generate Generates the application code for the specified application. The components generated (frontend, backend, or both) are determined by the project's components configuration set at project creation. This cannot be overridden. The application must already exist before calling this endpoint. # Get an application by ID Source: https://docs.withsutro.com/api-reference/applications/get-an-application-by-id /openapi.yaml get /applications/{applicationId} # Get CORS configuration Source: https://docs.withsutro.com/api-reference/applications/get-cors-configuration /openapi.yaml get /applications/{applicationId}/cors Returns the current CORS configuration for the application's backend API. # Get information about a specific version of an application Source: https://docs.withsutro.com/api-reference/applications/get-information-about-a-specific-version-of-an-application /openapi.yaml get /applications/{applicationId}/versions/{version} # Get the OpenAPI spec for an application Source: https://docs.withsutro.com/api-reference/applications/get-the-openapi-spec-for-an-application /openapi.yaml get /applications/{applicationId}/openapi # Gets the current status of the Application Source: https://docs.withsutro.com/api-reference/applications/gets-the-current-status-of-the-application /openapi.yaml get /applications/{applicationId}/status # List application versions Source: https://docs.withsutro.com/api-reference/applications/list-application-versions /openapi.yaml get /applications/{applicationId}/versions # List applications for a project Source: https://docs.withsutro.com/api-reference/applications/list-applications-for-a-project /openapi.yaml get /projects/{projectId}/applications # List applications for the authenticated customer Source: https://docs.withsutro.com/api-reference/applications/list-applications-for-the-authenticated-customer /openapi.yaml get /applications # Publish an application Source: https://docs.withsutro.com/api-reference/applications/publish-an-application /openapi.yaml post /applications/{applicationId}/publish # Unpublish an application Source: https://docs.withsutro.com/api-reference/applications/unpublish-an-application /openapi.yaml post /applications/{applicationId}/unpublish # Update an application through SLang Source: https://docs.withsutro.com/api-reference/applications/update-an-application-through-slang /openapi.yaml put /applications/{applicationId}/slang Compiles SLang into SCode and updates the application. # Update an application's SCode Source: https://docs.withsutro.com/api-reference/applications/update-an-applications-scode /openapi.yaml put /applications/{applicationId}/scode Accepts a JSON SCode object only. # Update CORS configuration Source: https://docs.withsutro.com/api-reference/applications/update-cors-configuration /openapi.yaml patch /applications/{applicationId}/cors Updates the CORS configuration for the application's backend API. This is required when self-hosting the frontend to allow cross-origin requests. # Attach a file Source: https://docs.withsutro.com/api-reference/attachments/attach-a-file /openapi.yaml post /applications/{applicationId}/attachments # Attach an uploaded file to a project Source: https://docs.withsutro.com/api-reference/attachments/attach-an-uploaded-file-to-a-project /openapi.yaml post /projects/{projectId}/file # Create a project attachment Source: https://docs.withsutro.com/api-reference/attachments/create-a-project-attachment /openapi.yaml post /projects/{projectId}/attachments # Get an attachment by ID Source: https://docs.withsutro.com/api-reference/attachments/get-an-attachment-by-id /openapi.yaml get /attachments/{attachmentId} # List Application's Attachments Source: https://docs.withsutro.com/api-reference/attachments/list-applications-attachments /openapi.yaml get /applications/{applicationId}/attachments # List project attachments Source: https://docs.withsutro.com/api-reference/attachments/list-project-attachments /openapi.yaml get /projects/{projectId}/attachments # Remove an attachment from a Project Source: https://docs.withsutro.com/api-reference/attachments/remove-an-attachment-from-a-project /openapi.yaml delete /attachments/{attachmentId} # Add a new Builder user Source: https://docs.withsutro.com/api-reference/builders/add-a-new-builder-user /uapi.yaml post /builders # Create a new builder Source: https://docs.withsutro.com/api-reference/builders/create-a-new-builder /openapi.yaml post /builders # Delete a builder Source: https://docs.withsutro.com/api-reference/builders/delete-a-builder /openapi.yaml delete /builders/{builderId} # Get a builder by ID Source: https://docs.withsutro.com/api-reference/builders/get-a-builder-by-id /openapi.yaml get /builders/{builderId} # Get a list of Builder users Source: https://docs.withsutro.com/api-reference/builders/get-a-list-of-builder-users /uapi.yaml get /builders Returns a list of all of the Builder users defined for a Customer # Get info about a Builder Source: https://docs.withsutro.com/api-reference/builders/get-info-about-a-builder /uapi.yaml get /builders/{builderId} # List all builders for the authenticated customer Source: https://docs.withsutro.com/api-reference/builders/list-all-builders-for-the-authenticated-customer /openapi.yaml get /builders # Remove a Builder from the system Source: https://docs.withsutro.com/api-reference/builders/remove-a-builder-from-the-system /uapi.yaml delete /builders/{builderId} # Add an accepted token issuer Source: https://docs.withsutro.com/api-reference/certificates/add-an-accepted-token-issuer /uapi.yaml post /config/issuers # Batch unassign JWT issuers from a certificate Source: https://docs.withsutro.com/api-reference/certificates/batch-unassign-jwt-issuers-from-a-certificate /uapi.yaml delete /certs/{certificateId}/issuers Unassigns multiple JWT issuers from a certificate in a single batch operation. Validates that all issuer IDs exist and belong to the customer before performing unassignment. Only unassigns issuers that currently have this specific certificate assigned. # Delete a Certificate Source: https://docs.withsutro.com/api-reference/certificates/delete-a-certificate /uapi.yaml delete /certs/{certificateId} Deletes a certificate and automatically unassigns it from any API clients and JWT issuers. This is a soft delete operation. # Download the Sutro root CA certificate Source: https://docs.withsutro.com/api-reference/certificates/download-the-sutro-root-ca-certificate /uapi.yaml get /certs/ca.crt Downloads the PEM-encoded Sutro root CA certificate. This certificate can be used to verify certificates issued by Sutro. # Get a list of current Certificates Source: https://docs.withsutro.com/api-reference/certificates/get-a-list-of-current-certificates /uapi.yaml get /certs # Get the list of accepted token issuers Source: https://docs.withsutro.com/api-reference/certificates/get-the-list-of-accepted-token-issuers /uapi.yaml get /config/issuers # Remove an accepted token issuer Source: https://docs.withsutro.com/api-reference/certificates/remove-an-accepted-token-issuer /uapi.yaml delete /config/issuers/{issuerId} # Request a certificate Source: https://docs.withsutro.com/api-reference/certificates/request-a-certificate /uapi.yaml post /certs/request # Set the Certificate used for verifying tokens from the Customer Source: https://docs.withsutro.com/api-reference/certificates/set-the-certificate-used-for-verifying-tokens-from-the-customer /uapi.yaml post /config/token_certs/{issuerId} # Perform initial setup of platform for your organization Source: https://docs.withsutro.com/api-reference/configuration/perform-initial-setup-of-platform-for-your-organization /uapi.yaml post /initialization # Add a field to a model in the Application Source: https://docs.withsutro.com/api-reference/data-models/add-a-field-to-a-model-in-the-application /openapi.yaml post /applications/{applicationId}/models/{modelId}/fields # Add a model to the application Source: https://docs.withsutro.com/api-reference/data-models/add-a-model-to-the-application /openapi.yaml post /applications/{applicationId}/models # Get a model from the Application Source: https://docs.withsutro.com/api-reference/data-models/get-a-model-from-the-application /openapi.yaml get /applications/{applicationId}/models/{modelId} # Get all models for an application Source: https://docs.withsutro.com/api-reference/data-models/get-all-models-for-an-application /openapi.yaml get /applications/{applicationId}/models # Join two models with a bidirectional relationship Source: https://docs.withsutro.com/api-reference/data-models/join-two-models-with-a-bidirectional-relationship /openapi.yaml post /applications/{applicationId}/models/join Creates a bidirectional relationship between two models in the application. The relationship type (one-to-one, one-to-many, or many-to-many) determines how records in the two models are associated. # Remove a field from a model in the Application Source: https://docs.withsutro.com/api-reference/data-models/remove-a-field-from-a-model-in-the-application /openapi.yaml delete /applications/{applicationId}/models/{modelId}/fields/{fieldId} # Remove a model from the Application Source: https://docs.withsutro.com/api-reference/data-models/remove-a-model-from-the-application /openapi.yaml delete /applications/{applicationId}/models/{modelId} # Update a field in a model in the Application Source: https://docs.withsutro.com/api-reference/data-models/update-a-field-in-a-model-in-the-application /openapi.yaml patch /applications/{applicationId}/models/{modelId}/fields/{fieldId} # Update a model in the Application Source: https://docs.withsutro.com/api-reference/data-models/update-a-model-in-the-application /openapi.yaml patch /applications/{applicationId}/models/{modelId} # Download frontend bundle Source: https://docs.withsutro.com/api-reference/deployments-assets/download-frontend-bundle /openapi.yaml get /applications/{applicationId}/frontendBundle Downloads a static zip bundle containing the built frontend assets. # Download web bundle (static files) for an application Source: https://docs.withsutro.com/api-reference/figma-integration/download-web-bundle-static-files-for-an-application /openapi.yaml get /applications/{applicationId}/webBundle Downloads a zip bundle containing all Figma-generated static files (HTML, CSS, images, etc.) for this application. This endpoint returns 200 with the zip file when the application status is Active, or 404 if the generation has not completed yet. Check GET /applications/{applicationId}/status to monitor generation progress. # Generate static code from a Figma frame for an application Source: https://docs.withsutro.com/api-reference/figma-integration/generate-static-code-from-a-figma-frame-for-an-application /openapi.yaml post /applications/{applicationId}/figma/generate-static-code Enqueues a job to generate static HTML/CSS code from a Figma frame for this application. This is an async operation - use GET /applications/{applicationId}/status to check the generation status, and GET /applications/{applicationId}/webBundle to download the result when ready. # Get Figma file structure (pages and frames) for an application Source: https://docs.withsutro.com/api-reference/figma-integration/get-figma-file-structure-pages-and-frames-for-an-application /openapi.yaml get /applications/{applicationId}/figma/structure Retrieves the structure of a Figma file including all pages and frames. Useful for letting users select which frame to generate code from. # Accept an invitation Source: https://docs.withsutro.com/api-reference/members/accept-an-invitation /uapi.yaml post /invitations/accept # Delete an invitation to a Member Source: https://docs.withsutro.com/api-reference/members/delete-an-invitation-to-a-member /uapi.yaml delete /invitations/{invitationId} # Get a list of Members Source: https://docs.withsutro.com/api-reference/members/get-a-list-of-members /uapi.yaml get /members Returns a list of all of the Members defined for a Customer # Get a list of pending invitations Source: https://docs.withsutro.com/api-reference/members/get-a-list-of-pending-invitations /uapi.yaml get /invitations # Resend an invitation to a Member Source: https://docs.withsutro.com/api-reference/members/resend-an-invitation-to-a-member /uapi.yaml post /invitations/{invitationId} # Reset a Member password by email with a reset token Source: https://docs.withsutro.com/api-reference/members/reset-a-member-password-by-email-with-a-reset-token /uapi.yaml post /members/password-reset # Reset a Member password with a reset token Source: https://docs.withsutro.com/api-reference/members/reset-a-member-password-with-a-reset-token /uapi.yaml post /members/{memberId}/password-reset # Send a password reset email Source: https://docs.withsutro.com/api-reference/members/send-a-password-reset-email /uapi.yaml post /members/{memberId}/password # Send a password reset email Source: https://docs.withsutro.com/api-reference/members/send-a-password-reset-email-1 /uapi.yaml post /members/password # Send invitations to Members Source: https://docs.withsutro.com/api-reference/members/send-invitations-to-members /uapi.yaml post /invitations Sends invitation emails to one or more new Members. # Update the current Member Source: https://docs.withsutro.com/api-reference/members/update-the-current-member /uapi.yaml put /members/current # Test API connectivity Source: https://docs.withsutro.com/api-reference/onboarding/test-api-connectivity /openapi.yaml get /hello Test endpoint to verify API connection and display builder info. Requires authentication but no specific permission. # Add a member to a project Source: https://docs.withsutro.com/api-reference/projects/add-a-member-to-a-project /openapi.yaml put /projects/{projectId}/members/{memberId} # Create a new project Source: https://docs.withsutro.com/api-reference/projects/create-a-new-project /openapi.yaml post /projects # Delete a project Source: https://docs.withsutro.com/api-reference/projects/delete-a-project /openapi.yaml delete /projects/{projectId} # Get a list of projects Source: https://docs.withsutro.com/api-reference/projects/get-a-list-of-projects /openapi.yaml get /projects # Get a list of projects with member counts Source: https://docs.withsutro.com/api-reference/projects/get-a-list-of-projects-with-member-counts /openapi.yaml get /projects/members # Get details about a specific project Source: https://docs.withsutro.com/api-reference/projects/get-details-about-a-specific-project /openapi.yaml get /projects/{projectId} # Get members of a project Source: https://docs.withsutro.com/api-reference/projects/get-members-of-a-project /openapi.yaml get /projects/{projectId}/members # Remove a member from a project Source: https://docs.withsutro.com/api-reference/projects/remove-a-member-from-a-project /openapi.yaml delete /projects/{projectId}/members/{memberId} # Update a project's name Source: https://docs.withsutro.com/api-reference/projects/update-a-projects-name /openapi.yaml patch /projects/{projectId} # Add a secret to the application Source: https://docs.withsutro.com/api-reference/secrets-configuration/add-a-secret-to-the-application /openapi.yaml post /applications/{applicationId}/secrets # List secrets in the application Source: https://docs.withsutro.com/api-reference/secrets-configuration/list-secrets-in-the-application /openapi.yaml get /applications/{applicationId}/secrets # Remove a secret from the Application Source: https://docs.withsutro.com/api-reference/secrets-configuration/remove-a-secret-from-the-application /openapi.yaml delete /applications/{applicationId}/secrets/{secretName} # Update a secret in the Application Source: https://docs.withsutro.com/api-reference/secrets-configuration/update-a-secret-in-the-application /openapi.yaml post /applications/{applicationId}/secrets/{secretName} # Check if a file exists Source: https://docs.withsutro.com/api-reference/storage/check-if-a-file-exists /openapi.yaml get /storage/files/{id}/exists Check whether a stored file exists by its ID. # Download a file Source: https://docs.withsutro.com/api-reference/storage/download-a-file /openapi.yaml get /storage/files/{id}/download Download a stored file by its ID. Returns the file as a binary stream with Content-Type, Content-Disposition, and Content-Length headers. # Get file metadata Source: https://docs.withsutro.com/api-reference/storage/get-file-metadata /openapi.yaml get /storage/files/{id} Retrieve metadata for a stored file without downloading it. # Upload a file Source: https://docs.withsutro.com/api-reference/storage/upload-a-file /openapi.yaml post /storage/files Upload a file to object storage. The file is associated with the authenticated customer and can optionally be linked to a builder. # Add a trigger to the application Source: https://docs.withsutro.com/api-reference/triggers/add-a-trigger-to-the-application /openapi.yaml post /applications/{applicationId}/triggers Adds a Trigger mapping to the Application. # Get a trigger from the Application Source: https://docs.withsutro.com/api-reference/triggers/get-a-trigger-from-the-application /openapi.yaml get /applications/{applicationId}/triggers/{triggerId} # List triggers in the application Source: https://docs.withsutro.com/api-reference/triggers/list-triggers-in-the-application /openapi.yaml get /applications/{applicationId}/triggers # Remove a trigger from the Application Source: https://docs.withsutro.com/api-reference/triggers/remove-a-trigger-from-the-application /openapi.yaml delete /applications/{applicationId}/triggers/{triggerId} # Update a trigger in the Application Source: https://docs.withsutro.com/api-reference/triggers/update-a-trigger-in-the-application /openapi.yaml patch /applications/{applicationId}/triggers/{triggerId} Updates a trigger in the Application. Accepts a partial TriggerMapping object. # Data Modeling Source: https://docs.withsutro.com/docs/SLang/data-modeling Define persisted entities, reusable schemas, enums, fields, and relations in SLang. SLang models backend data with two complementary constructs: * `entity` defines persisted database records. * `schema` defines reusable structured values that are not stored as their own table. Use entities for durable resources such as users, orders, documents, memberships, and tasks. Use schemas for request bodies, response shapes, nested values, and structured values that actions pass around. ## Entities An entity becomes a database-backed model. Fields are declared under `fields`, and relations are declared separately so both sides of a relationship are visible. ```slang theme={null} enum TaskStatus values todo in_progress done entity User description "Authenticated application user." subject identity email fields email: EMAIL description "Login email address." displayName: TEXT? entity Task description "A task owned by a user." fields title: TEXT minLength 1 status: TaskStatus := "todo" dueDate: DATE? relation User[tasks] 1 --- 0..* Task[owner] description "Each task belongs to one user." ``` ## Field Types Persisted fields support these SLang types: | Type | Use | | ----------------- | ------------------------------------------------------- | | `TEXT` | General strings. | | `EMAIL` | Email-shaped strings; commonly used as identity fields. | | `PHONE_NUMBER` | Phone numbers. | | `ADDRESS` | Postal address text. | | `NUMBER` | Integer or decimal numbers. | | `CURRENCY_AMOUNT` | Currency amount strings. | | `BOOLEAN` | `true` or `false`. | | `DATE` | Calendar dates. | | `TIME` | Time values. | | `DATE_TIME` | Timestamps. | | `URL` | Web links. | | `FILE` | Uploaded or stored document/blob values. | | `ENUM("a", "b")` | Inline string enum. | | `SomeEnum` | Named enum declared with `enum`. | Append `?` to make a field optional. Use `:=` for static defaults. ## Field Metadata Common field metadata includes: * `description "..."` for generated docs and editor context. * `minLength 1` for minimum text length. * `computed ` for computed fields. Defaults must be static values such as strings, numbers, booleans, objects, arrays, or `null`. ## Schemas Schemas use the same `fields` shape as entities, but they are structural types, not persisted database tables. Schemas can reference other schemas, including arrays of schemas. ```slang theme={null} schema Address description "A mailing address." fields street: TEXT city: TEXT postalCode: TEXT schema LineItem fields productName: TEXT quantity: NUMBER unitPrice: CURRENCY_AMOUNT schema OrderSummary fields orderNumber: TEXT shipping: Address items: [LineItem] totalAmount: CURRENCY_AMOUNT action BuildOrderSummary(orderNumber: TEXT, city: TEXT): OrderSummary body return { orderNumber := orderNumber shipping := { street := "1 Main St" city := city postalCode := "94105" } items := [] totalAmount := 0 } ``` ## Relations Relations connect entities and add relation fields to both sides. The general shape is: `relation Left[leftField] cardinality --- cardinality Right[rightField]` For example, `relation User[tasks] 1 --- 0..* Task[owner]` means: * `user.tasks` resolves to a list of tasks. * `task.owner` resolves to the owning user. * Creating or updating a `Task` can assign `owner := someUser` or `owner := @subject` when the field points to the subject entity. Use explicit join entities for many-to-many relationships when the relationship carries its own data, such as a membership role. # Files & Document Storage Source: https://docs.withsutro.com/docs/SLang/files-and-storage Accept uploads, persist files, store file metadata, and pass documents to AI. SLang represents uploaded and stored files with the `FILE` type. A `FILE` value carries file metadata and can be streamed, stored, downloaded, or passed to modules such as `AI.prompt`. ## Upload and Store a File HTTP file uploads are exposed through `@request.files.`. Use `store fileValue` to persist the upload to Sutro object storage before saving it on an entity. ```slang theme={null} import "AI" entity User subject identity email fields email: EMAIL displayName: TEXT? entity Document fields title: TEXT file: FILE summary: TEXT? relation User[documents] 1 --- 0..* Document[owner] action UploadDocument(title: TEXT, file: FILE): Document body user := @subject.entity storedFile := store file document := create Document { owner := user title := title file := storedFile } return document action SummarizeDocument(documentId: TEXT): Document body user := @subject.entity document := single Document where @id == documentId and owner == user summary := AI.prompt( message := "Summarize the uploaded document.", attachments := [document.file], provider := "openai", maxTokens := 600 ) update document { summary := summary } return document trigger UploadDocument on HttpRequest endpoint POST /documents arguments title := @request.body.title file := @request.files.file auth @subject is @defined trigger SummarizeDocument on HttpRequest endpoint POST /documents/{documentId}/summary arguments documentId := @request.path.documentId auth @subject is @defined ``` Clients should send upload requests as `multipart/form-data` with a file field matching the trigger binding. In the example above, the field name is `file`. ## What `store` Returns `store` accepts a `FILE` and returns a persisted `FILE`. The stored value keeps the original file name, MIME type, size, and a Sutro storage location. Persisted `FILE` values can be saved on entities and later used in actions. Use `store` when the file must survive after the current request. If an action only needs to process the upload immediately, it can pass the request file directly to another function or module without storing it first. Uploaded or stored `FILE` values can also be used as top-level request bodies with `HTTP.fetch` for outbound raw binary uploads. `HTTP.fetch` sends the file bytes unchanged and uses the file MIME type as the request `content-type` unless you provide one explicitly. `HTTP.fetch` can also return downloaded bytes as a `FILE` when you pass `responseType := "file"`. Store the returned file before saving it on an entity if it must survive after the current action. ## File Fields Use `FILE` fields for documents, images, PDFs, CSVs, or any uploaded blob that should be attached to an entity. `FILE` values are especially useful with: * Document upload workflows. * AI prompts with `attachments := [document.file]`. * Audit records that need to retain source files. * Imported data pipelines where a queue processes an uploaded file later. ## Upload Limits Generated app HTTP routes accept multipart uploads for trigger arguments bound from `@request.files`. The local and generated runtimes enforce upload limits before the SLang action runs, so oversized uploads fail at the HTTP layer. # Introduction to SLang Source: https://docs.withsutro.com/docs/SLang/introduction The programming language for defining Sutro backends. ## Overview SLang is the programming language for defining Sutro backends. The purpose of SLang is to provide a simple but powerful language to cleanly and intuitively define entire backends, including entities, logic, and security, without being slowed down by boilerplate, complex syntax, or hard-to-follow logical expressions. The result is a language that makes backend definition easy, avoids the majority of common mistakes, and is intuitive to pick up for humans and AI alike. Read about why backend engineering needs a new software language. Read about the "Zero-infra" philosophy behind Sutro. ## Core concepts SLang is designed around a small set of constructs that map directly to modern backend architecture: 1. **Entities**: Persisted database records and relationships. 2. **Schemas**: Reusable non-persisted structured types. 3. **Actions**: Typed business logic functions. 4. **Triggers**: HTTP endpoints, queues, cron jobs, and events that invoke actions. 5. **Security**: Subjects, identity fields, groups, roles, and permissions. 6. **Modules**: Built-in and local imports for capabilities such as AI and HTTP calls. ## Agent skill If you're using an AI coding agent like [Claude Code](https://docs.anthropic.com/en/docs/claude-code), you can install the official SLang skill to give your agent full knowledge of SLang syntax and semantics: ```bash theme={null} npx skills add https://github.com/SutroOrg/sutro-skills --skill slang ``` ## Learn more Define entities, fields, and relationships. Write business logic using simple control flow. Implement robust permissions and auth. Expose your logic via HTTP and Queues. Upload, persist, and pass documents through backend logic. Use built-in AI and HTTP modules or import local helpers. # Logic & Actions Source: https://docs.withsutro.com/docs/SLang/logic Write typed backend logic with actions, queries, mutations, control flow, and assertions. Actions are the functions of a SLang backend. They accept typed parameters, run backend logic, read and modify data, call modules, and return typed values. ## Action Shape An action has a name, typed parameters, a return type, optional metadata, and either a `body` or an `external` implementation. ```slang theme={null} entity User subject identity email fields email: EMAIL displayName: TEXT? enum TaskStatus values todo in_progress done entity Task fields title: TEXT status: TaskStatus := "todo" dueDate: DATE? completedAt: DATE_TIME? relation User[tasks] 1 --- 0..* Task[owner] action CreateTask(title: TEXT, dueDate?: DATE): Task description "Create a task for the current user." body user := @subject.entity task := create Task { owner := user title := title status := "todo" dueDate := dueDate } return task action ListMyTasks(): Page description "Return a page of tasks owned by the current user." body user := @subject.entity return pageOf Task where owner == user action CompleteTask(task: Task, completedAt: DATE_TIME): Task body update task { status := "done" completedAt := completedAt } return task action DeleteTask(task: Task): VOID body delete task action CloseAllOpenTasks(completedAt: DATE_TIME): NUMBER body page := pageOf Task where status != "done" count := 0 for task in page.items update task { status := "done" completedAt := completedAt } count := count + 1 return count ``` ## Reading Data Use `single` when the action needs one record. In HTTP contexts, a missing record is surfaced as a not-found response. ```slang theme={null} entity Todo fields title: TEXT action GetTodo(todoId: TEXT): Todo body todo := single Todo where @id == todoId return todo ``` Use `pageOf` when the action returns a collection. A page exposes `items`, `total`, and `offset`. Iterate over `page.items`, not over the page object itself. `where` filters support a limited comparison shape. The left side must be a model field or `@id`. The right side must be an in-scope value, such as an action parameter or local variable, an internal value such as `@subject`, or a plain string literal. ```slang theme={null} action ListTodoTasks(): Page body return pageOf Task where status == "todo" ``` Add `order by ` when callers need a stable, user-defined ordering. Ordering supports one persisted scalar field or `@id`; `asc` is the default direction, and `desc` reverses it. ```slang theme={null} entity Profile fields name: TEXT entity ProfileLink fields label: TEXT url: URL position: NUMBER relation Profile[links] 1 --- 0..* ProfileLink[profile] action ListProfileLinks(targetProfile: Profile): Page body return pageOf ProfileLink where profile == targetProfile order by position ``` ## Building Nested Response Bodies When an endpoint needs to return a parent object with related records nested inside it, query the parent record first, then query the child records and assign the child page's `items` array into the nested schema field. ```slang theme={null} schema PublicLink fields title: TEXT url: URL schema PublicPage fields slug: TEXT links: [PublicLink] entity ProfilePage fields slug: TEXT entity ProfileLink fields title: TEXT url: URL position: NUMBER relation ProfilePage[links] 1 --- 0..* ProfileLink[page] action CreateProfilePage(slug: TEXT): ProfilePage body page := create ProfilePage { slug := slug } return page action CreateProfileLink(pageId: TEXT, title: TEXT, url: URL, position: NUMBER): ProfileLink body targetPage := single ProfilePage where @id == pageId link := create ProfileLink { page := targetPage title := title url := url position := position } return link action GetPublicPage(slug: TEXT): PublicPage body profilePage := single ProfilePage where slug == slug links := pageOf ProfileLink where page == profilePage order by position return { slug := profilePage.slug links := links.items } trigger CreateProfilePage on HttpRequest endpoint POST /profile-pages arguments slug := @request.body.slug trigger CreateProfileLink on HttpRequest endpoint POST /profile-pages/{pageId}/links arguments pageId := @request.path.pageId title := @request.body.title url := @request.body.url position := @request.body.position trigger GetPublicPage on HttpRequest endpoint GET /public/pages/{slug} body { slug := @result.slug links := @result.links } arguments slug := @request.path.slug ``` After creating a page and two links, `GET /public/pages/alice` returns a nested `links` array. Because `links := links.items` returns the queried `ProfileLink` records directly, each nested link includes the record fields returned by the API, such as `id`, `title`, `url`, `position`, `page`, `createdAt`, and `updatedAt`. ## Writing Data Use `create Entity { ... }` to insert a record. Use `update record { ... }` to patch fields on an existing record. Use `delete record` to remove one. When you update a variable holding an entity instance, the variable is rebound to the updated instance, so returning the same variable returns the latest fields. ## Strings Use double-quoted strings for text. For dynamic text, prefer template string interpolation with `${...}` inside the string: ```slang theme={null} action BuildTaskPrompt(task: Task, categoryNames: TEXT): TEXT body return "Classify this task into one of these categories: ${categoryNames} Task title: ${task.title} Task description: ${task.description}" ``` Interpolations can include values that resolve to `TEXT`, `NUMBER`, or `BOOLEAN`. For entities, files, pages, and other structured values, interpolate a specific scalar field such as `${task.title}` rather than the whole value. The `+` operator can concatenate two text-compatible operands, such as `TEXT`, `EMAIL`, `PHONE_NUMBER`, `ADDRESS`, or `URL`, and can include `NUMBER` or `BOOLEAN` on the other side. Keep each `+` expression binary. Do not write long chains such as `"Task: " + task.title + ", categories: " + categoryNames`; use a template string, split the expression into steps, or parenthesize each binary pair. ```slang theme={null} action BuildCategoryList(user: User): TEXT body categories := pageOf Category where owner == user categoryNames := "" for category in categories.items categoryNames := "${categoryNames}${category.name}, " return categoryNames ``` ## Control Flow SLang supports: * `if` / `else` * `for item in array` * `while` * `break` and `continue` * boolean logic with `and`, `or`, and `not` * arithmetic and comparisons for compatible primitive values Use `assert(description := "...", rule := condition)` when an action should fail unless an invariant is true. # Modules, AI, and HTTP Source: https://docs.withsutro.com/docs/SLang/modules Import SLang modules and call built-in AI and HTTP capabilities. SLang files can import built-in modules and local helper modules. Built-ins are imported by name, and local modules are imported by path. ## Built-In Modules The current built-in modules are: | Module | Import | Export | | ------ | --------------- | ---------------------------------------------- | | AI | `import "AI"` | `AI.prompt(message := "text")` | | HTTP | `import "HTTP"` | `HTTP.fetch(url := "https://api.example.com")` | `import "AI"` is shorthand for `import "slang:AI"`. You can also alias built-ins with `as`. ```slang theme={null} import "slang:AI" as Assistant action DraftReply(message: TEXT): TEXT body return Assistant.prompt( message := message, system := "Write a concise support reply." ) ``` ## AI Prompting `AI.prompt` generates text. It accepts a required user message plus optional system instructions, `FILE` attachments, provider/model overrides, and max token settings. ```slang theme={null} import "AI" entity Document fields title: TEXT sourceFile: FILE summary: TEXT? action SummarizeDocument(document: Document): Document body summary := AI.prompt( message := "Summarize this document in five bullet points.", system := "You are a precise document analysis assistant.", attachments := [document.sourceFile], provider := "openai", maxTokens := 500 ) update document { summary := summary } return document ``` Supported providers are `openai` and `anthropic`. If you omit `provider`, SLang uses the default configured provider. If you omit `modelName`, the module uses the default model for that provider. Attachments must be `FILE` values. Store uploaded files before saving them on an entity; pass either the uploaded file or the stored file to `AI.prompt`. When building dynamic AI prompts, use template strings instead of chaining many `+` operators. This is especially useful when mixing literals, fields, and values accumulated in a loop. ```slang theme={null} import "AI" entity User subject identity email fields email: EMAIL entity Category fields name: TEXT entity Task fields title: TEXT description: TEXT? relation User[categories] 1 --- * Category[owner] relation User[tasks] 1 --- * Task[owner] action ClassifyTask(task: Task, user: User): TEXT body categories := pageOf Category where owner == user categoryNames := "" for category in categories.items categoryNames := "${categoryNames}${category.name}, " prompt := "Classify this task into one of these categories: ${categoryNames} Task title: ${task.title} Task description: ${task.description}" return AI.prompt( message := prompt, system := "Return only the best matching category name." ) ``` ## HTTP Fetching `HTTP.fetch` makes outbound HTTP or HTTPS calls and returns an object with `status`, `headers`, and optional `body`. ```slang theme={null} import "HTTP" action CreateRemoteTicket(baseUrl: TEXT, title: TEXT): UNKNOWN body response := HTTP.fetch( url := baseUrl + "/tickets", method := "POST", headers := { "authorization" := "Bearer example-token" }, query := { source := "sutro" }, body := { title := title } ) return response ``` To upload a raw binary file, pass a `FILE` as the top-level body. `HTTP.fetch` sends the file bytes unchanged and uses the file MIME type as the request `content-type` unless you provide one explicitly. ```slang theme={null} import "HTTP" action UploadRemoteFile(uploadUrl: TEXT, file: FILE): UNKNOWN body response := HTTP.fetch( url := uploadUrl, method := "PUT", body := file ) return response ``` To download response bytes without converting them to text, set `responseType := "file"`. The response keeps the same object shape, but `body` is a `FILE` value. ```slang theme={null} import "HTTP" action DownloadRemoteImage(imageUrl: TEXT): FILE body response := HTTP.fetch( url := imageUrl, responseType := "file" ) return response.body ``` `HTTP.fetch` behavior: * `method` defaults to `GET`. * Supported methods are `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `OPTIONS`, and `HEAD`. * `query` must be a plain object of strings, numbers, booleans, arrays of those primitives, `null`, or `undefined`. * Object request bodies are JSON-encoded and get `content-type: application/json` unless you set a content type yourself. * Top-level `FILE` request bodies are sent as raw bytes and get the file MIME type as `content-type` unless you set a content type yourself. * `FILE` values are not supported inside JSON object or array bodies. Multipart bodies, including `multipart/related`, are not constructed automatically. * JSON responses are parsed into objects; non-JSON responses return text. * Set `responseType := "file"` to return response bytes as a `FILE` in `body`. Store the returned file before saving it on an entity if it must survive after the action. ## Local Modules Local imports use relative paths and only expose symbols declared with `export`. Examples: * `import "./helpers"` merges exported symbols into the current file. * `import "./helpers" as Helpers` places exported symbols under `Helpers`. * `export action BuildTitle(title: TEXT): TEXT` makes an action importable. * `export entity SharedModel` makes an entity importable. Use aliases when two modules export symbols with similar names or when you want calls such as `Helpers.BuildTitle(title := title)` to be explicit. # Security & Auth Source: https://docs.withsutro.com/docs/SLang/security Define subjects, identities, groups, roles, permissions, and authenticated user updates. SLang security is built around the request `@subject`. A subject is the authenticated caller. You decide which entity represents a subject, which field identifies it, and which role paths grant permissions. ## Subjects and Identity Fields Mark an entity with `subject` when records of that entity can authenticate. Add `identity ` to choose the login identifier field. The identity field must exist on the entity. SLang also includes `@id` as an identity field internally, so `identity email` means the runtime can connect a token subject back to the persisted user row. ```slang theme={null} enum MembershipRole values member admin owner entity User subject identity email fields email: EMAIL displayName: TEXT? entity Organization group @id fields name: TEXT entity Membership role membershipRole fields membershipRole: MembershipRole := "member" entity Project fields title: TEXT relation User[memberships] 1 --- 0..* Membership[member] relation Organization[memberships] 1 --- 0..* Membership[organization] relation Organization[projects] 1 --- 0..* Project[organization] permissions User->memberships->member "project:read" permissions User->memberships->admin "project:read" "project:write" permissions User->memberships->owner "project:read" "project:write" "member:manage" action CurrentUser(): User body return @subject.entity action UpdateCurrentUser(displayName?: TEXT): User body user := @subject.entity update user { displayName := displayName } return user action ListProjects(organizationId: TEXT): Page body org := single Organization where @id == organizationId return pageOf Project where organization == org trigger CurrentUser on HttpRequest endpoint GET /me auth @subject is @defined trigger UpdateCurrentUser on HttpRequest endpoint PATCH /me arguments displayName := @request.body.displayName auth @subject is @defined trigger ListProjects on HttpRequest endpoint GET /organizations/{organizationId}/projects arguments organizationId := @request.path.organizationId auth @subject can "project:read" in Organization(@request.path.organizationId) ``` ## Getting the User Entity Use `@subject.entity` when action logic needs the persisted row for the authenticated subject. Common uses: * Return the current user from `GET /me`. * Update profile fields on the authenticated user. * Compare ownership with `where owner == @subject.entity`. When assigning ownership on create, you can assign either `owner := @subject.entity` or `owner := @subject` when the relation field points at the subject entity. The runtime resolves the subject to the stored entity before writing. ## Groups, Roles, and Permissions Use `group @id` on an entity whose instances scope permissions, such as an `Organization`, `Team`, or `Workspace`. Use `role ` on the entity that carries role membership. The role field must be a non-optional enum. In the example above, `Membership.membershipRole` is the role field. Permission statements start at a subject entity, traverse relation fields, and end at one role enum value: `permissions User->memberships->admin` That grants the listed permission strings to users whose `memberships` path resolves to a `Membership` with role `admin`. ## Trigger Auth Rules Trigger `auth` blocks support these predicates: * `@subject is @defined` for any authenticated subject. * `@subject is @anonymous` for anonymous callers. * `@subject is admin` for a role by name. * `@subject is admin in Organization(@request.path.organizationId)` for a role scoped to a group instance. * `@subject can "project:read"` for a global permission. * `@subject can "project:read" in Organization(@request.path.organizationId)` for a permission scoped to a group instance. You can combine predicates with `and` and `or`. Parenthesized auth subexpressions are not supported by current validation, so write combined rules without parentheses. If a trigger omits `auth`, it is public. ## Generated Auth Endpoints When a SLang app defines a subject with an identity field, the generated app exposes standard auth endpoints for that subject model: * `POST /register` * `POST /login` * `POST /refresh` * `GET /.well-known/jwks.json` Registration and login accept `identity` and `password`. The identity value should match the field declared by `identity `, such as the user's email address. # Generated App Security Source: https://docs.withsutro.com/docs/SLang/sutro-generated-app-security How Sutro generated apps resolve authenticated subjects and evaluate SLang auth rules. Generated apps turn SLang security declarations into runtime authentication and authorization behavior. ## Request Flow When a request reaches a generated app: 1. The runtime extracts credentials from the request. 2. It validates the credentials and establishes a subject. 3. It resolves principals, roles, groups, and permissions for that subject. 4. It exposes the result to SLang as `@subject`. 5. It evaluates the trigger `auth` block before running the action. If credentials are missing where authentication is required, the request fails with `401`. If the subject is authenticated but does not satisfy the auth rule, the request fails with `403`. ## Subject Resolution The generated app can resolve `@subject.entity` only when the token subject matches a SLang entity marked with `subject` and `identity`. ```slang theme={null} entity User subject identity email fields email: EMAIL displayName: TEXT? action CurrentUser(): User body return @subject.entity action UpdateDisplayName(displayName?: TEXT): User body user := @subject.entity update user { displayName := displayName } return user trigger CurrentUser on HttpRequest endpoint GET /me auth @subject is @defined trigger UpdateDisplayName on HttpRequest endpoint PATCH /me arguments displayName := @request.body.displayName auth @subject is @defined ``` The `identity email` declaration tells the generated app which user field is used for registration and login. The runtime also tracks the internal `@id`, which lets `@subject.entity` fetch the persisted user row. ## Principals, Roles, and Permissions Principals are security facts about a subject. Roles and permissions are derived from the model relationships declared in SLang: * `group @id` marks an entity whose instances can scope permissions. * `role roleField` marks the enum field that carries a role. * `permissions Subject->relationPath->roleValue` grants permission strings to that role. At request time, generated apps use those declarations to build `@subject.roles` and principal permissions. Trigger auth checks such as `@subject can "project:read" in Organization(@request.path.organizationId)` are evaluated from that runtime subject context. ## Generated Auth Endpoints Subject declarations enable generated auth endpoints: * `POST /register` * `POST /login` * `POST /refresh` * `GET /.well-known/jwks.json` Registration and login use the identity field declared in SLang. For `identity email`, clients send the user's email as the `identity` value. ## Practical Guidance Keep auth checks at the trigger boundary for coarse access control, and keep ownership checks inside actions for record-level safety. For example, a trigger can require `@subject is @defined`, while the action uses `single Document where @id == documentId and owner == @subject.entity`. # Syntax Basics Source: https://docs.withsutro.com/docs/SLang/syntax Basic SLang source syntax, including comments. ## Comments SLang comments are single-line comments that start with `;;`. ```slang theme={null} ;; This comment is valid SLang. entity Task fields title: TEXT ``` Do not use `#` or `//` for comments in `.slang` files. # API & Triggers Source: https://docs.withsutro.com/docs/SLang/triggers Expose SLang actions through HTTP, queues, cron schedules, and events. Triggers connect an action to an entry point. A trigger selects the transport, maps transport data into action arguments, and optionally protects execution with an `auth` block. ## HTTP Triggers HTTP triggers expose actions as REST endpoints. ```slang theme={null} entity Todo fields title: TEXT status: ENUM("todo", "done") := "todo" action CreateTodo(title: TEXT): Todo body todo := create Todo { title := title status := "todo" } return todo trigger CreateTodo on HttpRequest endpoint POST /todos statusCode 201 body { id := @result.id title := @result.title status := @result.status } responseHeaders { "x-resource-type" := "todo" } arguments title := @request.body.title ``` HTTP triggers support these request sources: | Source | Meaning | | -------------------------- | ----------------------------------- | | `@request.body.fieldName` | JSON request body fields. | | `@request.path.paramName` | Path parameters from `{paramName}`. | | `@request.query.paramName` | Query string values. | | `@request.files.fieldName` | Uploaded files as `FILE` values. | ### Entity arguments from path IDs When an action argument is typed as an entity, you can bind it directly from a path-string ID. The runtime auto-resolves the path string into the entity instance for you — there is no need to declare a `TEXT` id parameter and then look the entity up with `single Entity where @id == X`. ```slang theme={null} action GetTodo(todo: Todo): Todo body return todo trigger GetTodo on HttpRequest endpoint GET /todos/{id} arguments todo := @request.path.id ``` The argument inside the action body is the resolved entity, so field access (e.g. `todo.title`) and relation traversal work as expected. This also applies to `PUT /{collection}/{id}` and `DELETE /{collection}/{id}` triggers that operate on a single resource. By default, an HTTP trigger returns the action result with status `200` and no extra headers. Override that with `statusCode`, `body`, and `responseHeaders` when the public API shape should differ from the action result. ## Queues Use a queue when a request should return quickly while background work continues. ```slang theme={null} entity WorkItem fields label: TEXT entity ProcessedWork fields label: TEXT queue workQueue with WorkItem action EnqueueWork(label: TEXT): WorkItem body item := create WorkItem { label := label } enqueue workQueue with item return item action ProcessWork(message: WorkItem): VOID body create ProcessedWork { label := message.label } trigger EnqueueWork on HttpRequest endpoint POST /work arguments label := @request.body.label trigger ProcessWork on Queue queue workQueue arguments message := @message ``` Declare a queue with `queue name with EntityType`, enqueue with `enqueue name with value`, and consume with a `trigger ... on Queue` that maps `@message`. ## Cron Triggers Cron triggers run on a schedule and have no request or subject context, so they cannot use `auth`, `@request`, or `@subject`. ```slang theme={null} entity CleanupLog fields label: TEXT retentionDays: NUMBER action NightlyCleanup(retentionDays: NUMBER): VOID body create CleanupLog { label := "nightly" retentionDays := retentionDays } trigger NightlyCleanup on Cron schedule "0 2 * * *" arguments retentionDays := 30 ``` Schedules are plain cron strings. Use five-field cron expressions for minute-level schedules, or a seconds field when the local dev server needs sub-minute testing. ## Event Triggers Event triggers subscribe an action to an internal named event. ```slang theme={null} entity AuditEntry fields message: TEXT action RecordUserEvent(message: TEXT): VOID body create AuditEntry { message := message } trigger RecordUserEvent on Event event userCreated arguments message := @message ``` Event and queue triggers both use `@message` for their payload. The difference is how the message is produced: queues are explicit SLang queues, while events are named application events emitted by the runtime. # Prompt to backend overview Source: https://docs.withsutro.com/docs/backend/overview Generate, host and edit production-ready backends The Sutro API supports the generation, hosting and editing of production-ready backends. These generated API servers can be constructed with a single prompt, processed by our AI agent. They can also be constructed manually through calls to our API. You can [learn how to generate a backend from a prompt](/docs/backend/prompt-to-backend). ## Example For a deeper walk-through, follow the [Prompt to backend tutorial](/docs/backend/prompt-to-backend); the snippet below shows the type of output produced from a simple LLM prompt. This results in an API Server with a downloadable OpenAPI document. Once published, your API is accessible at `https://{applicationId}.app.withsutro.com/api/v{version}/`. ```yaml api.yaml expandable theme={null} openapi: 3.1.1 info: title: TaskTracker Pro version: 1.0.1 description: Manage and track personal tasks with deadlines to stay organized and ensure timely completion of work jsonSchemaDialect: https://spec.openapis.org/oas/3.1/dialect/base servers: - url: https://fc9fe14b-43ed-4a3b-99a7-ee4d0ba13224.app.withsutro.com/api/v1.0.1 description: Development Server components: schemas: User: type: object required: - id - todos properties: id: type: string format: uuid name: type: string $comment: p_TEXT email: type: string $comment: p_TEXT todos: type: array items: $ref: "#/components/schemas/ToDo" $comment: "urn:sutro:model:toDo" x-sutro-relOwner: true title: User description: User additionalProperties: false $id: User ToDo: type: object required: - id - user properties: id: type: string format: uuid title: type: string $comment: p_TEXT description: type: string $comment: p_TEXT deadline: type: string format: date-time $comment: p_DATE_TIME status: type: string $comment: p_TEXT user: $ref: "#/components/schemas/User" $comment: "urn:sutro:model:user" x-sutro-relOwner: false title: ToDo description: To Do additionalProperties: false $id: ToDo responses: GetUsersResponse: description: Entities retrieved successfully content: application/json: schema: type: object additionalProperties: false properties: items: type: array items: $ref: "#/components/schemas/User" total: type: number offset: type: number GetUserResponse: description: getEntity successful content: application/json: schema: $ref: "#/components/schemas/User" CreateUserResponse: description: createEntity successful content: application/json: schema: $ref: "#/components/schemas/User" UpdateUserResponse: description: updateEntity successful content: application/json: schema: $ref: "#/components/schemas/User" DeleteUserResponse: description: Response for Create urn:sutro:action:deleteUserServer GetToDosResponse: description: Entities retrieved successfully content: application/json: schema: type: object additionalProperties: false properties: items: type: array items: $ref: "#/components/schemas/ToDo" total: type: number offset: type: number GetToDoResponse: description: getEntity successful content: application/json: schema: $ref: "#/components/schemas/ToDo" CreateToDoResponse: description: createEntity successful content: application/json: schema: $ref: "#/components/schemas/ToDo" UpdateToDoResponse: description: updateEntity successful content: application/json: schema: $ref: "#/components/schemas/ToDo" DeleteToDoResponse: description: Response for Create urn:sutro:action:deleteToDoServer requestBodies: CreateUserRequestBody: description: Request body for createUser content: application/json: schema: type: object required: - todos properties: name: type: string $comment: p_TEXT email: type: string $comment: p_TEXT todos: type: array items: type: string description: ID of To Do $comment: "urn:sutro:model:toDo" x-sutro-relOwner: true title: User description: Request body for User additionalProperties: false $id: CreateUserRequestBody required: true UpdateUserRequestBody: description: Request body for updateUser content: application/json: schema: type: object properties: name: type: string $comment: p_TEXT email: type: string $comment: p_TEXT todos: type: array items: type: string description: ID of To Do $comment: "urn:sutro:model:toDo" x-sutro-relOwner: true $id: UpdateUserRequestBody description: Request body for User required: true CreateToDoRequestBody: description: Request body for createTo Do content: application/json: schema: type: object required: - user properties: title: type: string $comment: p_TEXT description: type: string $comment: p_TEXT deadline: type: string format: date-time $comment: p_DATE_TIME status: type: string $comment: p_TEXT user: type: string description: ID of User $comment: "urn:sutro:model:user" x-sutro-relOwner: false title: ToDo description: Request body for To Do additionalProperties: false $id: CreateToDoRequestBody required: true UpdateToDoRequestBody: description: Request body for updateTo Do content: application/json: schema: type: object properties: title: type: string $comment: p_TEXT description: type: string $comment: p_TEXT deadline: type: string format: date-time $comment: p_DATE_TIME status: type: string $comment: p_TEXT user: type: string description: ID of User $comment: "urn:sutro:model:user" x-sutro-relOwner: false $id: UpdateToDoRequestBody description: Request body for To Do required: true paths: /users: get: operationId: getUsers summary: Get a collection of Users responses: "200": $ref: "#/components/responses/GetUsersResponse" post: operationId: createUser summary: Create a new User responses: "200": $ref: "#/components/responses/CreateUserResponse" requestBody: $ref: "#/components/requestBodies/CreateUserRequestBody" /users/{id}: get: operationId: getUser summary: Get a single User responses: "200": $ref: "#/components/responses/GetUserResponse" parameters: - name: id in: path required: true schema: type: string format: uuid put: operationId: updateUser summary: Update an existing User responses: "200": $ref: "#/components/responses/UpdateUserResponse" requestBody: $ref: "#/components/requestBodies/UpdateUserRequestBody" parameters: - name: id in: path required: true schema: type: string format: uuid delete: operationId: deleteUser summary: Delete an existing User responses: "200": $ref: "#/components/responses/DeleteUserResponse" parameters: - name: id in: path required: true schema: type: string format: uuid /toDos: get: operationId: getTo Dos summary: Get a collection of To Dos responses: "200": $ref: "#/components/responses/GetToDosResponse" post: operationId: createTo Do summary: Create a new To Do responses: "200": $ref: "#/components/responses/CreateToDoResponse" requestBody: $ref: "#/components/requestBodies/CreateToDoRequestBody" /toDos/{id}: get: operationId: getTo Do summary: Get a single To Do responses: "200": $ref: "#/components/responses/GetToDoResponse" parameters: - name: id in: path required: true schema: type: string format: uuid put: operationId: updateTo Do summary: Update an existing To Do responses: "200": $ref: "#/components/responses/UpdateToDoResponse" requestBody: $ref: "#/components/requestBodies/UpdateToDoRequestBody" parameters: - name: id in: path required: true schema: type: string format: uuid delete: operationId: deleteTo Do summary: Delete an existing To Do responses: "200": $ref: "#/components/responses/DeleteToDoResponse" parameters: - name: id in: path required: true schema: type: string format: uuid ``` You can see API documentation for this example [here](/api-reference/get-a-collection-of-users). # How-to: Prompt to backend Source: https://docs.withsutro.com/docs/backend/prompt-to-backend Generate a backend API server using an LLM prompt ## Overview This tutorial walks through the steps of generating a simple API server from scratch using the Sutro API. ## Before you begin ### Tools * `jq` and `curl` ### Security bundle Download `security-bundle.zip` from the [Sutro Console](https://console.withsutro.com) during onboarding. Extract it and run all commands from that directory. The bundle includes your API client credentials (`apiClient.id`, `mtls.key`, `mtls.crt`), the Sutro CA certificate (`ca.crt`), and a pre-generated Builder JWT (`builder.jwt`) valid for 45 days. The test bundle creates a **test builder** for quick API testing, not for production. See [How to Secure Connections](/docs/getting-started/auth/how-to-secure-connections) for production setup. ### Verify your connection Test that your credentials work by calling the hello endpoint: ```sh theme={null} curl -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ "https://sapi.withsutro.com/hello" ``` You should see a response confirming your API client, Builder, and organization. ## Steps This flow takes you from prompt to publishing so every asset (project, app, and OpenAPI spec) stays under your control the whole time. Start by creating a Project to hold the prompt, application, and generated assets. Add a short description so you remember the goal. In this example, use "My To Do Server". Call [`POST /projects`](/api-reference/projects/create-a-new-project) ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X POST \ -o project.json \ -d '{ "name": "My To Do Server" }' \ "https://sapi.withsutro.com/projects" ``` Since we're only building a backend API, we omit the `components` array, which defaults to `["backend"]`. To include a frontend, pass `"components": ["backend", "frontend"]`. See the [full-stack quickstart](/docs/getting-started/building-full-stack-apps) for details. Congratulations! You've just created a Sutro Project. The project details now live in `project.json`; refer to that file in upcoming steps. Next, create an Application. Most Projects contain a single Application. Call `POST /projects/{projectId}/applications` ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X POST \ -o application.json \ -d '{ "scode": {} }' \ "https://sapi.withsutro.com/projects/$(jq -r '.id' < project.json)/applications" ``` Now you have an Application; two more steps and it will be building... Provide the Application with a prompt so the LLM knows what to generate. Since this tutorial builds a to-do server, use the following prompt: Call [`POST /applications/{applicationId}/attachments`](/api-reference/attachments/attach-a-file). ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X POST \ -d '{"type": "PROMPT", "prompt":"Build me an API server that helps users track To Dos.\n\nIt should include the ability to set deadlines on To Do items, as well as mark them completed"}' \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)/attachments" ``` The prompt is now attached; the Application is ready to generate. Generating an API server takes a little time, so call the Sutro API to *start* the process. Monitoring happens in the next step. Call [`POST /applications/{applicationId}/generate`](/api-reference/applications/generate-application). ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X POST \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)/generate" ``` This call will return quickly; our API server is being generated. Because `curl` drives this tutorial, poll the API for the Application's status. The `-s` flag limits output to just the Application status, so keep an eye out for unexpected text that might signal local network issues. Call [`GET /applications/{applicationId}/status`](/api-reference/applications/gets-the-current-status-of-the-application). ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -s \ -X GET \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)/status" | jq ``` Make this call every \~10 seconds until the status shows completion. Once the response says `"Successful"`, your API is published and accessible at: ``` https://{applicationId}.app.withsutro.com/api/v{version}/ ``` Replace `{applicationId}` with your application ID (from `application.json`). There are many ways to exercise the new API. Start by getting a description so you know the available paths and methods. Call [`GET /applications/{applicationId}/openapi`](/api-reference/applications/get-the-openapi-spec-for-an-application). ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -o openapi.yml \ -X GET \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)/openapi" ``` With the OpenAPI document in hand, pick your favorite API client and start exploring. This API doesn't have any user credentials because security wasn't configured. That's fine for exploration, but add proper authentication before going live with real users' data. Your backend is generated, published, and documented. Grab the OpenAPI file and start wiring clients with confidence. ## Reference * [`POST /projects`](/api-reference/projects/create-a-new-project) * [`POST /projects/{projectId}/application`](/api-reference/applications/generate-application) * [`POST /applications/{applicationId}/attachments`](/api-reference/attachments/attach-a-file) * `POST /applications/{applicationId}/generation` * [`GET /applications/{applicationId}/status`](/api-reference/applications/gets-the-current-status-of-the-application) * [`GET /applications/{applicationId}/openapi`](/api-reference/applications/get-the-openapi-spec-for-an-application) # CLI command reference Source: https://docs.withsutro.com/docs/cli/command-reference Commands, flags, and output modes for the Sutro CLI. ## Installation Install the CLI globally: ```sh npm theme={null} npm install --global @sutro-dev/sutro-cli ``` ```sh pnpm theme={null} pnpm add --global @sutro-dev/sutro-cli ``` ```sh yarn theme={null} yarn global add @sutro-dev/sutro-cli ``` The package installs the `sutro` command. Requirements: | Requirement | Value | | ----------- | ---------------------- | | Node.js | 22 or later | | npm package | `@sutro-dev/sutro-cli` | | Binary | `sutro` | ## Global options Global options work with every command. | Option | Description | | --------------- | --------------------------------------------------------------------------------------- | | `-V, --version` | Print the CLI version. | | `--json` | Output machine-readable JSON. For `sutro dev`, output is newline-delimited JSON events. | | `--debug` | Print debug details, including API request context and error context. | | `--color` | Force color output. | | `--no-color` | Disable color output. | | `-h, --help` | Show help for a command. | Examples: ```sh theme={null} sutro --version sutro status --json sutro publish --debug ``` ## Commands ### `sutro login` Log in to Sutro through the browser and store a local CLI session. ```sh theme={null} sutro login ``` Options: | Option | Description | | ----------- | ------------------------------------------------- | | `--no-open` | Print the login URL instead of opening a browser. | ### `sutro logout` Clear the locally stored CLI session. ```sh theme={null} sutro logout ``` ### `sutro whoami` Show the currently logged-in user. ```sh theme={null} sutro whoami ``` ### `sutro init` Link the current folder to a Sutro Project and Application. If no IDs are provided, the CLI creates a new Project and Application. ```sh theme={null} sutro init --name "Task API" ``` Options: | Option | Description | | ----------------------- | ---------------------------------------------------------------------------- | | `-n, --name ` | App name used when creating a new Project. | | `--project-id ` | Link to an existing Project and create a new Application inside it. | | `--application-id ` | Link to an existing Application. The CLI reads its Project ID automatically. | | `--entry-file ` | SLang entry file to scaffold and track. Defaults to `app.slang`. | | `-y, --yes` | Accept defaults without prompting. | `sutro init` writes `sutro.config.json` and creates the entry file if it does not already exist. ### `sutro dev` Run the linked SLang app in a remote dev session. ```sh theme={null} sutro dev ``` Options: | Option | Description | | ------------ | -------------------------------------------------------------------------------- | | `--no-watch` | Upload once and keep the remote session alive without watching for file changes. | `sutro dev` uploads all local `.slang` files under the project root, starts a remote preview, and prints an API URL like: ```text theme={null} https://dev-.app.withsutro.com/api/latest/ ``` While watching is enabled, changes to `.slang` files and `sutro.config.json` trigger a remote reload. Press Ctrl + C to stop the dev session. ### `sutro validate` Validate the linked SLang project without publishing it. ```sh theme={null} sutro validate ``` The CLI uploads the local source to Sutro and prints compiler diagnostics if validation fails. ### `sutro publish` Upload the linked SLang project and publish the Application. ```sh theme={null} sutro publish ``` The command uploads all local `.slang` files, publishes the Application, waits for the published version to become active, and prints the published URL. Publishing requires a payment method on file. ### `sutro status` Show the linked Project, Application, entry file, publish state, and published version. ```sh theme={null} sutro status ``` ### `sutro openapi` Open the published OpenAPI spec in Console. ```sh theme={null} sutro openapi ``` Options: | Option | Description | | -------------- | -------------------------------------------------------------------------------------------------------------- | | `--out [path]` | Save the OpenAPI spec locally instead of opening Console. Defaults to `openapi.json` when no path is provided. | Examples: ```sh theme={null} sutro openapi --out sutro openapi --out ./schema/openapi.json ``` ## Exit codes | Code | Meaning | | ---- | ------------------------------------------------------------------------------------------ | | `0` | Command succeeded. | | `1` | Runtime, authentication, network, API, validation, or publish failure. | | `2` | Usage error, such as an unknown flag or missing required input in a non-interactive shell. | ## Automation Use `--json` when calling the CLI from scripts or AI coding agents: ```sh theme={null} sutro status --json sutro validate --json sutro publish --json ``` `sutro dev --json` writes newline-delimited events because the command keeps running: ```sh theme={null} sutro dev --json ``` Each event includes an `event` field, such as `session_ready`, `session_update`, or `session_update_failed`. ## Related pages * [Sutro CLI quickstart](/docs/getting-started/cli-quickstart) * [Project configuration](/docs/cli/project-config) * [Introduction to SLang](/docs/SLang/introduction) # Project configuration Source: https://docs.withsutro.com/docs/cli/project-config How sutro.config.json links a local SLang project to a Sutro Application. ## Overview `sutro.config.json` links a local folder to a Sutro Project and Application. CLI commands that operate on a project, such as `sutro dev`, `sutro validate`, `sutro publish`, `sutro status`, and `sutro openapi`, read this file from the current working directory. Create the file with: ```sh theme={null} sutro init ``` ## File format Example: ```json theme={null} { "$schema": "https://assets.withsutro.com/sutro-cli-schema.json", "projectId": "", "applicationId": "", "entryFile": "app.slang" } ``` Fields: | Field | Required | Description | | --------------- | -------- | -------------------------------------------------------------------------------- | | `$schema` | No | JSON schema URL used by editors for validation and autocomplete. | | `projectId` | Yes | Sutro Project ID linked to this folder. | | `applicationId` | Yes | Sutro Application ID that receives validation, dev-session, and publish updates. | | `entryFile` | Yes | SLang entry file. Defaults to `app.slang` when generated by `sutro init`. | `entryFile` must point to a file inside the project directory. ## Creating config Create a new Project and Application: ```sh theme={null} sutro init --name "Task API" ``` Create a new Application inside an existing Project: ```sh theme={null} sutro init --project-id ``` Link an existing Application: ```sh theme={null} sutro init --application-id ``` Use a custom entry file: ```sh theme={null} sutro init --entry-file backend/app.slang ``` ## Source upload behavior When the CLI uploads SLang source, it sends: * The configured `entryFile`. * Every `.slang` file under the project directory. * Paths relative to the project directory. The CLI skips generated and vendor directories: | Directory | Reason | | -------------- | ---------------------------------------------------- | | `.git` | Git internals are not source files. | | `.slang-data` | Local runtime data from older development workflows. | | `.sutro` | Local Sutro cache data. | | `.turbo` | Build cache. | | `coverage` | Test coverage output. | | `dist` | Build output. | | `node_modules` | Installed dependencies. | ## Multi-file projects Local imports work with multi-file projects. For example: ```text theme={null} task-api/ sutro.config.json app.slang models.slang ``` `app.slang` can import `models.slang`: ```slang theme={null} import "./models" action ListTasks(): Page body return pageOf Task ``` `models.slang` can define shared models: ```slang theme={null} export entity Task fields title: TEXT completed: BOOLEAN ``` When you run `sutro dev`, `sutro validate`, or `sutro publish`, the CLI uploads both files. ## Related pages * [Sutro CLI quickstart](/docs/getting-started/cli-quickstart) * [CLI command reference](/docs/cli/command-reference) * [SLang modules](/docs/SLang/modules) # Prompt to frontend overview Source: https://docs.withsutro.com/docs/frontend/overview Generate, customize and publish production-ready web frontends The Sutro API supports the generation, customization, and publishing of production-ready web frontends that seamlessly integrate with your generated backend APIs. ## Generation Methods Frontends can be generated in two ways: **By prompt**: Generate a complete full-stack application (backend + frontend) from a single natural language description. The frontend is automatically created to work with the generated backend API. **By Figma design**: Convert existing Figma designs into pixel-perfect HTML/CSS code. This allows you to bring your design mockups to life while maintaining visual fidelity to your original designs. ## Customization and Iteration Once generated, frontends can be customized to the fullest extent using our AI assistant. You can have natural language conversations with the assistant to make changes, add features, modify layouts, or refine the user experience. The assistant understands your application's structure and can make targeted modifications while maintaining consistency. ## Publishing Options Generated frontends can be accessed in two ways: **Hosted by Sutro**: Your frontend can be hosted directly through the Sutro API, making it immediately accessible via a URL. This is perfect for rapid prototyping and testing. Simply publish your application and access it via the provided URL. **Static bundle export**: Export your frontend as a static bundle (HTML, CSS, JavaScript, and assets) that can be served by any web server. This gives you complete control over hosting and deployment. When self-hosting, you'll need to: 1. Configure CORS on your backend to allow requests from your frontend's origin 2. Export the frontend bundle via the API 3. Deploy the bundle to your hosting provider The exported bundle is a production-ready React application that connects to your Sutro-hosted backend. ## Getting Started * [Learn how to build a full-stack app with frontend](/docs/getting-started/building-full-stack-apps) - Generate both backend and frontend from a prompt * [Self-host your frontend](/docs/getting-started/building-full-stack-apps#self-hosting-the-frontend) - Export and deploy the frontend to your own infrastructure * [Prompt to frontend](/docs/frontend/prompt-to-frontend) - Use prompts to modify and iterate on your frontend using natural language # How-to: Prompt to frontend Source: https://docs.withsutro.com/docs/frontend/prompt-to-frontend Use prompts to modify and iterate on your frontend using natural language ## Overview This guide shows you how to use the Sutro AI Assistant to make changes to your built application using natural language. The assistant allows you to have a conversation about your application and trigger modifications through simple prompts. ## Before you begin ### Tools * `jq` and `curl` ### Security bundle Download `security-bundle.zip` from the [Sutro Console](https://console.withsutro.com) during onboarding. Extract it and run all commands from that directory. The bundle includes your API client credentials (`apiClient.id`, `mtls.key`, `mtls.crt`), the Sutro CA certificate (`ca.crt`), and a pre-generated Builder JWT (`builder.jwt`) valid for 45 days. The test bundle creates a **test builder** for quick API testing, not for production. See [How to Secure Connections](/docs/getting-started/auth/how-to-secure-connections) for production setup. ### Prerequisites * You should have already created a project and published an application. If you haven't, follow the [Building full-stack apps](/docs/getting-started/building-full-stack-apps) guide first. * Have your `project.json` file handy (or at least the project ID). ### Verify your connection Test that your credentials work by calling the hello endpoint: ```sh theme={null} curl -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ "https://sapi.withsutro.com/hello" ``` You should see a response confirming your API client, Builder, and organization. ## Steps This flow keeps the entire conversation auditable. Every message, change, and status update is captured so you can steer the assistant with confidence. Before making changes, you may want to see the existing conversation history for your project. Messages are stored per project to maintain conversation context. Call [`GET /projects/{projectId}/messages`](/api-reference/ai-assistant/get-all-messages-for-a-project). ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -s \ -X GET \ "https://sapi.withsutro.com/projects/$(jq -r '.id' < project.json)/messages" | jq ``` This will return a list of all messages (both user and assistant messages) for your project, allowing you to see the conversation history. Send a message to the assistant to start or continue a conversation. When you send a message, it will: * Create a user message in the conversation history * Process your message with the AI assistant * Trigger changes to your application if your message requests modifications * Return the assistant's response The components that can be modified (frontend, backend, or both) are determined by your project's components configuration set at project creation. This cannot be overridden. Call [`POST /projects/{projectId}/messages`](/api-reference/ai-assistant/send-a-message-to-the-assistant). ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X POST \ -d '{ "content": [ { "type": "text", "text": "Add a dark mode toggle button in the header that switches between light and dark themes" } ] }' \ "https://sapi.withsutro.com/projects/$(jq -r '.id' < project.json)/messages" ``` The response will include the assistant's message, which may contain information about the changes being made or confirmation that the changes have been processed. The user message is automatically stored in the conversation history. Conversation history and updates stay in sync. You're now ready to guide the assistant through iterative refinements. ## Tips * **Be specific**: When describing changes you want to make, be as specific as possible. For example, "Add a dark mode toggle button in the header" is better than "add dark mode". * **Iterate**: You can have multiple conversations with the assistant. Each message builds on the conversation history, so you can refine your requests based on previous interactions. * **Check your project components**: Remember that the assistant can only modify components that were configured when you created your project. If you created a project with only `backend`, the assistant won't be able to modify frontend components. * **Monitor your application**: After triggering changes, you may want to check your application status and republish if necessary to see the changes take effect. # Introduction to the API Source: https://docs.withsutro.com/docs/getting-started/api Learn about the Sutro API, authentication, requests, responses, and errors ## Overview The Sutro API provides programmatic access to create, manage, and publish backends. You can use the API to define backends, manage projects and applications, handle authentication, and interact with all Sutro resources. ## What you can do With the Sutro API, you can: * **Create and manage projects**: Organize your backends into projects * **Define backends**: Use API calls to define backend logic and security * **Publish applications**: Publish and manage your backend applications * **Handle authentication**: Configure Members, Builders, and security settings * **Make precise edits**: Update backends without editing SLang definitions directly ## Authentication All API requests require authentication using JWTs and mutual TLS (mTLS). The authentication system ensures secure access to your resources. [Learn about authentication](/docs/getting-started/auth/overview) to get started with API access. ## Requests, responses, and errors The Sutro API follows REST principles and uses standard HTTP methods. All endpoints return consistent response formats and error codes. [Learn about requests, responses, and errors](/docs/getting-started/requests-responses-errors) to understand how to interact with the API. ## Getting started To use the Sutro API, you'll need: * API client credentials (from your security bundle) * Builder JWT for authentication * Mutual TLS certificates for secure connections Download your security bundle from the [Sutro Console](https://console.withsutro.com) to get started. ## Related * [Welcome](/docs/getting-started/welcome) - Learn about all ways to create a Sutro backend * [Console](/docs/getting-started/sutro-console) - Use the web console interface * [Studio](/docs/getting-started/studio) - Use the visual Studio interface * [SLang](/docs/SLang/introduction) - Define your backend using SLang # Builders Source: https://docs.withsutro.com/docs/getting-started/auth/builders Configuring the system for Builders **Builders** are end users or clients who build and run apps that integrate with Sutro. They are managed by your organization (via [Members](/docs/getting-started/auth/members)), not Sutro directly. To support your own user base, you'll need to configure certificates for both **JWT verification** and **mTLS security**. Learn more about [JSON Web Tokens (JWTs)](/docs/getting-started/auth/jwts) and [Mutual TLS (mTLS)](/docs/getting-started/auth/mutual-tls). ## JWT verification The Sutro API verifies JWTs that your system generates and includes in requests from your Builders. ### Required claims Every JWT must include the following claims: | Claim | Description | | ----- | ------------------------------------------------------------- | | `sub` | The security ID (SID) associated with the user in your system | | `iss` | The issuer SID previously registered with the UAPI | | `aud` | Must include `https://sapi.withsutro.com` | JWTs must be signed using the **RS256** algorithm. The public key used to verify signatures must be preregistered with the **User Management API (UAPI)**. ### Configuration Two elements are needed for JWT verification: 1. **Register an Issuer SID** 2. **Register a Verification Certificate** #### 1. Register an issuer SID Issuer SIDs identify and verify the source of JWTs. * Each SID must be globally unique and comply with [RFC 7519](https://www.rfc-editor.org/rfc/rfc7519#page-9). * In practice, use a **UUID** or a **URI** containing a domain you own. * Multiple issuer SIDs can be registered if needed. #### 2. Register a verification certificate JWTs signed with RS256 require a matching **public certificate** to be registered with the UAPI. Once registered, that certificate can be linked to one or more issuer SIDs. You hold the private key; Sutro never stores it. Register only the public certificate. ## mTLS security **Mutual TLS (mTLS)** adds another layer of authentication, requiring clients to present a certificate for every request. This uses public-private key pairs: the client signs each request with its private key, and Sutro verifies it using the corresponding public certificate registered via the UAPI. ### Configuration Sutro can generate mTLS certificates for you. * Certificates are signed by Sutro's private Certificate Authority. * The **public certificate** is stored by Sutro; the **private key** is available only once at generation. * Certificates expire after **90 days**. Automatic renewal of mTLS certificates will be available in an upcoming release. ## Summary | Security Layer | What You Do | Managed In | | ------------------- | ------------------------------------------------ | ---------- | | JWT Verification | Register issuer SID and verification certificate | UAPI | | mTLS Security | Upload or generate client certificate | UAPI | | Certificate Renewal | Manual (auto-renew coming soon) | UAPI | # How to secure connections Source: https://docs.withsutro.com/docs/getting-started/auth/how-to-secure-connections Authenticate as an organization member, initialize signing keys, create a Builder, and generate a Builder JWT to call the Frontend API. ## Before you begin **Roles & credentials** * Organization member credentials for the **Sutro API** (email and password). **Tools** * `curl`, `jq`, `uuidgen`, and the `jwt` CLI. * Node.js (optional) if you prefer the JavaScript example. * UNIX shell (macOS/Linux) or WSL on Windows. **Variables you'll need** * `` — Email for an organization member. * `` — Password for that account. * `` — Friendly name for the certificate to generate (e.g., "Staging key"). * `` — Issuer string to embed in Builder JWTs (e.g., your org slug or auth issuer). All placeholders appear in **angle brackets** and must be replaced before running commands. ## Steps Sutro walks you through each credential step so you stay in charge of the entire security chain—from login to Builder-issued tokens—with Sutro validating every move. Use your organization member credentials to obtain an access token. ```sh theme={null} curl -H "Content-Type: application/json" \ -X POST \ -d '{"email":"","password":""}' \ -o auth.json \ https://sapi.withsutro.com/login # Store the access token for subsequent requests ORG_MEMBER_JWT=$(jq -r '.access_token' < auth.json) ``` ```javascript theme={null} const user = process.env.ORG_MEMBER_EMAIL const password = process.env.ORG_MEMBER_PASSWORD; const { access_token: memberJwt } = await fetch( "https://sapi.withsutro.com/login", { method: "POST", body: JSON.stringify({ user, password }), headers: { "Content-Type": "application/json" }, } ).then((x) => x.json()); ``` | Placeholder | Meaning | | ----------------------- | ------------------------------------------------- | | `` | Email of an organization member with login access | | `` | Password for that account | Provision a certificate and private key for signing Builder JWTs. ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer ${ORG_MEMBER_JWT}" \ -X POST \ -d '{"commonName": $COMMON_NAME, "jwtIssuer": $JWT_ISSUER}' \ -o certs.json \ https://sapi.withsutro.com/initialization # Save the certificate and private key to files and capture the certificate ID and API Client Identifier CERTIFICATE_ID=$(jq -r '.certificate.id' < certs.json) API_CLIENT_IDENTIFIER=$(jq -r '.apiClientIdentifier' < certs.json) jq -r '.privateKey' < certs.json > mtls.key jq -r '.certificate.content' < certs.json > mtls.crt ``` ```javascript theme={null} const { certificate: {id: certificateId, content: certificate}, privateKey, apiClientIdentifier } = await fetch( "https://sapi.withsutro.com/initialization", { method: "POST", body: JSON.stringify({"commonName": process.env.COMMON_NAME, "jwtIssuer": process.env.JWT_ISSUER}), headers: { "Authorization": `Bearer ${memberJwt}`, "Content-Type": "application/json" }, } ).then((x) => x.json()); ``` | Placeholder | Meaning | | --------------- | ---------------------------------------------------------------- | | `` | Friendly label for the certificate (e.g., "Production key") | | `` | The value you expect to place in the `iss` claim of Builder JWTs | > The file `mtls.key` contains your **private key**. Store it securely and restrict file permissions. Create a Builder and record its `sid`. You'll use this value as the JWT subject (`sub`). ```sh theme={null} BUILDER_SID=$(uuidgen) curl -H "Content-Type: application/json" \ -H "Authorization: Bearer ${ORG_MEMBER_JWT}" \ -X POST \ -d "{\"sid\": \"$BUILDER_SID\"}" \ -o builder.json \ https://sapi.withsutro.com/builders ``` ```javascript theme={null} const builderSid = crypto.randomUUID(); const { id: builderId } = await fetch( "https://sapi.withsutro.com/builders", { method: "POST", body: JSON.stringify({"sid": builderSid}), headers: { "Authorization": `Bearer ${memberJwt}`, "Content-Type": "application/json" }, } ).then((x) => x.json()); ``` > **Important:** The JWT `sub` **must equal** the Builder's `sid`. Use the `jwt` CLI to sign a short-lived access token with your private key. ```sh theme={null} # Generate a signed Builder JWT (1 hour expiration) BUILDER_JWT=$(jwt encode --secret @mtls.key \ -A RS256 \ --iss "$JWT_ISSUER" \ --sub "$BUILDER_SID" \ --aud "https://sapi.withsutro.com" \ --jti $(uuidgen) \ --exp=$(($(date +%s) + 3600))) echo "${BUILDER_JWT}" ``` | Field | Meaning | | ----- | -------------------------------------------------------- | | `iss` | Must match `` you set during initialization | | `sub` | Must equal the Builder's `sid` (`${BUILDER_SID}`) | | `aud` | Audience of the Sutro API: `https://sapi.withsutro.com` | | `exp` | Expiration time (Unix seconds). The example uses 1 hour. | If you prefer Node.js: ```javascript theme={null} import crypto from "node:crypto"; import jwt from "jsonwebtoken"; import fs from "node:fs"; const privateKey = fs.readFileSync("mtls.key", "utf8"); const builderSid = process.env.BUILDER_SID; // set from the previous step const issuer = process.env.JWT_ISSUER; // set to const accessToken = jwt.sign( {}, privateKey, { algorithm: "RS256", expiresIn: "1h", jwtid: crypto.randomUUID(), audience: "https://sapi.withsutro.com", subject: builderSid, issuer, } ); console.log(accessToken); ``` > Set `BUILDER_SID` and `JWT_ISSUER` in your environment before running the script. * Inspect claims and signature at [https://jwt.io/](https://jwt.io/). * Your public certificate is in `mtls.crt` (PEM). ```sh theme={null} # View the PEM-encoded public certificate cat mtls.crt ``` Your organization keys and Builder JWT flow are locked down—keep building knowing every API call is authenticated and auditable. ## Reference * **POST `/login`** — Exchange organization member credentials for a JWT used to administer your organization. * **POST `/initialization`** — Provision a certificate and private key used to sign Builder JWTs. * **POST `/builders`** — Create a Builder and obtain its `sid`. * **Builder JWT claims** — `iss` (issuer), `sub` (Builder `sid`), `aud` (`https://sapi.withsutro.com`), `jti`, `exp`. ## Next steps * [Build a full-stack app](/docs/getting-started/building-full-stack-apps) using your Builder JWT * Review the [API Reference](/api-reference/projects/get-a-list-of-projects) for all available endpoints # JSON Web Tokens (JWTs) Source: https://docs.withsutro.com/docs/getting-started/auth/jwts Understanding how JWTs work in Sutro's authentication system **JSON Web Tokens (JWTs)** are compact, signed tokens that carry identification and authorization information. A JWT contains three parts: * **Header** — how the token is constructed * **Payload** — identity and other claims * **Signature** — proof that the token is genuine Within the payload, the **subject (`sub`) claim** identifies the user or entity: ```json theme={null} { "sub": "123-45-6789" } ``` This value is a **Security Identifier (SID)** that uniquely represents an identity. ## Signing and Verification JWTs are signed so that recipients can verify they have not been tampered with. Verification is done by checking that the signature matches the payload using a corresponding verification key. ## Symmetric vs Asymmetric Keys JWTs can be signed using: * **Symmetric keys** — one shared key used for both signing and verifying * **Asymmetric keys** — a private key for signing and a public key for verification Symmetric keys create risk: anyone who can verify a token can also forge one.\ Asymmetric keys avoid this. The signing private key never leaves your control, and we only receive the public verification key. ## Why Asymmetric Keys and JWTs? While [Mutual TLS (mTLS)](/docs/getting-started/auth/mutual-tls) proves *which server* is sending a request, it does not tell us *which user* the server is acting on behalf of. JWTs fill this gap by conveying identity and permission information for individual [Builders](/docs/getting-started/auth/builders) and [Members](/docs/getting-started/auth/members). Asymmetric JWT verification is used because: * You keep the private signing key, maintaining full control over user management. * Sutro only needs the public key, ensuring verification is possible without ever being able to forge tokens. * Each authentication service or environment can have its own key pair, making token origin traceable. This separation—[mTLS](/docs/getting-started/auth/mutual-tls) for server identity, JWTs for user identity—provides strong, flexible, and auditable security. # Managing organization members Source: https://docs.withsutro.com/docs/getting-started/auth/members How to invite, approve, and manage members in your Sutro organization. **Members** are users within your organization who can access the Sutro Console. They can review usage, manage [Builders](/docs/getting-started/auth/builders), and configure certificates for verifying Builder requests. When Sutro is first configured, a **root account** is created for initial setup and administration. From there, you can add additional members using one of the methods below. ## Authentication flow Members authenticate using JWTs issued by the **Sutro Auth Server**: 1. Members log in via the **Sutro Auth Server** using their credentials. * Currently supports **username/password** authentication. * Future releases will include SSO and identity provider integration. 2. Upon successful login, the Auth Server issues a [JSON Web Token (JWT)](/docs/getting-started/auth/jwts). * Include this token in the `Authorization` header of all API requests. ## Add members ### 1. Invite by email Invite members directly via email. The invitation includes a setup link. Once they create their account, they're automatically added to your organization. This is the simplest and most controlled onboarding method. ### 2. Self-signup Allow users to register without an invitation. By default, self-signed users have no access until they're approved or belong to a pre-registered domain. ## Approve members ### Automatic approval Users are automatically added to your organization if: * Their email matches a **pending invitation**, or * Their domain is already **registered and verified**. Any matching invitations are automatically marked as accepted. ### Manual approval If a user signs up without an invitation or verified domain, a **member** with the proper permissions must approve them manually. Only members with authorization can approve new members. ## Member domains You can automatically approve members from trusted domains by registering those domains with the **User Management API (UAPI)**. 1. Register your domain using the UAPI. 2. Add the DNS record provided by the API to verify ownership. 3. Once verified, users with matching email domains are automatically approved. DNS verification can take some time depending on propagation speed. ## Summary | Method | Description | Requires Manual Approval | | ------------------------------- | ---------------------------------------------------- | ------------------------ | | Email Invitation | Invite users via email; link adds them automatically | No | | Self-Signup (Verified Domain) | User registers with verified domain | No | | Self-Signup (Unverified Domain) | User registers manually | Yes | | Member Domain Registration | Automatically approves users from trusted domains | No | # Mutual TLS (mTLS) Source: https://docs.withsutro.com/docs/getting-started/auth/mutual-tls Understanding how mTLS works in Sutro's authentication system TLS (formerly SSL) is the standard protocol for verifying a **server's** identity and encrypting communication.\ In traditional TLS: * The **server** sends its certificate. * The **client** verifies it against a trusted Certificate Authority (CA). * The client then trusts that the server is genuine. **mTLS extends this by requiring both sides to present certificates.** With mTLS: * The **client** sends its own certificate, signed by a trusted CA. * The **server** verifies this certificate and checks that the client controls the private key associated with it. This provides strong, cryptographic proof that the request is coming from a trusted system. ## Why mTLS? Servers that can call our APIs operate with high privilege.\ mTLS ensures that: * Only systems you explicitly trust can connect to us. * Each client environment can have its own certificate, improving auditability. * Private keys stay entirely under your control; we never see them. This approach supports a **Zero Trust Architecture (ZTA)**, where no system is implicitly trusted and every request must be identified, authenticated, and authorized. # Authentication overview Source: https://docs.withsutro.com/docs/getting-started/auth/overview Understand how Sutro authenticates Members and Builders using JWTs and mTLS, and learn how API requests are validated ## Users Sutro can be accessed by two main types of users: 1. **[Members](/docs/getting-started/auth/members)**: Users within your organization who can access the Sutro Console. They can review usage, manage Builders, and configure certificates for verifying Builder requests. 2. **[Builders](/docs/getting-started/auth/builders)**: End users or clients who build and run apps that integrate with Sutro. ## Certificates Our security model relies on two complementary mechanisms: 1. [Mutual TLS (mTLS)](/docs/getting-started/auth/mutual-tls) ensures that only trusted servers can call our APIs. 2. [JSON Web Tokens (JWTs)](/docs/getting-started/auth/jwts) ensure that only authorized Builders can access the resources they are allowed to use. Sutro relies on **mTLS** for all server-to-server communication and **JWTs** for all user-level access control. This separation provides strong, flexible, and auditable security. ## What happens during validation During request processing we confirm the JWT is well-formed, that it targets the Sutro API, and that (for Builder traffic) the request arrives over mutual TLS. When all validation points pass, we continue execution; otherwise the request is rejected. * The request must include a JWT that is well-formed. * Malformed or missing tokens are rejected before any additional checks run. * The `aud` claim must equal `"https://sapi.withsutro.com"`. * The `iss` claim must map to an issuer that the organization has previously registered with Sutro. * Sutro looks up the public certificate associated with the issuer. * The JWT's signature must verify against that certificate; if it fails, the request is denied. * The `sub` claim must resolve to a known Member or Builder. * That principal must belong to the customer sending the request. * If the SID represents a Builder, the request must arrive over mTLS. * The presented client certificate must match the Builder's certificate stored with Sutro. When all stages succeed, Sutro marks the request as authenticated and forwards it to the requested endpoint. ### Quick reference | Check | Requirement | | -------------------- | ------------------------------------------------------------------------------------------------- | | **JWT structure** | Must be well-formed; malformed or missing tokens are rejected | | **Audience (`aud`)** | Must equal `"https://sapi.withsutro.com"` | | **Issuer (`iss`)** | Must map to a registered issuer for your organization | | **Signature** | Must verify against the public certificate associated with the issuer | | **Subject (`sub`)** | Must resolve to a known Member or Builder belonging to your organization | | **Builder mTLS** | If the subject is a Builder, the request must arrive over mTLS with a matching client certificate | ## Next steps Ready to set up authentication for your application? Follow our step-by-step guide to [secure your connections](/docs/getting-started/auth/how-to-secure-connections). # How-to: Prompt to full-stack Source: https://docs.withsutro.com/docs/getting-started/building-full-stack-apps How to generate and publish a full-stack app from a prompt. ## Overview This guide walks through the full workflow, from authentication to publishing, using the Sutro API to build a full-stack application from a prompt. This guide will work for any of Sutro's APIs. ## Before you begin ### Tools * `jq` and `curl` ### Security bundle Download `security-bundle.zip` from the [Sutro Console](https://console.withsutro.com) during onboarding. Extract it and run all commands from that directory. The bundle includes your API client credentials (`apiClient.id`, `mtls.key`, `mtls.crt`), the Sutro CA certificate (`ca.crt`), and a pre-generated Builder JWT (`builder.jwt`) valid for 45 days. The test bundle creates a **test builder** for quick API testing—not for production. See [How to Secure Connections](/docs/getting-started/auth/how-to-secure-connections) for production setup. ### Verify your connection Test that your credentials work by calling the hello endpoint: ```sh theme={null} curl -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ https://sapi.withsutro.com/hello ``` You should see a response confirming your API client, Builder, and organization. ## Steps Sutro takes you through every stage, from prompts to production, so you retain end-to-end visibility while Sutro does the heavy lifting. The first step is to create a new project. A project is like the container for your application, and it can have multiple components: * `backend`: A backend API hosted by Sutro * `frontend`: An optional frontend web application, hosted by Sutro, or exported as static bundle The `components` array controls what gets generated. If omitted, only `["backend"]` is created by default. Since we're building a full-stack app, we explicitly request both `backend` and `frontend`. It's currently not possible to create a standalone frontend project. Call [`POST /projects`](/api-reference/projects/create-a-new-project) ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X POST \ -o project.json \ -d '{ "name": "My New Project", "components": ["backend", "frontend"] }' \ "https://sapi.withsutro.com/projects" ``` Congratulations! You've just created your first Sutro Project. The project details are stored in `project.json`; refer to that file in upcoming steps. Next, create an empty application within your project. This application will serve as the container for your generated code. Call [`POST /projects/{projectId}/applications`](/api-reference/applications/create-a-new-application) ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X POST \ -o application.json \ -d '{ "scode": {} }' \ "https://sapi.withsutro.com/projects/$(jq -r '.id' < project.json)/applications" ``` Now you have an Application; next attach a prompt to it. Attach a prompt to the application that describes what you want to build. This prompt will be used during the generation process. Call [`POST /applications/{applicationId}/attachments`](/api-reference/attachments/attach-a-file). ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X POST \ -d '{ "type": "PROMPT", "prompt": "A todo app where users can create, edit, and delete tasks. Users should be able to mark tasks as complete and filter by status." }' \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)/attachments" ``` The prompt is attached and the Application is ready to generate. Generating an application takes a little time, so call the Sutro API to *start* the process and monitor it in the next step. This will automatically use the prompt that was attached to this specific application. Because you selected the `backend` and `frontend` components when creating the project, this will first generate a backend API, and then a frontend web application based on the prompt you attached. Call [`POST /applications/{applicationId}/generate`](/api-reference/applications/generate-application). ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X POST \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)/generate" ``` This call returns quickly; your application is being generated. Because `curl` drives this guide, poll the API for the application's status. The `-s` flag limits output to the Application status, so unexpected text may signal local network issues. Call [`GET /applications/{applicationId}/status`](/api-reference/applications/gets-the-current-status-of-the-application). ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -s \ -X GET \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)/status" | jq ``` Make this call every \~10 seconds until the status shows completion. Once the status shows `"active"`, your application has been successfully generated and published. Now that your application has been published, you can get the URL where it's accessible. Call [`GET /applications/{applicationId}`](/api-reference/applications/get-an-application-by-id) to retrieve the application details, including the public URL. ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -s \ -X GET \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)" | jq ``` The response includes the application details, including the URL where your frontend application is accessible. You can now open this URL in your browser to view and interact with your published full-stack application. The deployment response includes a `url` field with the full URL of your deployed backend API, which is accessible at: ``` https://{applicationId}.app.withsutro.com/api/v{version}/ ``` Replace `{applicationId}` with your application ID (from `application.json`). Your application is published, versioned, and ready for teammates or customers to explore. Share the URL with confidence! ## Self-hosting the frontend Instead of using Sutro's hosted frontend, you can export a static bundle and serve it from your own infrastructure. This gives you complete control over hosting, CDN configuration, and deployment pipelines. When self-hosting the frontend, your frontend will make requests to the Sutro-hosted backend from a different origin. You need to configure CORS to allow these requests. Call [`PATCH /applications/{applicationId}/cors`](/api-reference/applications/update-cors-configuration) ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X PATCH \ -d '{ "allowedOrigins": ["http://localhost:8080"] }' \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)/cors" ``` For production, replace `http://localhost:8080` with your actual domain (e.g., `https://app.yourdomain.com`). You can include multiple origins in the array. You can verify the current CORS configuration by calling `GET /applications/{applicationId}/cors`. Download the production-ready frontend as a static bundle (HTML, CSS, JavaScript, and assets). Call [`GET /applications/{applicationId}/frontendBundle`](/api-reference/deployments-assets/download-frontend-bundle) ```sh theme={null} curl -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ --output frontend-bundle.zip \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)/frontendBundle" ``` The downloaded zip contains everything needed to serve your frontend from any static file server. Extract the bundle and serve it with any static file server. Here's how to test locally using `http-server`: ```sh theme={null} # Extract the bundle unzip frontend-bundle.zip -d frontend # Install http-server if you don't have it npm install -g http-server # Serve the frontend on port 8080 http-server frontend -p 8080 ``` Open `http://localhost:8080` in your browser to see your application running locally against the Sutro-hosted backend. Make sure the port matches the origin you configured in the CORS settings. If you're using a different port, update the CORS configuration accordingly. ## Reference * [Create a project](/api-reference/projects/create-a-new-project) * [Create an application](/api-reference/applications/create-a-new-application) * [Attach a prompt](/api-reference/attachments/attach-a-file) * [Generate application](/api-reference/applications/generate-application) * [Get application status](/api-reference/applications/gets-the-current-status-of-the-application) * [Get application](/api-reference/applications/get-an-application-by-id) * [Update CORS configuration](/api-reference/applications/update-cors-configuration) * [Export frontend bundle](/api-reference/deployments-assets/download-frontend-bundle) # Sutro CLI quickstart Source: https://docs.withsutro.com/docs/getting-started/cli-quickstart Create, preview, validate, and publish a SLang backend with the Sutro CLI. ## Overview The Sutro CLI is the fastest way to build a SLang backend from your local editor. You write `.slang` files locally, and Sutro runs validation, preview, and publish workflows on the hosted Sutro backend. In this guide, you'll: * Install the CLI. * Log in with your Sutro account. * Link a local folder to a Sutro Project and Application. * Run a remote dev session with live reload. * Validate and publish the backend. ## Before you begin You need: * Node.js 22 or later. * npm, pnpm, or yarn. * A Sutro account. Publishing requires a payment method on file. You can add one in [Sutro Studio](https://studio.withsutro.com/) or [Sutro Console](https://console.withsutro.com/). ## Steps Install the CLI globally: ```sh npm theme={null} npm install --global @sutro-dev/sutro-cli ``` ```sh pnpm theme={null} pnpm add --global @sutro-dev/sutro-cli ``` ```sh yarn theme={null} yarn global add @sutro-dev/sutro-cli ``` Confirm that the `sutro` command is available: ```sh theme={null} sutro --version ``` Start the browser-based login flow: ```sh theme={null} sutro login ``` The CLI opens Sutro Studio in your browser. After login completes, the CLI stores a local session for future commands. If your environment cannot open a browser automatically, print the login URL instead: ```sh theme={null} sutro login --no-open ``` Create a new folder and initialize it with Sutro: ```sh theme={null} mkdir task-api cd task-api sutro init --name "Task API" ``` `sutro init` creates a remote Project and Application, writes `sutro.config.json`, and creates `app.slang` if it does not exist. To link an existing Application instead, pass its ID: ```sh theme={null} sutro init --application-id ``` Replace the generated `app.slang` with a small task API: ```slang theme={null} entity Task fields title: TEXT completed: BOOLEAN action CreateTask(title: TEXT): Task body return create Task { title := title completed := false } action ListTasks(): Page body return pageOf Task trigger CreateTask on HttpRequest endpoint POST /tasks arguments title := @request.body.title trigger ListTasks on HttpRequest endpoint GET /tasks ``` Start the preview server: ```sh theme={null} sutro dev ``` The CLI creates a remote dev session, uploads your local `.slang` files, and prints a preview API URL: ```text theme={null} Remote dev session ready. url: https://dev-.app.withsutro.com/api/latest/ session: version: 1.0.1 files: 1 ``` Keep this command running while you edit. When a `.slang` file or `sutro.config.json` changes, the CLI uploads the latest source and refreshes the remote preview. Press Ctrl + C to stop the dev session. Open a second terminal and call the URL printed by `sutro dev`: ```sh theme={null} export SUTRO_DEV_API="https://dev-.app.withsutro.com/api/latest" curl -X POST "$SUTRO_DEV_API/tasks" \ -H "Content-Type: application/json" \ -d '{"title":"Write CLI docs"}' curl "$SUTRO_DEV_API/tasks" ``` Replace `` with the value printed by `sutro dev`. Run validation before publishing: ```sh theme={null} sutro validate ``` The CLI uploads the local SLang source to Sutro for validation and prints compiler diagnostics if the project does not compile. Publish the linked Application: ```sh theme={null} sutro publish ``` The CLI uploads the local SLang source, publishes the Application, and prints the published API URL and version. Check the linked Application: ```sh theme={null} sutro status ``` Save the published OpenAPI spec: ```sh theme={null} sutro openapi --out openapi.json ``` You now have a local SLang project linked to Sutro, a remote dev preview, and a published backend API. ## Learn more * [CLI command reference](/docs/cli/command-reference) * [Project configuration](/docs/cli/project-config) * [Introduction to SLang](/docs/SLang/introduction) * [SLang data modeling](/docs/SLang/data-modeling) # Prompt to full-stack overview Source: https://docs.withsutro.com/docs/getting-started/prompt-to-full-stack-overview Generate and publish complete full-stack applications from a single prompt The Sutro API supports generating complete full-stack applications (both backend and frontend) from a single natural language prompt. This allows you to go from idea to published application in minutes. ## What you can do With Prompt to full-stack, you can: * Generate both backend APIs and frontend interfaces from a single prompt * Publish complete applications ready for production use * Iterate on your application using natural language * Manage the entire application lifecycle through the Sutro API ## How it works 1. Create a project with both backend and frontend components 2. Provide a natural language description of your application 3. Sutro generates the backend API and frontend interface 4. Publish and access your complete application [Learn how to build a full-stack app](/docs/getting-started/building-full-stack-apps) ## Related * [Prompt to backend](/docs/backend/prompt-to-backend) - Generate just the backend API * [Prompt to frontend](/docs/frontend/prompt-to-frontend) - Modify and iterate on frontends # Requests, responses & errors Source: https://docs.withsutro.com/docs/getting-started/requests-responses-errors Request format, response handling, and error codes for the Sutro API. ## Request format All Sutro endpoints follow REST principles and use standard HTTP methods (`GET`, `POST`, `PUT`, `DELETE`). Most requests return a response within milliseconds containing the result of the requested action. ### Long-running operations Some operations—such as generating an application from uploaded attachments—take longer to complete. Sutro uses a **Request–Monitor–Retrieve** pattern for long-running operations: 1. **Request** — Send a standard HTTP request to start the action. The API responds immediately, confirming that the operation has begun. 2. **Monitor** — Poll a status endpoint to check progress. Continue polling until the status returns `Complete`. 3. **Retrieve** — Once complete, send a follow-up request to the specified endpoint to obtain the final results. Webhooks coming soon. With webhooks, polling won't be necessary and Sutro will notify you automatically when an action completes. ## Response format Sutro follows REST conventions for responses. Successful requests return `2xx` status codes with JSON payloads containing the requested data or operation confirmation. ## Error codes ### 4xx – Client errors These indicate an issue with the request itself. | Status | Meaning | How to fix | | ------------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | **400** | Invalid request body or parameters. | Review request data and correct any formatting or validation issues. | | **401** | Authentication missing or invalid. | Include valid credentials or refresh expired tokens. | | **403** | Authenticated but not authorized. | Use credentials with sufficient permissions. | | **404** | Resource not found or not visible to user. | Confirm the resource exists and that you have permission to access it. | | **405 / 406** | Invalid request method or unacceptable format. | Review API documentation for supported verbs and content types. | | **409** | Request conflicts with current resource state (e.g., trying to remove an active mTLS certificate). | Adjust the resource state first, then retry. | | **429** | Rate limit exceeded. | Wait until the limit resets before retrying. | ### 5xx – Server errors These indicate an issue on Sutro's side. | Status | Meaning | What to do | | ----------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------ | | **500–599** | Internal system errors or service outages. | These are automatically logged by Sutro. Contact support if you need details or an ETA for resolution. | Always log both the HTTP status and the error payload from the response. This helps you debug client-side issues and improves support turnaround if you need to escalate. # Quickstart Source: https://docs.withsutro.com/docs/getting-started/slang-quickstart Get started with Sutro by creating your first backend using Studio or the CLI. ## Overview This quickstart shows two ways to create your first backend with Sutro: * **Studio**: Build a backend visually in the browser. * **Sutro CLI**: Write SLang locally, preview it in a remote dev session, and publish it from your terminal. Choose the path that fits how you want to work. ## Option 1: Using Studio Studio is the simplest way to start without writing code. Visit [Sutro Studio](https://studio.withsutro.com/). Use Studio to define: * Entities and relationships. * Actions and business logic. * Security rules. * HTTP endpoints. Publish directly from Studio when your backend is ready. ## Option 2: Using the Sutro CLI Use the CLI when you want to define your backend in SLang and edit it from your local development environment. If you're using an AI coding agent like [Claude Code](https://docs.anthropic.com/en/docs/claude-code), install the official SLang skill to give your agent full knowledge of SLang syntax: ```bash theme={null} npx skills add https://github.com/SutroOrg/sutro-skills --skill slang ``` ### Before you begin You need Node.js 22 or later, npm, and a Sutro account. Publishing requires a payment method on file. Add one in [Sutro Studio](https://studio.withsutro.com/) or [Sutro Console](https://console.withsutro.com/) before publishing. ### Steps Install the npm package: ```sh theme={null} npm install --global @sutro-dev/sutro-cli ``` Start the browser-based login flow: ```sh theme={null} sutro login ``` Create and initialize a local project: ```sh theme={null} mkdir task-api cd task-api sutro init --name "Task API" ``` `sutro init` creates a remote Project and Application, writes `sutro.config.json`, and creates `app.slang` if it does not exist. Replace `app.slang` with a simple task API: ```slang theme={null} entity Task fields title: TEXT completed: BOOLEAN action CreateTask(title: TEXT): Task body return create Task { title := title completed := false } action ListTasks(): Page body return pageOf Task trigger CreateTask on HttpRequest endpoint POST /tasks arguments title := @request.body.title trigger ListTasks on HttpRequest endpoint GET /tasks ``` Start a remote dev session: ```sh theme={null} sutro dev ``` The CLI uploads your local `.slang` files and prints a preview URL: ```text theme={null} https://dev-.app.withsutro.com/api/latest/ ``` Keep `sutro dev` running while you edit. The CLI reloads the remote preview when local `.slang` files change. Validate the project: ```sh theme={null} sutro validate ``` Publish the backend: ```sh theme={null} sutro publish ``` The CLI prints the published API URL and version. You've created and published your first Sutro backend. ## Next steps * [Sutro CLI quickstart](/docs/getting-started/cli-quickstart) - Learn the complete CLI workflow. * [CLI command reference](/docs/cli/command-reference) - Review every command and option. * [Project configuration](/docs/cli/project-config) - Learn how `sutro.config.json` works. * [Introduction to SLang](/docs/SLang/introduction) - Understand SLang language constructs and features. * [Read the API reference](/api-reference/projects/get-a-list-of-projects) - Explore the lower-level Sutro API. # Sutro Studio Source: https://docs.withsutro.com/docs/getting-started/studio Use Sutro Studio to create and edit your backend in minutes ## Overview Studio is the simplest way to get started with Sutro. It's an online Playground environment where you can quickly create and edit your production-ready backend without writing code or managing infrastructure. ## What you can do With Studio, you can: * Create new backends visually through an intuitive interface * Edit existing backends without writing SLang directly * See changes take effect immediately * Manage your backend infrastructure without any operations work ## Getting started To access Studio, visit the [Sutro Console](https://console.withsutro.com) and navigate to Studio. You can start creating your backend in minutes. ## Related * [Welcome](/docs/getting-started/welcome) - Learn about all ways to create a Sutro backend * [SLang](/docs/SLang/introduction) - Define your backend using SLang directly * [SLang quickstart](/docs/getting-started/slang-quickstart) - Get started with SLang * [Building full-stack apps](/docs/getting-started/building-full-stack-apps) - Generate complete applications # Sutro Console Source: https://docs.withsutro.com/docs/getting-started/sutro-console Access and manage your Sutro projects, applications, and resources through the web console ## Overview The Sutro Console is a web-based interface where you can manage your Sutro projects, applications, and resources. It provides a visual way to interact with your backends, view usage, manage authentication, and configure your infrastructure. ## What you can do With the Sutro Console, you can: * **Manage projects**: Create and organize your projects and applications * **View applications**: See all your published backends and their status * **Monitor usage**: Track API usage and resource consumption * **Manage authentication**: Configure Members, Builders, and security settings * **Download security bundles**: Get your API credentials and certificates * **Access Studio**: Use the visual Studio interface to build backends ## Getting started Visit the [Sutro Console](https://console.withsutro.com) to get started. You'll need to sign in with your account to access your projects and resources. ## Related * [Welcome](/docs/getting-started/welcome) - Learn about all ways to create a Sutro backend * [Studio](/docs/getting-started/studio) - Use the visual Studio interface * [SLang](/docs/SLang/introduction) - Define your backend using SLang directly * [Authentication](/docs/getting-started/auth/overview) - Learn about managing authentication and security # Welcome to Sutro Source: https://docs.withsutro.com/docs/getting-started/welcome An introduction to Sutro and its use cases Sutro is a no-ops backend infrastructure for building production-ready backends, optimized for vibe coding platforms. You define a backend, including logic and security, Sutro runs it, scales it and migrates it without you having to do any infra operations work. ## How it works Think of Sutro like Supabase, but instead of defining just a database schema, you define your entire backend: | | Sutro | Supabase | | -------------------------- | --------------------------------------------------- | ----------------------- | | **Definition language** | SLang | SQL schema | | **What you define** | Entire backend, including logic and security | Database model only | | **What you get** | Complete backend infrastructure | Trivial endpoints | | **Infrastructure handled** | All backend infrastructure (runs, scales, migrates) | Database infrastructure | ## Creating a Sutro backend There are four ways to define and edit a Sutro backend: The simplest way to use Sutro. Quickly create and edit your backend in minutes. Write SLang locally, preview changes in a remote dev session, and publish from your terminal. Sutro's intuitive definition language for defining entities, logic, triggers, and security. A CRUD API for defining and making precise edits to Sutro backends without editing SLang directly. Use Sutro's built-in AI agents or your own to build and edit backends. SLang and the APIs are AI-optimized. Install the [official agent skill](https://github.com/SutroOrg/sutro-skills) to give your AI agent full SLang knowledge. To get started, check out our [quickstart guide](/docs/getting-started/slang-quickstart). ## Modular APIs Sutro also includes additional tools to help vibecode apps move from idea to production. * [**Prompt to backend**](/docs/backend/prompt-to-backend) - Generate backends with domain models, actions, and security rules * [**Prompt to frontend**](/docs/frontend/prompt-to-frontend) - Use prompts to modify and iterate on your frontend using natural language * [**Prompt to full-stack**](/docs/getting-started/building-full-stack-apps) - Generate & publish a full-stack app from a single prompt * [**Figma to code**](/docs/planning/figma-to-code) - Convert Figma designs into easy-to-use static code # How-to: Figma to code Source: https://docs.withsutro.com/docs/planning/figma-to-code How to turn Figma files into static HTML and CSS bundles. ## Before you begin ### Tools * `jq` and `curl` ### Security bundle Download `security-bundle.zip` from the [Sutro Console](https://console.withsutro.com) during onboarding. Extract it and run all commands from that directory. The bundle includes your API client credentials (`apiClient.id`, `mtls.key`, `mtls.crt`), the Sutro CA certificate (`ca.crt`), and a pre-generated Builder JWT (`builder.jwt`) valid for 45 days. The test bundle creates a **test builder** for quick API testing, not for production. See [How to Secure Connections](/docs/getting-started/auth/how-to-secure-connections) for production setup. ### Verify your connection Test that your credentials work by calling the hello endpoint: ```sh theme={null} curl -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ "https://sapi.withsutro.com/hello" ``` You should see a response confirming your API client, Builder, and organization. ## Steps Ship-ready bundles take a few deliberate moves, and each step keeps you in control of inputs and outputs throughout the journey. ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X POST \ -o project.json \ -d '{"name": "My Figma Project"}' \ "https://sapi.withsutro.com/projects" ``` **Response** (HTTP 201) ```json theme={null} { "id": "abc123", "name": "My Figma Project", "createdAt": "2025-01-15T10:30:00.000Z", "updatedAt": "2025-01-15T10:30:00.000Z" } ``` The project details are stored in `project.json`; refer to that file in upcoming steps. ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X POST \ -o application.json \ "https://sapi.withsutro.com/projects/$(jq -r '.id' < project.json)/applications" ``` **Response** (HTTP 201) ```json theme={null} { "id": "def456", "projectId": "abc123", "scode": {}, "status": "Initialized", "createdAt": "2025-01-15T10:31:00.000Z", "updatedAt": "2025-01-15T10:31:00.000Z" } ``` The application details are stored in `application.json`; refer to that file in upcoming steps. Retrieve the structure of your Figma file to locate frame IDs for code generation. ```sh theme={null} curl -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X GET \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)/figma/structure?projectLink=&pat=" | jq ``` Replace: * `` : your Figma file link (e.g. `https://www.figma.com/design/abc123/MyFile`) * `` : your Figma personal access token **Response** Returns a JSON structure of pages and frames with their IDs. ```json theme={null} { "fileName": "My Design File", "pages": [ { "id": "0:1", "name": "Page 1", "frames": [ { "id": "1:15", "name": "Landing Page", "type": "FRAME" } ] } ] } ``` Trigger the code generation for a specific frame in your Figma file. ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X POST \ -d '{ "fileKey": "", "frameId": "", "accessToken": "" }' \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)/figma/generate-static-code" ``` Replace: * `` : from your Figma URL (`/file//...`) * `` : from step 3 * `` : your Figma personal access token **Response** ```json theme={null} { "success": true } ``` The request creates a background job. Poll the application status endpoint to monitor the generation progress. ```sh theme={null} curl -H "Content-Type: application/json" \ -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -s \ -X GET \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)/status" | jq ``` **Possible responses** **Status: Generating** (Application generation in progress) ```json theme={null} { "applicationId": "def456", "status": "Generating" } ``` **Status: Active** (Generation complete) ```json theme={null} { "applicationId": "def456", "status": "Active" } ``` The application is ready. Proceed to step 6 to download the bundle. **Status: Failed** (Generation failed) ```json theme={null} { "applicationId": "def456", "status": "Failed" } ``` Once the application status is `Active`, download the generated code as a zip file. ```sh theme={null} curl -H "Authorization: Bearer $(cat builder.jwt)" \ -H "x-sutro-api-client: $(cat apiClient.id)" \ --cacert ca.crt \ --key mtls.key \ --cert mtls.crt \ -X GET \ -o application-bundle.zip \ "https://sapi.withsutro.com/applications/$(jq -r '.id' < application.json)/webBundle" ``` **Response** * **Content-Type**: `application/zip` * **Content-Disposition**: `attachment; filename="application--web-bundle.zip"` * **Body**: Binary zip file containing the generated HTML, CSS, and assets The zip file contains all the static files generated from your Figma design. You now have an exportable frontend bundle. Unzip it, drop it into your hosting pipeline, and show it off! # Figma to code overview Source: https://docs.withsutro.com/docs/planning/figma-to-code-overview Convert Figma designs into static HTML and CSS bundles The Sutro API supports converting Figma designs into pixel-perfect static HTML and CSS bundles. This allows you to bring your design mockups to life while maintaining visual fidelity to your original designs. ## What you can do With Figma to code, you can: * Convert Figma frames into static HTML/CSS code * Export complete web bundles ready to publish * Maintain design fidelity from Figma to code * Generate production-ready static sites ## How it works 1. Connect your Figma file to a Sutro project 2. Select the frames you want to convert 3. Generate static code bundles 4. Download and publish the generated HTML/CSS [Learn how to convert Figma designs to code](/docs/planning/figma-to-code) ## Example This example demonstrates how Sutro converts a Figma landing page design into a static HTML/CSS bundle. ### Input The source Figma file is a community landing page template available at [https://www.figma.com/community/file/1230604708032389430](https://www.figma.com/community/file/1230604708032389430). ### Result The original Figma design with all visual elements, typography, and layout. Full landing page design used as input for this Figma-to-code example The static web page bundle generated by Sutro, matching the design specifications. Static site bundle generated from Sutro (output) ### Live Demo View the published web page: [https://figma-to-code-example-landing-page-1.pages.dev/](https://figma-to-code-example-landing-page-1.pages.dev/)