Get a single snippet
curl --request GET \
--url https://www.getsnippets.ai/api/prompts/snippet \
--header 'Authorization: Bearer <token>'import requests
url = "https://www.getsnippets.ai/api/prompts/snippet"
headers = {"Authorization": "Bearer <token>"}
response = requests.get(url, headers=headers)
print(response.text)const options = {method: 'GET', headers: {Authorization: 'Bearer <token>'}};
fetch('https://www.getsnippets.ai/api/prompts/snippet', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://www.getsnippets.ai/api/prompts/snippet",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "https://www.getsnippets.ai/api/prompts/snippet"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", "Bearer <token>")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.get("https://www.getsnippets.ai/api/prompts/snippet")
.header("Authorization", "Bearer <token>")
.asString();require 'uri'
require 'net/http'
url = URI("https://www.getsnippets.ai/api/prompts/snippet")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = 'Bearer <token>'
response = http.request(request)
puts response.read_body{
"success": true,
"data": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"title": "<string>",
"content": {
"type": "plaintext",
"content": "Hello, world!"
},
"snippet_note": "<string>",
"shortcut": "<string>",
"folder_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"team_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"workspace_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"is_archived": true,
"created_at": "2023-11-07T05:31:56Z",
"updated_at": "2023-11-07T05:31:56Z"
},
"usage": {
"remainingRequests": 123
}
}Snippets
Get Snippet
Retrieves a single snippet by its ID. API Cost: 1 request.
GET
/
snippet
Get a single snippet
curl --request GET \
--url https://www.getsnippets.ai/api/prompts/snippet \
--header 'Authorization: Bearer <token>'import requests
url = "https://www.getsnippets.ai/api/prompts/snippet"
headers = {"Authorization": "Bearer <token>"}
response = requests.get(url, headers=headers)
print(response.text)const options = {method: 'GET', headers: {Authorization: 'Bearer <token>'}};
fetch('https://www.getsnippets.ai/api/prompts/snippet', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://www.getsnippets.ai/api/prompts/snippet",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "https://www.getsnippets.ai/api/prompts/snippet"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", "Bearer <token>")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.get("https://www.getsnippets.ai/api/prompts/snippet")
.header("Authorization", "Bearer <token>")
.asString();require 'uri'
require 'net/http'
url = URI("https://www.getsnippets.ai/api/prompts/snippet")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = 'Bearer <token>'
response = http.request(request)
puts response.read_body{
"success": true,
"data": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"title": "<string>",
"content": {
"type": "plaintext",
"content": "Hello, world!"
},
"snippet_note": "<string>",
"shortcut": "<string>",
"folder_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"team_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"workspace_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"is_archived": true,
"created_at": "2023-11-07T05:31:56Z",
"updated_at": "2023-11-07T05:31:56Z"
},
"usage": {
"remainingRequests": 123
}
}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 requestCode Examples
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');
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')
curl -X GET "https://www.getsnippets.ai/api/prompts/snippet?id=550e8400-e29b-41d4-a716-446655440000" \
-H "Authorization: Bearer YOUR_API_KEY"
<?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');
?>
Response Example
{
"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
Fetching Prompt for Voice AI Integration
Fetching Prompt for Voice AI Integration
Retrieve a specific prompt variation for use in voice AI services like VAPI:
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;
}
Display in Application UI
Display in Application UI
Fetch snippet data to display in your application:
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';
}
Verify Snippet Exists Before Update
Verify Snippet Exists Before Update
Check if a snippet exists before performing operations:
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;
}
}
Cache Frequently Accessed Snippets
Cache Frequently Accessed Snippets
Implement caching to reduce API calls:
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;
}
Error Handling
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'}`);
}
}
}
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')
Common Issues
404 Not Found
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
403 Forbidden
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
401 Unauthorized
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_KEYformat
Best Practices
Use caching for frequently accessed snippets to reduce API calls
Implement error handling for all possible error scenarios
Store snippet IDs persistently to avoid lookup operations
Monitor usage through the response’s usage field
Validate IDs before making requests to avoid unnecessary API calls
Don’t fetch snippets in tight loops without caching - this will quickly
exhaust your API quota and hit rate limits.
Related Endpoints
- Get Multiple Snippets - Fetch multiple snippets at once
- Create Snippet - Create a new snippet
- Update Snippet - Update an existing snippet
- Get Snippet Variation - Get a specific variation
Authorizations
API key authentication using Bearer token. Include your API key in the Authorization header.
Query Parameters
The ID of the snippet to fetch
⌘I