> ## 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.

# Get Snippet

> Retrieves a single snippet by its ID. API Cost: 1 request.

## Overview

Retrieves a single snippet by its ID. This endpoint returns the complete snippet data including content, metadata, folder assignment, and timestamps.

**API Cost**: 1 request

## Code Examples

<CodeGroup>
  ```javascript JavaScript 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 getSnippet(snippetId) {
  	try {
  		const response = await axios.get(`${BASE_URL}/snippet`, {
  			headers: {
  				Authorization: `Bearer ${API_KEY}`,
  			},
  			params: {
  				id: snippetId,
  			},
  		});

  		console.log('Snippet:', response.data.data);
  		console.log('Remaining requests:', response.data.usage.remainingRequests);

  		return response.data;
  	} catch (error) {
  		if (error.response) {
  			console.error('Error:', error.response.data.message);
  			console.error('Status:', error.response.status);
  		} else {
  			console.error('Error:', error.message);
  		}
  		throw error;
  	}
  }

  // Usage
  getSnippet('550e8400-e29b-41d4-a716-446655440000');
  ```

  ```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 get_snippet(snippet_id):
      try:
          response = requests.get(
              f'{BASE_URL}/snippet',
              headers={'Authorization': f'Bearer {API_KEY}'},
              params={'id': snippet_id}
          )
          response.raise_for_status()

          data = response.json()
          print('Snippet:', data['data'])
          print('Remaining requests:', data['usage']['remainingRequests'])

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

  # Usage
  get_snippet('550e8400-e29b-41d4-a716-446655440000')
  ```

  ```bash cURL theme={null}
  curl -X GET "https://www.getsnippets.ai/api/prompts/snippet?id=550e8400-e29b-41d4-a716-446655440000" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```php PHP theme={null}
  <?php

  $apiKey = getenv('SNIPPETS_AI_API_KEY');
  $baseUrl = 'https://www.getsnippets.ai/api/prompts';

  function getSnippet($snippetId) {
      global $apiKey, $baseUrl;

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, "$baseUrl/snippet?id=$snippetId");
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, [
          "Authorization: Bearer $apiKey"
      ]);

      $response = curl_exec($ch);
      $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      curl_close($ch);

      $data = json_decode($response, true);

      if ($httpCode === 200) {
          echo "Snippet: " . json_encode($data['data']) . "\n";
          echo "Remaining requests: " . $data['usage']['remainingRequests'] . "\n";
          return $data;
      } else {
          echo "Error: " . $data['message'] . "\n";
          throw new Exception($data['message']);
      }
  }

  // Usage
  getSnippet('550e8400-e29b-41d4-a716-446655440000');
  ?>
  ```
</CodeGroup>

## Response Example

```json theme={null}
{
	"success": true,
	"data": {
		"id": "550e8400-e29b-41d4-a716-446655440000",
		"title": "Welcome Email Template",
		"content": {
			"type": "plaintext",
			"content": "Welcome to our platform! We're excited to have you."
		},
		"snippet_note": "Use for new user onboarding",
		"shortcut": "welcome_email",
		"folder_id": "660e8400-e29b-41d4-a716-446655440001",
		"team_id": "770e8400-e29b-41d4-a716-446655440002",
		"workspace_id": "880e8400-e29b-41d4-a716-446655440003",
		"is_archived": false,
		"created_at": "2024-01-15T10:30:00Z",
		"updated_at": "2024-01-20T14:45:00Z",
		"created_by": "990e8400-e29b-41d4-a716-446655440004"
	},
	"usage": {
		"remainingRequests": 99999
	}
}
```

## Use Cases

<AccordionGroup>
  <Accordion title="Fetching Prompt for Voice AI Integration">
    Retrieve a specific prompt variation for use in voice AI services like VAPI:

    ```javascript theme={null}
    async function getPromptForVoiceAgent(snippetId) {
      const response = await getSnippet(snippetId);
      const promptContent = response.data.content.content;
      
      // Use with VAPI or similar service
      const vapiCall = await initiateVoiceCall({
        systemPrompt: promptContent,
        phoneNumber: customerPhone
      });
      
      return vapiCall;
    }
    ```
  </Accordion>

  <Accordion title="Display in Application UI">
    Fetch snippet data to display in your application:

    ```javascript theme={null}
    async function displaySnippet(snippetId) {
      const response = await getSnippet(snippetId);
      const snippet = response.data;
      
      // Render in UI
      document.getElementById('snippet-title').textContent = snippet.title;
      document.getElementById('snippet-content').textContent = 
        snippet.content.content;
      document.getElementById('snippet-note').textContent = 
        snippet.snippet_note || 'No notes';
    }
    ```
  </Accordion>

  <Accordion title="Verify Snippet Exists Before Update">
    Check if a snippet exists before performing operations:

    ```javascript theme={null}
    async function safeUpdateSnippet(snippetId, updates) {
      try {
        // Verify snippet exists
        await getSnippet(snippetId);
        
        // Proceed with update
        return await updateSnippet(snippetId, updates);
      } catch (error) {
        if (error.response?.status === 404) {
          console.log('Snippet not found, creating new one');
          return await createSnippet(updates);
        }
        throw error;
      }
    }
    ```
  </Accordion>

  <Accordion title="Cache Frequently Accessed Snippets">
    Implement caching to reduce API calls:

    ```javascript theme={null}
    const cache = new Map();
    const CACHE_TTL = 5 * 60 * 1000; // 5 minutes

    async function getCachedSnippet(snippetId) {
      const cached = cache.get(snippetId);
      
      if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
        console.log('Cache hit - saved 1 API request');
        return cached.data;
      }
      
      const response = await getSnippet(snippetId);
      cache.set(snippetId, {
        data: response.data,
        timestamp: Date.now()
      });
      
      return response.data;
    }
    ```
  </Accordion>
</AccordionGroup>

## Error Handling

<CodeGroup>
  ```javascript Comprehensive Error Handling theme={null}
  async function getSnippetSafely(snippetId) {
  	try {
  		return await getSnippet(snippetId);
  	} catch (error) {
  		const status = error.response?.status;
  		const message = error.response?.data?.message;

  		switch (status) {
  			case 400:
  				throw new Error(`Invalid request: ${message}`);
  			case 401:
  				throw new Error('Invalid API key - check your authentication');
  			case 403:
  				throw new Error('Access denied - check team permissions');
  			case 404:
  				throw new Error(`Snippet ${snippetId} not found`);
  			case 429:
  				const retryAfter = error.response.headers['retry-after'];
  				throw new Error(`Rate limit exceeded. Retry after ${retryAfter}s`);
  			default:
  				throw new Error(`API error: ${message || 'Unknown error'}`);
  		}
  	}
  }
  ```

  ```python Error Handling with Retry theme={null}
  import time

  def get_snippet_with_retry(snippet_id, max_retries=3):
      for attempt in range(max_retries):
          try:
              return get_snippet(snippet_id)
          except requests.exceptions.HTTPError as e:
              if e.response.status_code == 429:
                  # Rate limit - wait and retry
                  retry_after = int(e.response.headers.get('Retry-After', 60))
                  if attempt < max_retries - 1:
                      print(f'Rate limited. Waiting {retry_after}s...')
                      time.sleep(retry_after)
                      continue
              elif e.response.status_code == 404:
                  print(f'Snippet {snippet_id} not found')
                  return None
              elif e.response.status_code in [401, 403]:
                  print(f'Authentication/permission error')
                  raise
              else:
                  raise

      raise Exception('Max retries exceeded')
  ```
</CodeGroup>

## Common Issues

<AccordionGroup>
  <Accordion title="404 Not Found">
    **Problem**: The snippet ID doesn't exist or was deleted.

    **Solution**:

    * Verify the snippet ID is correct
    * Check if the snippet was deleted
    * Ensure the snippet belongs to your workspace
  </Accordion>

  {' '}

  <Accordion title="403 Forbidden">
    **Problem**: Your API key doesn't have access to the snippet's team.
    **Solution**: - Check your API key's team permissions - Ensure the API key has
    access to the required team - Verify your workspace subscription is active
  </Accordion>

  <Accordion title="401 Unauthorized">
    **Problem**: Invalid or missing API key.

    **Solution**:

    * Check the Authorization header is properly formatted
    * Verify your API key is active
    * Ensure you're using `Bearer YOUR_API_KEY` format
  </Accordion>
</AccordionGroup>

## Best Practices

<Check>
  **Use caching** for frequently accessed snippets to reduce API calls
</Check>

<Check>**Implement error handling** for all possible error scenarios</Check>
<Check>**Store snippet IDs** persistently to avoid lookup operations</Check>
<Check>**Monitor usage** through the response's usage field</Check>

<Check>
  **Validate IDs** before making requests to avoid unnecessary API calls
</Check>

<Warning>
  Don't fetch snippets in tight loops without caching - this will quickly
  exhaust your API quota and hit rate limits.
</Warning>

## Related Endpoints

* [Get Multiple Snippets](/api-reference/snippets/get-snippets) - Fetch multiple snippets at once
* [Create Snippet](/api-reference/snippets/create-snippet) - Create a new snippet
* [Update Snippet](/api-reference/snippets/update-snippet) - Update an existing snippet
* [Get Snippet Variation](/api-reference/variations/get-variation) - Get a specific variation


## OpenAPI

````yaml GET /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:
    get:
      tags:
        - Snippets
      summary: Get a single snippet
      description: 'Retrieves a single snippet by its ID. API Cost: 1 request.'
      operationId: getSnippet
      parameters:
        - name: id
          in: query
          required: true
          description: The ID of the snippet to fetch
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: Snippet retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SnippetResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/RateLimitExceeded'
components:
  schemas:
    SnippetResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        data:
          type: object
          properties:
            id:
              type: string
              format: uuid
            title:
              type: string
            content:
              $ref: '#/components/schemas/SnippetContent'
            snippet_note:
              type: string
              nullable: true
            shortcut:
              type: string
              nullable: true
            folder_id:
              type: string
              format: uuid
              nullable: true
            team_id:
              type: string
              format: uuid
            workspace_id:
              type: string
              format: uuid
            is_archived:
              type: boolean
            created_at:
              type: string
              format: date-time
            updated_at:
              type: string
              format: date-time
        usage:
          $ref: '#/components/schemas/UsageInfo'
    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
    NotFound:
      description: Not Found - Requested resource does not exist
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            success: false
            message: Snippet not found
    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.

````