Skip to main content
This page provides copy-paste examples in popular languages for calling your Endprompt endpoints.

JavaScript / Node.js

Using Fetch

async function callEndprompt(text) {
  const response = await fetch('https://acme.api.endprompt.ai/api/v1/summarize', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': process.env.ENDPROMPT_API_KEY
    },
    body: JSON.stringify({
      text: text,
      max_length: 100
    })
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message);
  }

  return await response.json();
}

// Usage
const result = await callEndprompt('Your long text here...');
console.log(result.summary);

Using Axios

const axios = require('axios');

async function callEndprompt(text) {
  try {
    const response = await axios.post(
      'https://acme.api.endprompt.ai/api/v1/summarize',
      {
        text: text,
        max_length: 100
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'x-api-key': process.env.ENDPROMPT_API_KEY
        },
        timeout: 60000 // 60 second timeout
      }
    );

    return response.data;
  } catch (error) {
    if (error.response) {
      throw new Error(error.response.data.message);
    }
    throw error;
  }
}

Python

Using Requests

import os
import requests

def call_endprompt(text: str) -> dict:
    response = requests.post(
        'https://acme.api.endprompt.ai/api/v1/summarize',
        headers={
            'Content-Type': 'application/json',
            'x-api-key': os.environ.get('ENDPROMPT_API_KEY')
        },
        json={
            'text': text,
            'max_length': 100
        },
        timeout=60
    )
    
    response.raise_for_status()
    return response.json()

# Usage
result = call_endprompt('Your long text here...')
print(result['summary'])

Using HTTPX (Async)

import os
import httpx

async def call_endprompt(text: str) -> dict:
    async with httpx.AsyncClient() as client:
        response = await client.post(
            'https://acme.api.endprompt.ai/api/v1/summarize',
            headers={
                'Content-Type': 'application/json',
                'x-api-key': os.environ.get('ENDPROMPT_API_KEY')
            },
            json={
                'text': text,
                'max_length': 100
            },
            timeout=60.0
        )
        
        response.raise_for_status()
        return response.json()

# Usage
import asyncio
result = asyncio.run(call_endprompt('Your long text here...'))

TypeScript

interface SummarizeRequest {
  text: string;
  max_length?: number;
}

interface SummarizeResponse {
  summary: string;
  word_count: number;
}

async function callEndprompt(request: SummarizeRequest): Promise<SummarizeResponse> {
  const response = await fetch('https://acme.api.endprompt.ai/api/v1/summarize', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': process.env.ENDPROMPT_API_KEY!
    },
    body: JSON.stringify(request)
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message);
  }

  return await response.json() as SummarizeResponse;
}

// Usage
const result = await callEndprompt({ text: 'Your long text...', max_length: 100 });
console.log(result.summary);

C# / .NET

using System.Net.Http;
using System.Net.Http.Json;

public class EndpromptClient
{
    private readonly HttpClient _httpClient;
    
    public EndpromptClient(string apiKey)
    {
        _httpClient = new HttpClient
        {
            BaseAddress = new Uri("https://acme.api.endprompt.ai"),
            Timeout = TimeSpan.FromSeconds(60)
        };
        _httpClient.DefaultRequestHeaders.Add("x-api-key", apiKey);
    }
    
    public async Task<SummarizeResponse> SummarizeAsync(string text, int maxLength = 100)
    {
        var request = new { text, max_length = maxLength };
        
        var response = await _httpClient.PostAsJsonAsync("/api/v1/summarize", request);
        response.EnsureSuccessStatusCode();
        
        return await response.Content.ReadFromJsonAsync<SummarizeResponse>();
    }
}

public record SummarizeResponse(string Summary, int WordCount);

// Usage
var client = new EndpromptClient(Environment.GetEnvironmentVariable("ENDPROMPT_API_KEY"));
var result = await client.SummarizeAsync("Your long text here...");
Console.WriteLine(result.Summary);

Go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
    "os"
    "time"
)

type SummarizeRequest struct {
    Text      string `json:"text"`
    MaxLength int    `json:"max_length,omitempty"`
}

type SummarizeResponse struct {
    Summary   string `json:"summary"`
    WordCount int    `json:"word_count"`
}

func CallEndprompt(text string, maxLength int) (*SummarizeResponse, error) {
    client := &http.Client{Timeout: 60 * time.Second}
    
    reqBody, _ := json.Marshal(SummarizeRequest{
        Text:      text,
        MaxLength: maxLength,
    })
    
    req, _ := http.NewRequest("POST", 
        "https://acme.api.endprompt.ai/api/v1/summarize",
        bytes.NewBuffer(reqBody))
    
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("x-api-key", os.Getenv("ENDPROMPT_API_KEY"))
    
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    
    var result SummarizeResponse
    if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
        return nil, err
    }
    
    return &result, nil
}

Ruby

require 'net/http'
require 'json'
require 'uri'

def call_endprompt(text, max_length: 100)
  uri = URI('https://acme.api.endprompt.ai/api/v1/summarize')
  
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.read_timeout = 60
  
  request = Net::HTTP::Post.new(uri.path)
  request['Content-Type'] = 'application/json'
  request['x-api-key'] = ENV['ENDPROMPT_API_KEY']
  request.body = { text: text, max_length: max_length }.to_json
  
  response = http.request(request)
  
  raise "Error: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
  
  JSON.parse(response.body)
end

# Usage
result = call_endprompt('Your long text here...')
puts result['summary']

PHP

<?php

function callEndprompt(string $text, int $maxLength = 100): array {
    $url = 'https://acme.api.endprompt.ai/api/v1/summarize';
    
    $data = [
        'text' => $text,
        'max_length' => $maxLength
    ];
    
    $options = [
        'http' => [
            'method' => 'POST',
            'header' => implode("\r\n", [
                'Content-Type: application/json',
                'x-api-key: ' . getenv('ENDPROMPT_API_KEY')
            ]),
            'content' => json_encode($data),
            'timeout' => 60
        ]
    ];
    
    $context = stream_context_create($options);
    $response = file_get_contents($url, false, $context);
    
    if ($response === false) {
        throw new Exception('Request failed');
    }
    
    return json_decode($response, true);
}

// Usage
$result = callEndprompt('Your long text here...');
echo $result['summary'];

Error Handling Pattern

All examples should include proper error handling:
try {
  const result = await callEndprompt(text);
  return result;
} catch (error) {
  if (error.status === 401) {
    console.error('Invalid API key');
  } else if (error.status === 422) {
    console.error('Validation error:', error.message);
  } else if (error.status === 429) {
    console.error('Rate limited, retry after:', error.retryAfter);
  } else {
    console.error('Unexpected error:', error.message);
  }
  throw error;
}

Next Steps