Integration Examples
Working code examples for the Code Snippet Manager API.
Base URL: https://api.codesnippet-manager.example.com/v1
1. cURL
# Login and capture token
TOKEN=$(curl -s -X POST https://api.codesnippet-manager.example.com/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"user@example.com","password":"securepassword123"}' \
| python3 -c "import sys,json;print(json.load(sys.stdin)['access_token'])")
# List snippets (page 1, 20 per page)
curl -s "https://api.codesnippet-manager.example.com/v1/snippets?page=1&limit=20" \
-H "Authorization: Bearer $TOKEN"
# Create a snippet
curl -s -X POST https://api.codesnippet-manager.example.com/v1/snippets \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "Debounce utility",
"content": "function debounce(fn, ms){let t;return(...a)=>{clearTimeout(t);t=setTimeout(()=>fn(...a),ms)}}",
"language": "javascript",
"tags": ["utils", "performance"],
"description": "Classic debounce",
"is_public": false
}'
# Search
curl -s "https://api.codesnippet-manager.example.com/v1/snippets/search?q=debounce&language=javascript" \
-H "Authorization: Bearer $TOKEN"
# Update
curl -s -X PUT https://api.codesnippet-manager.example.com/v1/snippets/snip_xyz789 \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"is_public": true}'
# Delete
curl -s -X DELETE https://api.codesnippet-manager.example.com/v1/snippets/snip_xyz789 \
-H "Authorization: Bearer $TOKEN" -w "%{http_code}\n"
2. JavaScript (Fetch API)
const API_BASE = 'https://api.codesnippet-manager.example.com/v1';
const API_TOKEN = process.env.CSM_TOKEN;
const authHeaders = {
'Authorization': `Bearer ${API_TOKEN}`,
'Content-Type': 'application/json'
};
async function request(path, options = {}) {
const res = await fetch(`${API_BASE}${path}`, {
...options,
headers: { ...authHeaders, ...(options.headers || {}) }
});
if (res.status === 204) return null;
const body = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(body?.error?.message || `HTTP ${res.status}`);
return body;
}
// CRUD helpers
export const listSnippets = (params = {}) => {
const qs = new URLSearchParams(params).toString();
return request(`/snippets${qs ? `?${qs}` : ''}`);
};
export const getSnippet = (id) => request(`/snippets/${id}`);
export const createSnippet = (payload) =>
request('/snippets', { method: 'POST', body: JSON.stringify(payload) });
export const updateSnippet = (id, payload) =>
request(`/snippets/${id}`, { method: 'PUT', body: JSON.stringify(payload) });
export const deleteSnippet = (id) =>
request(`/snippets/${id}`, { method: 'DELETE' });
export const searchSnippets = (q, filters = {}) =>
request(`/snippets/search?${new URLSearchParams({ q, ...filters })}`);
// Usage
const created = await createSnippet({
title: 'Python retry decorator',
content: 'def retry(n=3):\n def deco(f):\n ...\n return deco',
language: 'python',
tags: ['python', 'decorators']
});
console.log('Created:', created.id);
Auto-pagination helper
async function* iterateSnippets(filters = {}) {
let page = 1;
while (true) {
const res = await listSnippets({ ...filters, page, limit: 100 });
for (const item of res.data) yield item;
if (page >= res.pagination.total_pages) break;
page += 1;
}
}
for await (const s of iterateSnippets({ language: 'python' })) {
console.log(s.title);
}
3. Python (requests)
import os
import requests
API_BASE = "https://api.codesnippet-manager.example.com/v1"
class SnippetClient:
def __init__(self, token: str | None = None):
self.token = token or os.environ["CSM_TOKEN"]
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json",
})
def _handle(self, resp: requests.Response):
if resp.status_code == 204:
return None
resp.raise_for_status()
return resp.json()
def list_snippets(self, **params):
return self._handle(self.session.get(f"{API_BASE}/snippets", params=params))
def get_snippet(self, snippet_id: str):
return self._handle(self.session.get(f"{API_BASE}/snippets/{snippet_id}"))
def create_snippet(self, title, content, language, tags=None, **extra):
payload = {"title": title, "content": content,
"language": language, "tags": tags or [], **extra}
return self._handle(self.session.post(f"{API_BASE}/snippets", json=payload))
def update_snippet(self, snippet_id: str, **updates):
return self._handle(self.session.put(f"{API_BASE}/snippets/{snippet_id}", json=updates))
def delete_snippet(self, snippet_id: str):
return self._handle(self.session.delete(f"{API_BASE}/snippets/{snippet_id}"))
def search(self, q: str, **filters):
return self._handle(self.session.get(f"{API_BASE}/snippets/search",
params={"q": q, **filters}))
if __name__ == "__main__":
client = SnippetClient()
snippet = client.create_snippet(
title="FastAPI dependency injection",
content="async def get_db():\n async with Session() as s:\n yield s",
language="python",
tags=["fastapi", "database"],
description="Reusable DB dependency",
)
print("Created:", snippet["id"])
print("Search hits:", client.search("fastapi")["pagination"]["total"])
Bulk import from local files
from pathlib import Path
def import_folder(client, folder: str, language: str, tags=None):
created = []
for path in Path(folder).rglob(f"*.{language}"):
snippet = client.create_snippet(
title=path.stem,
content=path.read_text(encoding="utf-8"),
language=language,
tags=(tags or []) + [path.parent.name],
)
created.append(snippet["id"])
return created
4. Go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
const apiBase = "https://api.codesnippet-manager.example.com/v1"
type Snippet struct {
ID string `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
Language string `json:"language"`
Tags []string `json:"tags"`
}
func do(method, path string, payload any, out any) error {
var body io.Reader
if payload != nil {
b, _ := json.Marshal(payload)
body = bytes.NewReader(b)
}
req, err := http.NewRequest(method, apiBase+path, body)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("CSM_TOKEN"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
b, _ := io.ReadAll(resp.Body)
return fmt.Errorf("http %d: %s", resp.StatusCode, b)
}
if out != nil && resp.StatusCode != http.StatusNoContent {
return json.NewDecoder(resp.Body).Decode(out)
}
return nil
}
func main() {
var created Snippet
err := do("POST", "/snippets", map[string]any{
"title": "Goroutine worker pool",
"content": "for w := 0; w < n; w++ { go worker(jobs, results) }",
"language": "go",
"tags": []string{"go", "concurrency"},
}, &created)
if err != nil {
panic(err)
}
fmt.Println("Created:", created.ID)
}
5. Common integration patterns
| Pattern | Recommendation |
|---|---|
| Token storage | Environment variable or secret manager, never in source control |
| Retries | Exponential backoff on 429 and 5xx (max 3 attempts) |
| Timeouts | 10s connect / 30s read |
| Idempotency | Send Idempotency-Key header on POST to avoid duplicates |
| Caching | Respect ETag / Cache-Control on GET responses |
| Webhooks | Verify X-CSM-Signature (HMAC-SHA256) before trusting payload |