> ## Documentation Index
> Fetch the complete documentation index at: https://docs.getsnippets.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Create Snippet

> Creates a new snippet with optional variations and tags. API Cost: 1 request.

## Overview

Creates a new snippet with optional variations, folder assignment, and tags. This endpoint allows you to create structured snippets programmatically.

**API Cost**: 1 request

## Code Examples

<CodeGroup>
  ```javascript JavaScript - Basic Snippet theme={null}
  const axios = require('axios');

  const API_KEY = process.env.SNIPPETS_AI_API_KEY;
  const BASE_URL = 'https://www.getsnippets.ai/api/prompts';

  async function createSnippet(snippetData) {
  	try {
  		const response = await axios.post(`${BASE_URL}/snippet`, snippetData, {
  			headers: {
  				Authorization: `Bearer ${API_KEY}`,
  				'Content-Type': 'application/json',
  			},
  		});

  		console.log('Created snippet ID:', response.data.data.snippetId);
  		console.log('Remaining requests:', response.data.usage.remainingRequests);

  		return response.data;
  	} catch (error) {
  		console.error('Error:', error.response?.data || error.message);
  		throw error;
  	}
  }

  // Basic snippet
  const basicSnippet = {
  	title: 'My API Snippet',
  	content: {
  		type: 'plaintext',
  		content: "console.log('Hello, World!');",
  	},
  	teamId: 'your-team-id',
  };

  createSnippet(basicSnippet);
  ```

  ```javascript JavaScript - Full-Featured Snippet theme={null}
  // Snippet with all optional fields
  const fullSnippet = {
  	title: 'Customer Onboarding Email',
  	content: {
  		type: 'plaintext',
  		content: 'Dear {{customer_name}},\n\nWelcome to our platform!',
  	},
  	teamId: 'your-team-id',
  	note: 'Use this template for new customer onboarding',
  	shortcut: 'welcome_email',
  	folderId: 'folder-uuid',
  	tagIds: ['tag-uuid-1', 'tag-uuid-2'],
  	additionalVariations: [
  		{
  			content: {
  				type: 'plaintext',
  				content: 'Hola {{customer_name}},\n\n¡Bienvenido!',
  			},
  			variationName: 'Spanish Version',
  		},
  		{
  			content: {
  				type: 'plaintext',
  				content: 'Bonjour {{customer_name}},\n\nBienvenue!',
  			},
  			variationName: 'French Version',
  		},
  	],
  };

  createSnippet(fullSnippet);
  ```

  ```python Python theme={null}
  import os
  import requests

  API_KEY = os.environ.get('SNIPPETS_AI_API_KEY')
  BASE_URL = 'https://www.getsnippets.ai/api/prompts'

  def create_snippet(snippet_data):
      try:
          response = requests.post(
              f'{BASE_URL}/snippet',
              headers={
                  'Authorization': f'Bearer {API_KEY}',
                  'Content-Type': 'application/json'
              },
              json=snippet_data
          )
          response.raise_for_status()

          data = response.json()
          print(f"Created snippet ID: {data['data']['snippetId']}")
          print(f"Remaining requests: {data['usage']['remainingRequests']}")

          return data
      except requests.exceptions.HTTPError as e:
          print(f"Error: {e.response.json().get('message')}")
          raise

  # Basic snippet
  basic_snippet = {
      'title': 'My API Snippet',
      'content': {
          'type': 'plaintext',
          'content': 'print("Hello, World!")'
      },
      'teamId': 'your-team-id'
  }

  create_snippet(basic_snippet)
  ```

  ```bash cURL theme={null}
  curl -X POST "https://www.getsnippets.ai/api/prompts/snippet" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "title": "My API Snippet",
      "content": {
        "type": "plaintext",
        "content": "Hello, World!"
      },
      "teamId": "your-team-id",
      "note": "Created via API",
      "folderId": "folder-uuid",
      "tagIds": ["tag-uuid-1"]
    }'
  ```
</CodeGroup>

## Real-World Use Case: Voice AI Integration

Here's a complete example of creating prompts for a voice AI system (like VAPI):

```javascript theme={null}
async function createVoiceAgentPrompts(clientData) {
	const { clientName, industry, teamId, folderId } = clientData;

	// Create a snippet with multiple language variations
	const snippet = {
		title: `${clientName} - ${industry} Agent`,
		content: {
			type: 'plaintext',
			content: `You are a professional ${industry} assistant for ${clientName}. 
