Client Guide
This guide demonstrates how to create a client that sends JSON definitions using HTTP POST requests to the ObjectWeaver API.
Step 1: Define the Client
Start by defining a client that will manage the API connection.
- Go
- Python
- JavaScript/Node.js
type Client struct {
Password string // APIKey is the authentication token for the API.
BaseURL string // BaseURL is the base endpoint for API requests.
}
class Client:
def __init__(self, password: str, base_url: str):
"""
Initialize a new client instance.
Args:
password: The authentication token for the API
base_url: The base endpoint for API requests
"""
self.password = password
self.base_url = base_url
class Client {
/**
* Initialize a new client instance.
*
* @param {string} password - The authentication token for the API
* @param {string} baseURL - The base endpoint for API requests
*/
constructor(password, baseURL) {
this.password = password;
this.baseURL = baseURL;
}
}
Step 2: Initialize a New Client
Create a constructor function to initialize a new client instance with the API key and base URL.
For a new client the endpoint that is available within the docker image is: /api/objectGen.
An example endpoint is: http://localhost:2008
- Go
- Python
- JavaScript/Node.js
func NewClient(password, url string) *Client {
return &Client{
Password: password,
BaseURL: url, // Replace with your API's base URL
}
}
def create_client(password: str, url: str) -> Client:
"""
Create a new client instance.
Args:
password: The API authentication token
url: The base URL for API requests
Returns:
A new Client instance
"""
return Client(password, url)
function createClient(password, url) {
/**
* Create a new client instance.
*
* @param {string} password - The API authentication token
* @param {string} url - The base URL for API requests
* @returns {Client} A new Client instance
*/
return new Client(password, url);
}
Step 3: Define the SendRequest Method
Implement a method to send a POST request with a JSON-encoded definition.
- Go
- Python
- JavaScript/Node.js
func (c *Client) SendHttpRequest(prompt string, definition *Definition) (*http.Response, error) {
url := c.BaseURL
requestBody := RequestBody{
Prompt: prompt,
Definition: definition,
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
return nil, fmt.Errorf("error marshalling definition: %v", err)
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/api/objectGen", url), bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+c.Password)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
return resp, nil
}
import requests
import json
from typing import Dict, Any
class Client:
# ... (previous code)
def send_http_request(self, prompt: str, definition: Dict[str, Any]) -> requests.Response:
"""
Send a POST request with a JSON-encoded definition.
Args:
prompt: The prompt for the API
definition: The definition object
Returns:
The HTTP response object
Raises:
requests.RequestException: If the request fails
"""
url = f"{self.base_url}/objectGen"
request_body = {
"prompt": prompt,
"definition": definition
}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.password}"
}
response = requests.post(url, headers=headers, json=request_body)
response.raise_for_status()
return response
const fetch = require('node-fetch');
class Client {
// ... (previous code)
/**
* Send a POST request with a JSON-encoded definition.
*
* @param {string} prompt - The prompt for the API
* @param {Object} definition - The definition object
* @returns {Promise<Response>} The HTTP response object
*/
async sendHttpRequest(prompt, definition) {
const url = `${this.baseURL}/objectGen`;
const requestBody = {
prompt: prompt,
definition: definition
};
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.password}`
};
const response = await fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(requestBody)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response;
}
}
Step 4: Example Usage
Demonstrate how to use the client to send a definition.
- Go
- Python
- JavaScript/Node.js
// Example usage
func ExampleUsage() {
// Initialize a new client with your API key
password := "your-password"
url := "http://localhost:2008"
client := NewClient(password, url)
// Define a sample definition
definition := &Definition{
Type: "Object",
Instruction: "Sample instruction for the definition.",
Properties: map[string]Definition{
"property1": {Type: "String", Instruction: "Description of property1"},
"property2": {Type: "Number", Instruction: "Description of property2"},
},
}
// Send the request
resp, err := client.SendRequest(definition)
if err != nil {
fmt.Printf("Error sending request: %v\n", err)
return
}
defer resp.Body.Close()
// Process response as needed
fmt.Printf("Response Status: %s\n", resp.Status)
// Additional processing of response body, headers, etc.
}
# Example usage
def example_usage():
# Initialize a new client with your API key
password = "your-password"
url = "http://localhost:2008"
client = create_client(password, url)
# Define a sample definition
definition = {
"type": "object",
"instruction": "Sample instruction for the definition.",
"properties": {
"property1": {
"type": "string",
"instruction": "Description of property1"
},
"property2": {
"type": "number",
"instruction": "Description of property2"
}
}
}
# Send the request
try:
response = client.send_http_request("Sample prompt", definition)
print(f"Response Status: {response.status_code}")
print(f"Response Body: {response.json()}")
except requests.RequestException as e:
print(f"Error sending request: {e}")
// Example usage
async function exampleUsage() {
// Initialize a new client with your API key
const password = "your-password";
const url = "http://localhost:2008";
const client = createClient(password, url);
// Define a sample definition
const definition = {
type: "object",
instruction: "Sample instruction for the definition.",
properties: {
property1: {
type: "string",
instruction: "Description of property1"
},
property2: {
type: "number",
instruction: "Description of property2"
}
}
};
// Send the request
try {
const response = await client.sendHttpRequest("Sample prompt", definition);
const data = await response.json();
console.log(`Response Status: ${response.status}`);
console.log(`Response Body:`, data);
} catch (error) {
console.error(`Error sending request: ${error.message}`);
}
}
// Run the example
exampleUsage();
tip
Ensure to adapt the definition structure and example usage to fit your specific API requirements and data structures.