TypeScript@mechmocks/sdk
npm install @mechmocks/sdk
/**
* @mechmocks/sdk v2.0.0 — Official TypeScript & Node.js Client for MechMocks Studio
* Origin: https://mechmock.com
*/
export interface MechMocksClientOptions {
apiKey?: string;
baseUrl?: string;
timeoutMs?: number;
}
export interface RenderRequest {
bezelId?: string;
finish?: string;
backdrop?: string;
headline?: string;
subheadline?: string;
calloutBadge?: string;
width?: number;
height?: number;
pitch?: number;
yaw?: number;
reflection?: number;
redactSecrets?: boolean;
}
export interface CsvBatchRequest {
csvText?: string;
rows?: Array<Record<string, string>>;
defaultBezelId?: string;
defaultFinish?: string;
defaultBackdrop?: string;
}
export class MechMocksClient {
private readonly apiKey: string;
private readonly baseUrl: string;
private readonly timeoutMs: number;
constructor(options: MechMocksClientOptions = {}) {
this.apiKey = options.apiKey || process.env.MECHMOCKS_API_KEY || '';
this.baseUrl = (options.baseUrl || 'https://mechmock.com').replace(/\/+$/, '');
this.timeoutMs = options.timeoutMs || 15000;
}
private async request<T>(path: string, body?: unknown, method = 'POST'): Promise<T> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
try {
const headers: Record<string, string> = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
if (this.apiKey) {
headers['Authorization'] = `Bearer ${this.apiKey}`;
}
const response = await fetch(`${this.baseUrl}${path}`, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
signal: controller.signal
});
if (!response.ok) {
throw new Error(`MechMocks API error (${response.status})`);
}
return (await response.json()) as T;
} finally {
clearTimeout(timer);
}
}
async render(payload: RenderRequest) {
return this.request('/api/v1/render', payload, 'POST');
}
async renderBatch(payload: Record<string, unknown>) {
return this.request('/api/v1/renders/batch', payload, 'POST');
}
async exportCsvBatch(payload: CsvBatchRequest) {
return this.request('/api/v1/renders/csv-batch', payload, 'POST');
}
async captureUrl(url: string, options: RenderRequest = {}) {
return this.request('/api/v1/capture-url', { url, ...options }, 'POST');
}
async localizeDeck(headlines: string[], targetLocales: string[] = [], presetId = 'apple-69') {
return this.request('/api/v1/localize-deck', { headlines, targetLocales, presetId }, 'POST');
}
async buildSignedOgUrl(workspaceSlug: string, bezelId: string, props: RenderRequest = {}) {
return this.request('/api/v1/og/sign', { workspaceSlug, bezelId, props }, 'POST');
}
}
Pythonmechmocks
pip install mechmocks
"""
mechmocks v2.0.0 — Official Python SDK for MechMocks Commercial Studio
Origin: https://mechmock.com
Supports stdlib urllib.request and optional httpx client transport.
"""
import json
import os
import urllib.request
from typing import Any, Dict, List, Optional
class MechMocksClient:
def __init__(
self,
api_key: Optional[str] = None,
base_url: str = "https://mechmock.com",
timeout: float = 15.0,
) -> None:
self.api_key = api_key or os.environ.get("MECHMOCKS_API_KEY", "")
self.base_url = base_url.rstrip("/")
self.timeout = timeout
def _request(self, path: str, payload: Optional[Dict[str, Any]] = None, method: str = "POST") -> Dict[str, Any]:
url = f"{self.base_url}{path}"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": "mechmocks-python-sdk/2.0.0",
}
if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}"
data = json.dumps(payload).encode("utf-8") if payload is not None else None
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
return json.loads(resp.read().decode("utf-8"))
def render(self, **kwargs: Any) -> Dict[str, Any]:
return self._request("/api/v1/render", kwargs, "POST")
def render_batch(self, **kwargs: Any) -> Dict[str, Any]:
return self._request("/api/v1/renders/batch", kwargs, "POST")
def export_csv_batch(self, csv_text: str = "", rows: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]:
return self._request("/api/v1/renders/csv-batch", {"csvText": csv_text, "rows": rows}, "POST")
def capture_url(self, url: str, bezel_id: str = "safari-chrome-glass") -> Dict[str, Any]:
return self._request("/api/v1/capture-url", {"url": url, "bezelId": bezel_id}, "POST")
def localize_deck(self, headlines: List[str], target_locales: Optional[List[str]] = None, preset_id: str = "apple-69") -> Dict[str, Any]:
return self._request(
"/api/v1/localize-deck",
{"headlines": headlines, "targetLocales": target_locales or [], "presetId": preset_id},
"POST",
)
def build_signed_og_url(self, workspace_slug: str, bezel_id: str, props: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
return self._request(
"/api/v1/og/sign",
{"workspaceSlug": workspace_slug, "bezelId": bezel_id, "props": props or {}},
"POST",
)
Gogithub.com/mechmocks/mechmocks-go
go get github.com/mechmocks/mechmocks-go
// Package mechmocks provides the official Go SDK for MechMocks Commercial Studio.
// Module: github.com/mechmocks/mechmocks-go
package mechmocks
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
type Client struct {
APIKey string
BaseURL string
HTTPClient *http.Client
}
func NewClient(apiKey string, baseURL string) *Client {
if strings.TrimSpace(baseURL) == "" {
baseURL = "https://mechmock.com"
}
return &Client{
APIKey: apiKey,
BaseURL: strings.TrimRight(baseURL, "/"),
HTTPClient: &http.Client{Timeout: 15 * time.Second},
}
}
func (c *Client) postJSON(ctx context.Context, path string, payload any) (map[string]any, error) {
bodyBytes, err := json.Marshal(payload)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+path, bytes.NewReader(bodyBytes))
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
if c.APIKey != "" {
req.Header.Set("Authorization", "Bearer "+c.APIKey)
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("mechmocks api status %d", resp.StatusCode)
}
var out map[string]any
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return nil, err
}
return out, nil
}
func (c *Client) Render(ctx context.Context, payload map[string]any) (map[string]any, error) {
return c.postJSON(ctx, "/api/v1/render", payload)
}
func (c *Client) RenderBatch(ctx context.Context, payload map[string]any) (map[string]any, error) {
return c.postJSON(ctx, "/api/v1/renders/batch", payload)
}
func (c *Client) ExportCsvBatch(ctx context.Context, csvText string) (map[string]any, error) {
return c.postJSON(ctx, "/api/v1/renders/csv-batch", map[string]any{"csvText": csvText})
}
func (c *Client) CaptureURL(ctx context.Context, targetURL string, bezelID string) (map[string]any, error) {
return c.postJSON(ctx, "/api/v1/capture-url", map[string]any{"url": targetURL, "bezelId": bezelID})
}
func (c *Client) LocalizeDeck(ctx context.Context, headlines []string, locales []string, presetID string) (map[string]any, error) {
return c.postJSON(ctx, "/api/v1/localize-deck", map[string]any{
"headlines": headlines,
"targetLocales": locales,
"presetId": presetID,
})
}
func (c *Client) BuildSignedOgURL(ctx context.Context, workspaceSlug string, bezelID string, props map[string]any) (map[string]any, error) {
return c.postJSON(ctx, "/api/v1/og/sign", map[string]any{
"workspaceSlug": workspaceSlug,
"bezelId": bezelID,
"props": props,
})
}
C# (.NET 8)MechMocks.Sdk
dotnet add package MechMocks.Sdk
// MechMocks.Sdk v2.0.0 — Official .NET 8 Client for MechMocks Commercial Studio
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace MechMocks.Sdk
{
public sealed class MechMocksClient
{
private readonly HttpClient _httpClient;
private readonly string _baseUrl;
public MechMocksClient(string apiKey = "", string baseUrl = "https://mechmock.com", HttpClient? httpClient = null)
{
_baseUrl = (baseUrl ?? "https://mechmock.com").TrimEnd('/');
_httpClient = httpClient ?? new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
if (!string.IsNullOrWhiteSpace(apiKey))
{
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
}
}
private async Task<JsonDocument> PostJsonAsync(string path, object payload, CancellationToken ct = default)
{
var json = JsonSerializer.Serialize(payload);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await _httpClient.PostAsync(_baseUrl + path, content, ct).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var stream = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
return await JsonDocument.ParseAsync(stream, cancellationToken: ct).ConfigureAwait(false);
}
public Task<JsonDocument> RenderAsync(object payload, CancellationToken ct = default) =>
PostJsonAsync("/api/v1/render", payload, ct);
public Task<JsonDocument> RenderBatchAsync(object payload, CancellationToken ct = default) =>
PostJsonAsync("/api/v1/renders/batch", payload, ct);
public Task<JsonDocument> ExportCsvBatchAsync(string csvText, CancellationToken ct = default) =>
PostJsonAsync("/api/v1/renders/csv-batch", new { csvText }, ct);
public Task<JsonDocument> CaptureUrlAsync(string url, string bezelId = "safari-chrome-glass", CancellationToken ct = default) =>
PostJsonAsync("/api/v1/capture-url", new { url, bezelId }, ct);
public Task<JsonDocument> LocalizeDeckAsync(IEnumerable<string> headlines, IEnumerable<string> targetLocales, string presetId = "apple-69", CancellationToken ct = default) =>
PostJsonAsync("/api/v1/localize-deck", new { headlines, targetLocales, presetId }, ct);
public Task<JsonDocument> BuildSignedOgUrlAsync(string workspaceSlug, string bezelId, object props, CancellationToken ct = default) =>
PostJsonAsync("/api/v1/og/sign", new { workspaceSlug, bezelId, props }, ct);
}
}