Your role is to help customers with inquiries, schedule appointments, 
and provide information about services. Be polite, professional, and helpful.`,
		},
		teamId: teamId,
		folderId: folderId,
		note: `Voice agent prompt for ${clientName}`,
		shortcut: `${clientName.toLowerCase()}_agent`,
		tagIds: [industryTagId, voiceAgentTagId],
		additionalVariations: [
			{
				content: {
					type: 'plaintext',
					content: `Eres un asistente profesional de ${industry} para ${clientName}.
Tu función es ayudar a los clientes con consultas, programar citas
y proporcionar información sobre servicios. Sé cortés, profesional y servicial.`,
				},
				variationName: 'Spanish Version',
			},
			{
				content: {
					type: 'plaintext',
					content: `You are handling after-hours calls for ${clientName}.
Inform customers of business hours and offer to schedule a callback
during office hours. Be understanding and helpful.`,
				},
				variationName: 'After Hours',
			},
		],
	};

	try {
		const response = await createSnippet(snippet);
		console.log(`✅ Created voice agent prompt: ${response.data.snippetId}`);
		console.log(`   Variations: ${response.data.metadata.totalVariations}`);

		return response.data.snippetId;
	} catch (error) {
		console.error(
			`❌ Failed to create prompt for ${clientName}:`,
			error.message
		);
		throw error;
	}
}

// Usage
createVoiceAgentPrompts({
	clientName: 'Dental Clinic ABC',
	industry: 'Healthcare',
	teamId: 'healthcare-team-id',
	folderId: 'dental-clients-folder-id',
});
```

## Response Example

```json theme={null}
{
	"success": true,
	"data": {
		"snippetId": "550e8400-e29b-41d4-a716-446655440000"
	},
	"usage": {
		"remainingRequests": 99999
	},
	"metadata": {
		"totalVariations": 3,
		"tagsAttached": 2
	}
}
```

## Validation Rules

<ParamField path="title" type="string" required>
  **Length**: 1-200 characters Cannot be empty or exceed 200 characters.
</ParamField>

<ParamField path="content" type="object" required>
  Must include `type` and `content` fields.

  ```json theme={null}
  {
    "type": "plaintext",
    "content": "Your content here"
  }
  ```
</ParamField>

<ParamField path="teamId" type="string" required>
  Must be a valid team ID that your API key has access to.
</ParamField>

<ParamField path="note" type="string">
  **Length**: 0-5000 characters (optional)
</ParamField>

<ParamField path="shortcut" type="string">
  **Length**: 0-100 characters (optional)
</ParamField>

<ParamField path="folderId" type="string">
  Must be a valid folder ID in the same team (optional)
</ParamField>

<ParamField path="tagIds" type="array">
  Array of valid tag IDs from the same team (optional)
</ParamField>

## Batch Creation

To create multiple snippets, use the [batch endpoint](/api-reference/snippets/create-snippets) instead:

```javascript theme={null}
// Instead of this (inefficient):
for (const snippetData of snippets) {
	await createSnippet(snippetData); // N API calls + N * rate limit issues
}

// Do this (efficient):
await createSnippets({ snippets }); // 1 API call, N request cost
```

## Error Handling

<CodeGroup>
  ```javascript Validation Error Handling theme={null}
  async function createSnippetSafe(snippetData) {
  	// Pre-validate before API call
  	if (!snippetData.title || snippetData.title.length === 0) {
  		throw new Error('Title is required');
  	}

  	if (snippetData.title.length > 200) {
  		throw new Error('Title cannot exceed 200 characters');
  	}

  	if (!snippetData.content) {
  		throw new Error('Content is required');
  	}

  	if (!snippetData.teamId) {
  		throw new Error('Team ID is required');
  	}

  	if (snippetData.note && snippetData.note.length > 5000) {
  		throw new Error('Note cannot exceed 5000 characters');
  	}

  	try {
  		return await createSnippet(snippetData);
  	} catch (error) {
  		const status = error.response?.status;
  		const message = error.response?.data?.message;

  		if (status === 400) {
  			throw new Error(`Validation error: ${message}`);
  		} else if (status === 403) {
  			if (message?.includes('team')) {
  				throw new Error('API key does not have access to this team');
  			} else if (message?.includes('folder')) {
  				throw new Error('Folder not found or not accessible');
  			} else if (message?.includes('tag')) {
  				throw new Error('One or more tags not found');
  			}
  		}

  		throw error;
  	}
  }
  ```
</CodeGroup>

## Best Practices

<Check>
  **Validate data before API calls** to catch errors early and save on API costs
</Check>

<Check>**Use meaningful titles** that make snippets easy to identify</Check>
<Check>**Add notes** to provide context for team members</Check>
<Check>**Organize with folders** and tags for better management</Check>

