REST API Examples

Real-world examples of using the SuperPrompts REST API in different programming languages.

Python with OpenAI

Fetch a prompt and use it with OpenAI's API:

import requests
import openai
import os

API_KEY = os.getenv('SUPERPROMPTS_API_KEY')
PROMPT_ID = 'customer-support-bot'

def get_prompt(prompt_id):
    response = requests.get(
        f'https://superprompts.app/api/v1/prompts/{prompt_id}',
        headers={'x-api-key': API_KEY}
    )
    response.raise_for_status()
    return response.json()['content']

def chat(user_message):
    system_prompt = get_prompt(PROMPT_ID)
    
    response = openai.ChatCompletion.create(
        model='gpt-4',
        messages=[
            {'role': 'system', 'content': system_prompt},
            {'role': 'user', 'content': user_message}
        ]
    )
    
    return response.choices[0].message.content

# Usage
response = chat('Hello, I need help with my order')
print(response)

Node.js with Anthropic

Use SuperPrompts with Anthropic's Claude:

import Anthropic from '@anthropic-ai/sdk';
import axios from 'axios';

const API_KEY = process.env.SUPERPROMPTS_API_KEY;
const PROMPT_ID = 'assistant';

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY
});

async function getPrompt(promptId) {
  const response = await axios.get(
    `https://superprompts.app/api/v1/prompts/${promptId}`,
    {
      headers: { 'x-api-key': API_KEY }
    }
  );
  return response.data.content;
}

async function chat(userMessage) {
  const systemPrompt = await getPrompt(PROMPT_ID);
  
  const message = await anthropic.messages.create({
    model: 'claude-3-opus-20240229',
    max_tokens: 1024,
    system: systemPrompt,
    messages: [
      { role: 'user', content: userMessage }
    ]
  });
  
  return message.content[0].text;
}

// Usage
const response = await chat('Tell me about your capabilities');
console.log(response);

Ruby with HTTParty

Fetch prompts in Ruby:

require 'httparty'
require 'json'

class SuperPromptsClient
  BASE_URL = 'https://superprompts.app/api/v1'
  
  def initialize(api_key)
    @api_key = api_key
  end
  
  def get_prompt(prompt_id)
    response = HTTParty.get(
      "#{BASE_URL}/prompts/#{prompt_id}",
      headers: { 'x-api-key' => @api_key }
    )
    
    raise "API Error: #{response.code}" unless response.success?
    
    JSON.parse(response.body)['content']
  end
end

# Usage
client = SuperPromptsClient.new(ENV['SUPERPROMPTS_API_KEY'])
prompt = client.get_prompt('my-prompt')
puts prompt

Go with net/http

Fetch prompts in Go:

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
)

type PromptResponse struct {
    ID      string `json:"id"`
    Content string `json:"content"`
}

func getPrompt(promptID string) (string, error) {
    apiKey := os.Getenv("SUPERPROMPTS_API_KEY")
    url := fmt.Sprintf("https://superprompts.app/api/v1/prompts/%s", promptID)
    
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return "", err
    }
    
    req.Header.Set("x-api-key", apiKey)
    
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()
    
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return "", err
    }
    
    var promptResp PromptResponse
    err = json.Unmarshal(body, &promptResp)
    if err != nil {
        return "", err
    }
    
    return promptResp.Content, nil
}

func main() {
    prompt, err := getPrompt("my-prompt")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    fmt.Println(prompt)
}

PHP with cURL

Fetch prompts in PHP:

<?php

class SuperPromptsClient {
    private $apiKey;
    private $baseUrl = 'https://superprompts.app/api/v1';
    
    public function __construct($apiKey) {
        $this->apiKey = $apiKey;
    }
    
    public function getPrompt($promptId) {
        $url = $this->baseUrl . '/prompts/' . $promptId;
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'x-api-key: ' . $this->apiKey
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode !== 200) {
            throw new Exception('API Error: ' . $httpCode);
        }
        
        $data = json_decode($response, true);
        return $data['content'];
    }
}

// Usage
$client = new SuperPromptsClient(getenv('SUPERPROMPTS_API_KEY'));
$prompt = $client->getPrompt('my-prompt');
echo $prompt;

?>

Java with HttpClient

Fetch prompts in Java:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class SuperPromptsClient {
    private final String apiKey;
    private final HttpClient client;
    private static final String BASE_URL = "https://superprompts.app/api/v1";
    
    public SuperPromptsClient(String apiKey) {
        this.apiKey = apiKey;
        this.client = HttpClient.newHttpClient();
    }
    
    public String getPrompt(String promptId) throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(BASE_URL + "/prompts/" + promptId))
            .header("x-api-key", apiKey)
            .GET()
            .build();
        
        HttpResponse<String> response = client.send(
            request,
            HttpResponse.BodyHandlers.ofString()
        );
        
        if (response.statusCode() != 200) {
            throw new Exception("API Error: " + response.statusCode());
        }
        
        JsonObject json = JsonParser.parseString(response.body())
            .getAsJsonObject();
        return json.get("content").getAsString();
    }
    
    public static void main(String[] args) throws Exception {
        String apiKey = System.getenv("SUPERPROMPTS_API_KEY");
        SuperPromptsClient client = new SuperPromptsClient(apiKey);
        String prompt = client.getPrompt("my-prompt");
        System.out.println(prompt);
    }
}

Rust with reqwest

Fetch prompts in Rust:

use reqwest;
use serde::Deserialize;
use std::env;

#[derive(Deserialize)]
struct PromptResponse {
    id: String,
    content: String,
}

async fn get_prompt(prompt_id: &str) -> Result<String, Box<dyn std::error::Error>> {
    let api_key = env::var("SUPERPROMPTS_API_KEY")?;
    let url = format!("https://superprompts.app/api/v1/prompts/{}", prompt_id);
    
    let client = reqwest::Client::new();
    let response = client
        .get(&url)
        .header("x-api-key", api_key)
        .send()
        .await?;
    
    let prompt_response: PromptResponse = response.json().await?;
    Ok(prompt_response.content)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let prompt = get_prompt("my-prompt").await?;
    println!("{}", prompt);
    Ok(())
}