<Check>
  **Create variations** for different use cases (languages, contexts, etc.)
</Check>

<Warning>
  Always verify that folder IDs and tag IDs exist and belong to the correct team
  before creating snippets.
</Warning>

## Related Endpoints

* [Update Snippet](/api-reference/snippets/update-snippet) - Update an existing snippet
* [Create Multiple Snippets](/api-reference/snippets/create-snippets) - Batch create snippets
* [Get Snippet](/api-reference/snippets/get-snippet) - Retrieve a snippet
* [Create Folder](/api-reference/folders/create-folder) - Create a folder first


## OpenAPI

````yaml POST /snippet
openapi: 3.1.0
info:
  title: Snippets AI API
  description: >-
    A comprehensive API for managing snippets, folders, tags, and variations
    programmatically
  version: 1.0.0
  contact:
    name: Snippets AI Support
    email: team@getsnippets.ai
servers:
  - url: https://www.getsnippets.ai/api/prompts
    description: Production server
security:
  - bearerAuth: []
tags:
  - name: Snippets
    description: Operations for managing code snippets and text snippets
  - name: Variations
    description: Operations for managing snippet variations and version history
  - name: Folders
    description: Operations for organizing snippets into folders
  - name: Tags
    description: Operations for tagging and categorizing snippets
paths:
  /snippet:
    post:
      tags:
        - Snippets
      summary: Create a new snippet
      description: >-
        Creates a new snippet with optional variations and tags. API Cost: 1
        request.
      operationId: createSnippet
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateSnippetRequest'
      responses:
        '200':
          description: Snippet created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateSnippetResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '429':
          $ref: '#/components/responses/RateLimitExceeded'
components:
  schemas:
    CreateSnippetRequest:
      type: object
      required:
        - title
        - content
        - teamId
      properties:
        title:
          type: string
          maxLength: 200
          description: Title of the snippet
          example: My API Snippet
        content:
          $ref: '#/components/schemas/SnippetContent'
        teamId:
          type: string
          format: uuid
          description: ID of the team this snippet belongs to
        note:
          type: string
          maxLength: 5000
          description: Optional note for the snippet
        shortcut:
          type: string
          maxLength: 100
          description: Optional keyboard shortcut
        folderId:
          type: string
          format: uuid
          description: Optional folder ID to organize the snippet
        tagIds:
          type: array
          items:
            type: string
            format: uuid
          description: Optional array of tag IDs
        additionalVariations:
          type: array
          items:
            type: object
            required:
              - content
              - variationName
            properties:
              content:
                $ref: '#/components/schemas/SnippetContent'
              variationName:
                type: string
                example: Spanish Version
          description: Optional additional variations of this snippet
    CreateSnippetResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: object
          properties:
            snippetId:
              type: string
              format: uuid
        usage:
          $ref: '#/components/schemas/UsageInfo'
        metadata:
          type: object
          properties:
            totalVariations:
              type: integer
            tagsAttached:
              type: integer
    SnippetContent:
      type: object
      properties:
        type:
          type: string
          description: Content type (e.g., 'plaintext', 'code')
          example: plaintext
        content:
          type: string
          description: The actual content of the snippet
          example: Hello, world!
    UsageInfo:
      type: object
      properties:
        remainingRequests:
          type: integer
          description: Number of API requests remaining in your quota
    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        message:
          type: string
          description: Error message describing what went wrong
        error:
          type: string
          description: Additional error details
  responses:
    BadRequest:
      description: Bad request - Invalid parameters or malformed JSON
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            success: false
            message: Snippet ID is required
    Unauthorized:
      description: Unauthorized - Invalid or missing API key
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            success: false
            message: Invalid or inactive API key
    Forbidden:
      description: Forbidden - Insufficient permissions or quota exceeded
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            insufficient_quota:
              value:
                success: false
                message: >-
                  Insufficient API requests. This operation requires 5 requests
                  but you have 0 remaining.
                usage:
                  remainingRequests: 0
                  requiredRequests: 5
            no_access:
              value:
                success: false
                message: API key does not have access to this team
    RateLimitExceeded:
      description: Too Many Requests - Rate limit exceeded (20 requests per minute)
      headers:
        Retry-After:
          description: Number of seconds to wait before making another request
          schema:
            type: integer
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            success: false
            message: >-
              Rate limit exceeded. Too many requests from this API key. Try
              again in 120 seconds.
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >-
        API key authentication using Bearer token. Include your API key in the
        Authorization header.

````