### Run Go Client Example with API Key
Source: https://github.com/parallelworks/sdk/blob/canary/go/examples/README.md
This snippet shows how to set the Parallel Works API key as an environment variable and then execute the Go client example. It assumes Go 1.18+ is installed and an API key is available.
```bash
# Set your API key or token
export PW_API_KEY="your-api-key-or-token"
# Run the example
go run main.go
```
--------------------------------
### Install Parallel Works Go SDK
Source: https://github.com/parallelworks/sdk/blob/canary/go/README.md
Installs the Parallel Works Go SDK version 7 using the go get command. Requires Go 1.18 or later.
```bash
go get github.com/parallelworks/sdk/go/v7
```
--------------------------------
### Quick Start: Sync Client with API Key
Source: https://github.com/parallelworks/sdk/blob/canary/python/README.md
Demonstrates the simplest way to create a synchronous client using an API key from environment variables. It then fetches and prints bucket names from the API.
```python
import os
from parallelworks_client import Client
# The platform host is automatically extracted from your credential
with Client.from_credential(os.environ["PW_API_KEY"]).sync() as client:
response = client.get("/api/buckets")
for bucket in response.json():
print(f"Bucket: {bucket['name']}")
```
--------------------------------
### Quick Start: Initialize Client and Fetch Data
Source: https://github.com/parallelworks/sdk/blob/canary/typescript/README.md
Demonstrates the simplest way to initialize the Parallel Works client using an API key from environment variables and then making a GET request to fetch buckets.
```typescript
import { Client } from '@parallelworks/client'
// The platform host is automatically extracted from your credential
const client = Client.fromCredential(process.env.PW_API_KEY!)
const { data, error } = await client.GET('/api/buckets')
```
--------------------------------
### Install parallelworks-client
Source: https://github.com/parallelworks/sdk/blob/canary/python/README.md
Installs the parallelworks-client library using pip. This is the first step to using the client in your Python projects.
```bash
pip install parallelworks-client
```
--------------------------------
### Install Parallel Works SDKs
Source: https://github.com/parallelworks/sdk/blob/canary/README.md
Commands to install the Parallel Works SDKs for TypeScript, Python, and Go using their respective package managers.
```bash
npm install @parallelworks/client # TypeScript
pip install parallelworks-client # Python
go get github.com/parallelworks/sdk/go/v7 # Go
```
--------------------------------
### Quick Start: Fetch Buckets using Parallel Works SDKs
Source: https://github.com/parallelworks/sdk/blob/canary/README.md
Demonstrates how to initialize the Parallel Works client and fetch buckets using API keys or tokens for TypeScript, Python, and Go. The clients automatically detect the host from the credential.
```typescript
import { Client } from '@parallelworks/client'
const client = Client.fromCredential(process.env.PW_API_KEY!)
const { data } = await client.GET('/api/buckets')
```
```python
from parallelworks_client import Client
with Client.from_credential(os.environ["PW_API_KEY"]).sync() as client:
buckets = client.get("/api/buckets").json()
```
```go
import parallelworks "github.com/parallelworks/sdk/go/v7"
client, _ := parallelworks.NewClientFromCredential(os.Getenv("PW_API_KEY"))
buckets, _ := client.GetBuckets(context.Background())
```
--------------------------------
### List Buckets and Clusters (TypeScript, Python, Go)
Source: https://context7.com/parallelworks/sdk/llms.txt
Examples for retrieving a list of available storage buckets and compute clusters for the authenticated user. These operations are fundamental for managing resources within the Parallelworks platform.
```typescript
// TypeScript - List buckets and clusters
import { Client } from '@parallelworks/client'
const client = Client.fromCredential(process.env.PW_API_KEY!)
// Fetch buckets and clusters in parallel
const [bucketsResponse, clustersResponse] = await Promise.all([
client.GET('/api/buckets'),
client.GET('/api/clusters'),
])
// Display buckets
if (!bucketsResponse.error) {
const buckets = bucketsResponse.data ?? []
console.log(`Buckets (${buckets.length}):`)
for (const bucket of buckets) {
console.log(` - ${bucket.name} (${bucket.csp})`)
}
}
// Display clusters
if (!clustersResponse.error) {
const clusters = clustersResponse.data ?? []
console.log(`Clusters (${clusters.length}):`)
for (const cluster of clusters) {
console.log(` - ${cluster.name} (${cluster.status})`)
}
}
```
```python
# Python - List buckets and clusters (sync)
import os
from parallelworks_client import Client
with Client.from_credential(os.environ["PW_API_KEY"]).sync() as client:
# Fetch buckets
buckets_response = client.get("/api/buckets")
buckets_response.raise_for_status()
buckets = buckets_response.json()
print(f"Buckets ({len(buckets)}):")
for bucket in buckets:
print(f" - {bucket['name']} ({bucket['csp']})")
# Fetch clusters
clusters_response = client.get("/api/clusters")
clusters_response.raise_for_status()
clusters = clusters_response.json()
print(f"Clusters ({len(clusters)}):")
for cluster in clusters:
print(f" - {cluster['name']} ({cluster['status']})")
```
```go
// Go - List buckets and clusters
package main
import (
"context"
"fmt"
"log"
"os"
parallelworks "github.com/parallelworks/sdk/go/v7"
)
func main() {
client, _ := parallelworks.NewClientFromCredential(os.Getenv("PW_API_KEY"))
ctx := context.Background()
// List buckets
buckets, err := client.GetBuckets(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Buckets (%d):\n", len(*buckets))
for _, bucket := range *buckets {
fmt.Printf(" - %s (%s)\n", bucket.Name, bucket.Csp)
}
// List clusters
clusters, err := client.GetClusters(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Clusters (%d):\n", len(*clusters))
for _, cluster := range *clusters {
fmt.Printf(" - %s (%s)\n", cluster.Name, cluster.Status)
}
}
```
--------------------------------
### Get Session and Platform Info (Go)
Source: https://context7.com/parallelworks/sdk/llms.txt
Retrieves current session, API keys, available cloud providers, and feature previews using the Parallel Works Go SDK. Requires an API key for authentication.
```go
package main
import (
"context"
"fmt"
"os"
parallelworks "github.com/parallelworks/sdk/go/v7"
)
func main() {
client, _ := parallelworks.NewClientFromCredential(os.Getenv("PW_API_KEY"))
ctx := context.Background()
// Get current session
session, _ := client.GetAuthSession(ctx)
fmt.Printf("User: %s\n", session.User.Email)
// Get API keys
keys, _ := client.GetApikeys(ctx)
fmt.Printf("API Keys: %d\n", len(*keys))
// Get available CSPs
csps, _ := client.GetAvailableCsps(ctx)
fmt.Printf("Available CSPs: %v\n", *csps)
// Get feature previews
features, _ := client.GetFeaturePreviews(ctx)
for _, f := range *features {
fmt.Printf("Feature: %s (enabled: %v)\n", f.Name, f.Enabled)
}
}
```
--------------------------------
### Install Parallel Works Client
Source: https://github.com/parallelworks/sdk/blob/canary/typescript/README.md
Installs the core Parallel Works client package using npm. For React projects using SWR, additional packages like 'swr' and 'swr-openapi' are also required.
```bash
npm install @parallelworks/client
```
```bash
npm install @parallelworks/client swr swr-openapi
```
--------------------------------
### Go: Add Custom Middleware
Source: https://context7.com/parallelworks/sdk/llms.txt
Demonstrates how to add custom middleware to the Go client to intercept and modify requests. Examples include logging request and response details, and adding custom headers to outgoing requests. This allows for extended functionality like tracing or custom authentication.
```go
// Go - Add custom middleware
package main
import (
"log"
"net/http"
parallelworks "github.com/parallelworks/sdk/go/v7"
)
func main() {
// Logging middleware
logging := func(req *http.Request, next parallelworks.RoundTripFunc) (*http.Response, error) {
log.Printf("Request: %s %s", req.Method, req.URL)
resp, err := next(req)
if resp != nil {
log.Printf("Response: %d", resp.StatusCode)
}
return resp, err
}
// Custom header middleware
addHeaders := func(req *http.Request, next parallelworks.RoundTripFunc) (*http.Response, error) {
req.Header.Set("X-Custom-Header", "my-value")
return next(req)
}
client := parallelworks.NewClient(
"https://cloud.parallel.works",
parallelworks.WithAuth(¶llelworks.BasicAuth{Username: "pwt_..."}),
parallelworks.WithMiddleware(logging),
parallelworks.WithMiddleware(addHeaders),
parallelworks.WithUserAgent("my-app/1.0"),
)
_ = client
}
```
--------------------------------
### Setup SWR Hooks for React with TypeScript
Source: https://context7.com/parallelworks/sdk/llms.txt
This snippet shows how to set up SWR hooks for React applications using the Parallelworks TypeScript client. It includes automatic caching and revalidation. Dependencies include '@parallelworks/client' and '@parallelworks/client/swr'.
```typescript
// lib/api.ts - Setup SWR hooks
import { Client } from '@parallelworks/client'
import { createSwrHooks } from '@parallelworks/client/swr'
// Create client (credential should come from server-side session)
const client = Client.fromCredential(process.env.NEXT_PUBLIC_PW_API_KEY!)
export const { useQuery, useImmutable, useInfinite } = createSwrHooks(client)
```
--------------------------------
### Use SWR Hooks in React Component
Source: https://context7.com/parallelworks/sdk/llms.txt
This example demonstrates how to use the SWR hooks (`useQuery`, `useImmutable`) within a React component to fetch and display data. It handles loading and error states automatically. The component expects data to be an array of objects with 'id', 'name', and 'csp' properties for BucketList, and 'name' for WorkflowDetails.
```tsx
// components/BucketList.tsx - Use in React component
import { useQuery } from '@/lib/api'
export function BucketList() {
// Automatic caching, revalidation, and loading states
const { data, error, isLoading } = useQuery('/api/buckets')
if (isLoading) return
Loading buckets...
if (error) return Error: {error.message}
return (
{data?.map(bucket => (
-
{bucket.name} ({bucket.csp})
))}
)
}
// Use useImmutable for data that never changes
export function WorkflowDetails({ id }: { id: string }) {
const { data } = useImmutable('/api/workflows/{workflow}', {
params: { path: { workflow: id } }
})
return {data?.name}
}
```
--------------------------------
### Get Session and Platform Info (TypeScript)
Source: https://context7.com/parallelworks/sdk/llms.txt
Fetches current user session, API keys, available cloud providers, and feature previews using the Parallel Works TypeScript SDK. Requires an API key for authentication.
```typescript
import { Client } from '@parallelworks/client'
const client = Client.fromCredential(process.env.PW_API_KEY!)
// Get current session info
const { data: session } = await client.GET('/api/auth/session')
console.log('Current user:', session?.user?.email)
console.log('Organization:', session?.organization?.name)
// Get API keys
const { data: apiKeys } = await client.GET('/api/apikeys')
console.log('API Keys:', apiKeys?.length)
// Get available cloud providers
const { data: csps } = await client.GET('/api/csps')
console.log('Available CSPs:', csps)
// Get platform feature previews
const { data: features } = await client.GET('/api/feature-previews')
for (const feature of features ?? []) {
console.log(`Feature: ${feature.name} - ${feature.enabled ? 'enabled' : 'disabled'}`)
}
```
--------------------------------
### Pagination Support with PageIterator in Go
Source: https://context7.com/parallelworks/sdk/llms.txt
This Go snippet illustrates the use of the `PageIterator` provided by the Parallelworks SDK for handling paginated API responses. It outlines the available methods: `Next()`, `All()`, and `ForEach()` for iterating through pages of data. The example is conceptual and shows how to interact with the iterator.
```go
// Go - Pagination with PageIterator
package main
import (
"context"
"fmt"
parallelworks "github.com/parallelworks/sdk/go/v7"
)
func main() {
// Example: Paginate through allocation usage events
// PageIterator provides Next(), All(), and ForEach() methods
// Using ForEach to process items one at a time
// iterator.ForEach(func(item ItemType) error {
// fmt.Println(item)
// return nil
// })
// Using All() to fetch all pages at once
// allItems, err := iterator.All()
// Using Next() for manual pagination
// for {
// items, err := iterator.Next()
// if err != nil {
// break
// }
// if items == nil {
// break // No more pages
// }
// for _, item := range items {
// fmt.Println(item)
// }
// }
fmt.Println("PageIterator supports Next(), All(), and ForEach() methods")
}
```
--------------------------------
### Configure Go Client with Options
Source: https://github.com/parallelworks/sdk/blob/canary/go/README.md
Demonstrates initializing the Parallel Works client with various configuration options, including authentication, custom HTTP client, user agent, default retry, and middleware.
```go
import parallelworks "github.com/parallelworks/sdk/go/v7"
import "net/http"
// Assume customHTTPClient and loggingMiddleware are defined elsewhere
var customHTTPClient *http.Client
var loggingMiddleware parallelworks.RoundTripFunc
client := parallelworks.NewClient(
"https://cloud.parallel.works",
parallelworks.WithAuth(¶llelworks.BasicAuth{Username: "pwt_..."}),
parallelworks.WithHTTPClient(customHTTPClient),
parallelworks.WithUserAgent("my-app/1.0"),
parallelworks.WithDefaultRetry(),
parallelworks.WithMiddleware(loggingMiddleware),
)
```
--------------------------------
### Initialize Go Client with API Key
Source: https://github.com/parallelworks/sdk/blob/canary/go/README.md
Creates a new Parallel Works client by automatically detecting the platform host from an API key. Requires the PW_API_KEY environment variable.
```go
import parallelworks "github.com/parallelworks/sdk/go/v7"
import "context"
import "log"
import "os"
// The platform host is automatically extracted from your credential
client, err := parallelworks.NewClientFromCredential(os.Getenv("PW_API_KEY"))
if err != nil {
log.Fatal(err)
}
workflows, err := client.ListWorkflows(context.Background())
```
--------------------------------
### Initialize Go Client with Explicit Host and API Key
Source: https://github.com/parallelworks/sdk/blob/canary/go/README.md
Initializes the Parallel Works client with an explicit platform host and API key using Basic Authentication.
```go
import parallelworks "github.com/parallelworks/sdk/go/v7"
// API Key (Basic Auth)
client := parallelworks.NewClient(
"https://cloud.parallel.works",
parallelworks.WithAuth(¶llelworks.BasicAuth{
Username: "pwt_...",
}),
)
```
--------------------------------
### Initialize Client with Auto Host Detection (TypeScript, Python, Go)
Source: https://context7.com/parallelworks/sdk/llms.txt
Demonstrates initializing the Parallel Works client by automatically detecting the platform URL from API keys or JWT tokens. This method simplifies configuration by eliminating the need for manual host specification.
```typescript
// TypeScript - Host auto-detected from credential
import { Client } from '@parallelworks/client'
const client = Client.fromCredential(process.env.PW_API_KEY!)
const { data, error } = await client.GET('/api/buckets')
if (error) {
console.error('Failed to fetch buckets:', error)
} else {
console.log('Buckets:', data)
}
```
```python
# Python - Host auto-detected from credential
import os
from parallelworks_client import Client
with Client.from_credential(os.environ["PW_API_KEY"]).sync() as client:
response = client.get("/api/buckets")
response.raise_for_status()
buckets = response.json()
for bucket in buckets:
print(f"Bucket: {bucket['name']} ({bucket['csp']})")
```
```go
// Go - Host auto-detected from credential
package main
import (
"context"
"log"
"os"
parallelworks "github.com/parallelworks/sdk/go/v7"
)
func main() {
client, err := parallelworks.NewClientFromCredential(os.Getenv("PW_API_KEY"))
if err != nil {
log.Fatal(err)
}
buckets, err := client.GetBuckets(context.Background())
if err != nil {
log.Fatal(err)
}
for _, bucket := range *buckets {
log.Printf("Bucket: %s (%s)", bucket.Name, bucket.Csp)
}
}
```
--------------------------------
### Initialize Go Client with JWT Token
Source: https://github.com/parallelworks/sdk/blob/canary/go/README.md
Creates a new Parallel Works client by automatically detecting the platform host from a JWT token. The host is read from the 'platform_host' claim within the token.
```go
import parallelworks "github.com/parallelworks/sdk/go/v7"
// JWT token — host read from platform_host claim
client, _ := parallelworks.NewClientFromCredential("eyJhbGci...")
// Connects to the host in the token's platform_host claim
```
--------------------------------
### Initialize Go Client with Explicit Host and JWT Token
Source: https://github.com/parallelworks/sdk/blob/canary/go/README.md
Initializes the Parallel Works client with an explicit platform host and JWT token using Bearer Authentication.
```go
import parallelworks "github.com/parallelworks/sdk/go/v7"
// JWT Token (Bearer)
client := parallelworks.NewClient(
"https://cloud.parallel.works",
parallelworks.WithAuth(¶llelworks.BearerAuth{
Token: "eyJhbGci...",
}),
)
```
--------------------------------
### Async Support: Fetching Buckets
Source: https://github.com/parallelworks/sdk/blob/canary/python/README.md
Demonstrates how to use the client asynchronously to fetch bucket information. This is suitable for I/O-bound operations in Python applications.
```python
import asyncio
from parallelworks_client import Client
async def main():
async with Client.from_credential(os.environ["PW_API_KEY"]) as client:
response = await client.get("/api/buckets")
print(response.json())
asyncio.run(main())
```
--------------------------------
### Manage Organizations and Cloud Accounts in Go
Source: https://context7.com/parallelworks/sdk/llms.txt
This Go program demonstrates how to manage organizations and cloud accounts using the Parallelworks SDK. It retrieves lists of organizations, their associated cloud accounts, groups, and allocations. It requires the 'PW_API_KEY' environment variable to be set.
```go
// Go - Organization and cloud account management
package main
import (
"context"
"fmt"
"os"
parallelworks "github.com/parallelworks/sdk/go/v7"
)
func main() {
client, _ := parallelworks.NewClientFromCredential(os.Getenv("PW_API_KEY"))
ctx := context.Background()
// List organizations
orgs, _ := client.GetOrganizations(ctx)
for _, org := range *orgs {
fmt.Printf("Organization: %s\n", org.Name)
// List cloud accounts for organization
accounts, _ := client.GetOrganizationCloudAccounts(ctx, org.Name)
for _, account := range *accounts {
fmt.Printf(" Cloud Account: %s (%s)\n", account.Name, account.Csp)
}
// List groups
groups, _ := client.GetOrganizationGroups(ctx, org.Name)
for _, group := range *groups {
fmt.Printf(" Group: %s\n", group.Name)
}
// List allocations
allocations, _ := client.ListOrgAllocations(ctx, org.Name)
for _, alloc := range *allocations {
fmt.Printf(" Allocation: %s\n", alloc.Name)
}
}
}
```
--------------------------------
### Initialize Client with Explicit Host (TypeScript, Python, Go)
Source: https://context7.com/parallelworks/sdk/llms.txt
Shows how to initialize the Parallel Works client with an explicitly defined platform URL. Supports authentication via API key (Basic Auth) or JWT token (Bearer Auth), and also allows credential auto-detection.
```typescript
// TypeScript - Explicit host with API key
import { Client } from '@parallelworks/client'
// Using API Key (Basic Auth) - recommended for long-running integrations
const client = new Client('https://cloud.parallel.works')
.withApiKey('pwt_...')
// Using JWT Token (Bearer Auth) - for scripts, expires in 24h
const clientWithToken = new Client('https://cloud.parallel.works')
.withToken('eyJhbGci...')
// Auto-detect credential type
const clientAuto = new Client('https://cloud.parallel.works')
.withCredential(process.env.PW_CREDENTIAL!)
```
```python
# Python - Explicit host with API key
from parallelworks_client import Client
# Using API Key (Basic Auth)
client = Client.with_api_key(
"https://cloud.parallel.works",
"pwt_..."
)
# Using JWT Token (Bearer Auth)
client = Client.with_token(
"https://cloud.parallel.works",
"eyJhbGci..."
)
# Auto-detect credential type
client = Client.with_credential(
"https://cloud.parallel.works",
os.environ["PW_CREDENTIAL"]
)
```
```go
// Go - Explicit host with API key
package main
import parallelworks "github.com/parallelworks/sdk/go/v7"
// Using API Key (Basic Auth)
client := parallelworks.NewClient(
"https://cloud.parallel.works",
parallelworks.WithAuth(¶llelworks.BasicAuth{
Username: "pwt_...",
}),
)
// Using JWT Token (Bearer Auth)
clientWithToken := parallelworks.NewClient(
"https://cloud.parallel.works",
parallelworks.WithAuth(¶llelworks.BearerAuth{
Token: "eyJhbGci...",
}),
)
```
--------------------------------
### Go Client Credential Helper Functions
Source: https://github.com/parallelworks/sdk/blob/canary/go/README.md
Provides utility functions to check credential types and extract the platform host from credentials.
```go
import parallelworks "github.com/parallelworks/sdk/go/v7"
parallelworks.IsAPIKey("pwt_abc.xyz") // true
parallelworks.IsToken("eyJ.abc.def") // true
parallelworks.ExtractPlatformHost("pwt_...") // "cloud.parallel.works", nil
```
--------------------------------
### Authentication: Explicit Host Configuration
Source: https://github.com/parallelworks/sdk/blob/canary/python/README.md
Illustrates creating a client by explicitly providing the platform host along with API key or JWT token for authentication.
```python
# API Key (Basic Auth) - best for long-running integrations
client = Client.with_api_key(
"https://cloud.parallel.works",
"pwt_..."
)
# JWT Token (Bearer) - best for scripts, expires in 24h
client = Client.with_token(
"https://cloud.parallel.works",
"eyJhbGci..."
)
# Auto-detect credential type
client = Client.with_credential(
"https://cloud.parallel.works",
os.environ["PW_CREDENTIAL"]
)
```
--------------------------------
### Platform Settings and Session Info
Source: https://context7.com/parallelworks/sdk/llms.txt
Retrieve current session information, API keys, available cloud providers, and platform feature previews.
```APIDOC
## GET /api/auth/session
### Description
Retrieves the current user's session information, including user details and organization.
### Method
GET
### Endpoint
/api/auth/session
### Parameters
#### Query Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **user** (object) - User details.
- **organization** (object) - Organization details.
#### Response Example
```json
{
"user": {
"id": "user_123",
"email": "user@example.com"
},
"organization": {
"id": "org_abc",
"name": "Example Org"
}
}
```
## GET /api/apikeys
### Description
Retrieves a list of API keys associated with the current account.
### Method
GET
### Endpoint
/api/apikeys
### Parameters
#### Query Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **(array)** - An array of API key objects.
#### Response Example
```json
[
{
"id": "key_xyz",
"name": "My Key",
"created_at": "2023-01-01T12:00:00Z"
}
]
```
## GET /api/csps
### Description
Retrieves a list of available cloud service providers (CSPs).
### Method
GET
### Endpoint
/api/csps
### Parameters
#### Query Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **(array)** - An array of CSP objects.
#### Response Example
```json
[
{
"id": "aws",
"name": "Amazon Web Services"
},
{
"id": "gcp",
"name": "Google Cloud Platform"
}
]
```
## GET /api/feature-previews
### Description
Retrieves a list of available platform feature previews and their status.
### Method
GET
### Endpoint
/api/feature-previews
### Parameters
#### Query Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **(array)** - An array of feature preview objects.
#### Response Example
```json
[
{
"name": "New Dashboard",
"enabled": true
},
{
"name": "Advanced Analytics",
"enabled": false
}
]
```
```
--------------------------------
### Go: Configure Retry Behavior
Source: https://context7.com/parallelworks/sdk/llms.txt
Shows how to configure automatic retries with exponential backoff for transient failures in the Go client. It demonstrates using the default retry configuration and customizing retry parameters like maximum retries, base delay, and retryable status codes.
```go
// Go - Configure retry behavior
package main
import (
"time"
parallelworks "github.com/parallelworks/sdk/go/v7"
)
func main() {
// Use default retry config (3 retries, retries on 429/5xx)
client := parallelworks.NewClient(
"https://cloud.parallel.works",
parallelworks.WithAuth(¶llelworks.BasicAuth{Username: "pwt_..."}),
parallelworks.WithDefaultRetry(),
)
// Or customize retry behavior
clientCustom := parallelworks.NewClient(
"https://cloud.parallel.works",
parallelworks.WithAuth(¶llelworks.BasicAuth{Username: "pwt_..."}),
parallelworks.WithRetry(parallelworks.RetryConfig{
MaxRetries: 5,
BaseDelay: 2 * time.Second,
MaxDelay: 60 * time.Second,
Multiplier: 2.0,
RetryableStatusCodes: []int{429, 500, 502, 503, 504},
}),
)
_ = client
_ = clientCustom
}
```
--------------------------------
### Credential Helpers (Python & Go)
Source: https://context7.com/parallelworks/sdk/llms.txt
Demonstrates how to check credential types (API key vs. token) and extract the platform host from a credential string using the Parallelworks SDK. These functions are essential for initializing clients and ensuring correct authentication.
```python
# Python credential helpers
print(is_api_key("pwt_abc.xyz")) # True
print(is_token("eyJ.abc.def")) # True
# Extract platform host from credential
host = extract_platform_host("pwt_Y2xvdWQucGFyYWxsZWwud29ya3M.xxxxx")
print(host) # "cloud.parallel.works"
```
```go
// Go credential helpers
package main
import (
"fmt"
parallelworks "github.com/parallelworks/sdk/go/v7"
)
func main() {
// Check credential type
fmt.Println(parallelworks.IsAPIKey("pwt_abc.xyz")) // true
fmt.Println(parallelworks.IsToken("eyJ.abc.def")) // true
// Extract platform host from credential
host, err := parallelworks.ExtractPlatformHost("pwt_Y2xvdWQucGFyYWxsZWwud29ya3M.xxxxx")
if err != nil {
panic(err)
}
fmt.Println(host) // "cloud.parallel.works"
}
```
--------------------------------
### Authentication: Automatic Host Detection
Source: https://github.com/parallelworks/sdk/blob/canary/python/README.md
Shows how to create a client where the platform host is automatically detected from the provided API key or JWT token.
```python
# API key - host decoded from first segment after pwt_
client = Client.from_credential("pwt_Y2xvdWQucGFyYWxsZWwud29ya3M.xxxxx")
# Connects to: https://cloud.parallel.works
# JWT token - host read from platform_host claim
client = Client.from_credential("eyJhbGci...")
# Connects to the host in the token's platform_host claim
```
--------------------------------
### SWR Hooks Integration for React
Source: https://github.com/parallelworks/sdk/blob/canary/typescript/README.md
Demonstrates setting up SWR hooks for data fetching in a React application. It involves creating a client instance and then using `createSwrHooks` to generate custom hooks like `useQuery`.
```typescript
// lib/api.ts
import { Client } from '@parallelworks/client'
import { createSwrHooks } from '@parallelworks/client/swr'
// Credential should be securely provided by your server (e.g., via session)
const client = Client.fromCredential(credential)
export const { useQuery, useImmutable, useInfinite } = createSwrHooks(client)
```
```typescript
// components/BucketList.tsx
import { useQuery } from '@/lib/api'
export function BucketList() {
const { data, error, isLoading } = useQuery('/api/buckets')
if (isLoading) return Loading...
if (error) return Error: {error.message}
return (
{data?.map(bucket => (
- {bucket.name}
))}
)
}
```
--------------------------------
### Add Custom Middleware to Go Client
Source: https://github.com/parallelworks/sdk/blob/canary/go/README.md
Illustrates how to add custom middleware to the Parallel Works client to intercept and process requests, such as logging.
```go
import parallelworks "github.com/parallelworks/sdk/go/v7"
import "log"
import "net/http"
logging := func(req *http.Request, next parallelworks.RoundTripFunc) (*http.Response, error) {
log.Printf("%s %s", req.Method, req.URL)
return next(req)
}
client := parallelworks.NewClient(url, parallelworks.WithMiddleware(logging))
```
--------------------------------
### Authentication: Explicit Host Configuration
Source: https://github.com/parallelworks/sdk/blob/canary/typescript/README.md
Illustrates initializing the client with an explicit host URL, using methods like `withApiKey`, `withToken`, or `withCredential` to provide authentication details.
```typescript
// API Key (Basic Auth) - best for long-running integrations
const client = new Client('https://cloud.parallel.works')
.withApiKey('pwt_...')
// JWT Token (Bearer) - best for scripts, expires in 24h
const client = new Client('https://cloud.parallel.works')
.withToken('eyJhbGci...')
// Auto-detect credential type
const client = new Client('https://cloud.parallel.works')
.withCredential(process.env.PW_CREDENTIAL!)
```
--------------------------------
### Authentication: Automatic Host Detection
Source: https://github.com/parallelworks/sdk/blob/canary/typescript/README.md
Shows how to initialize the client using `Client.fromCredential`, which automatically detects and uses the platform host from either an API key (pwt_...) or a JWT token.
```typescript
// API key - host decoded from first segment after pwt_
const client = Client.fromCredential('pwt_Y2xvdWQucGFyYWxsZWwud29ya3M.xxxxx')
// Connects to: https://cloud.parallel.works
// JWT token - host read from platform_host claim
const client = Client.fromCredential('eyJhbGci...')
// Connects to the host in the token's platform_host claim
```
--------------------------------
### Python: Handle API Errors with Client
Source: https://context7.com/parallelworks/sdk/llms.txt
Demonstrates how to handle potential CredentialError and httpx.HTTPStatusError exceptions when interacting with the Parallelworks API using the Python client. It shows how to instantiate a client, make a request, and check for specific error types.
```python
import os
from parallelworks_client import Client, CredentialError
import httpx
try:
with Client.from_credential(os.environ["PW_API_KEY"]).sync() as client:
response = client.get("/api/workflows/non-existent")
response.raise_for_status()
except CredentialError as e:
print(f"Invalid credential: {e}")
except httpx.HTTPStatusError as e:
print(f"API Error {e.response.status_code}: {e.response.text}")
```
--------------------------------
### Configure Go Client Retry Policy
Source: https://github.com/parallelworks/sdk/blob/canary/go/README.md
Shows how to enable and customize the automatic retry mechanism for the Parallel Works client, including setting max retries, base delay, max delay, multiplier, and retryable status codes.
```go
import parallelworks "github.com/parallelworks/sdk/go/v7"
import "time"
// Use default retry config (3 retries, retries on 429/5xx)
client := parallelworks.NewClient(url, parallelworks.WithDefaultRetry())
// Or customize
client := parallelworks.NewClient(url, parallelworks.WithRetry(parallelworks.RetryConfig{
MaxRetries: 5,
BaseDelay: 2 * time.Second,
MaxDelay: 60 * time.Second,
Multiplier: 2.0,
RetryableStatusCodes: []int{429, 500, 502, 503, 504},
}))
```
--------------------------------
### Go: Handle API Errors with Sentinel Errors
Source: https://context7.com/parallelworks/sdk/llms.txt
Illustrates robust error handling in Go when using the Parallelworks SDK. It showcases how to check for specific sentinel errors like ErrInvalidCredential, ErrNotFound, ErrUnauthorized, ErrForbidden, and ErrTooManyRequests, and how to access detailed API error information.
```go
// Go - Error handling with sentinel errors
package main
import (
"context"
"errors"
"fmt"
"os"
parallelworks "github.com/parallelworks/sdk/go/v7"
)
func main() {
client, err := parallelworks.NewClientFromCredential(os.Getenv("PW_API_KEY"))
if err != nil {
if errors.Is(err, parallelworks.ErrInvalidCredential) {
fmt.Println("Invalid credential format")
}
return
}
ctx := context.Background()
_, err = client.GetWorkflow(ctx, "non-existent")
if errors.Is(err, parallelworks.ErrNotFound) {
fmt.Println("Workflow not found (404)")
} else if errors.Is(err, parallelworks.ErrUnauthorized) {
fmt.Println("Authentication failed (401)")
} else if errors.Is(err, parallelworks.ErrForbidden) {
fmt.Println("Access denied (403)")
} else if errors.Is(err, parallelworks.ErrTooManyRequests) {
fmt.Println("Rate limited (429)")
} else if err != nil {
// Access detailed error info
var apiErr *parallelworks.APIError
if errors.As(err, &apiErr) {
fmt.Printf("API Error %d: %s\n", apiErr.StatusCode, string(apiErr.Body))
}
}
}
```
--------------------------------
### Listing Workflows API
Source: https://context7.com/parallelworks/sdk/llms.txt
Retrieve all workflows available to the authenticated user with optional filtering.
```APIDOC
## GET /api/workflows
### Description
Retrieve all workflows available to the authenticated user with optional filtering.
### Method
GET
### Endpoint
/api/workflows
### Query Parameters
- **favoriteOnly** (boolean) - Optional - If true, only return favorite workflows.
### Response
#### Success Response (200)
- **data** (array) - An array of workflow objects.
- **name** (string) - The name of the workflow.
- **description** (string) - The description of the workflow.
#### Response Example
```json
{
"data": [
{
"name": "My Workflow",
"description": "This is my workflow"
}
]
}
```
```
--------------------------------
### Async Operations (Python)
Source: https://context7.com/parallelworks/sdk/llms.txt
Illustrates how to perform asynchronous operations using the Parallelworks Python client, leveraging the `httpx` library. This allows for concurrent fetching of resources like buckets and clusters, improving performance.
```python
# Python - Async client usage
import asyncio
import os
from parallelworks_client import Client
async def main():
# Create an authenticated async client
async with Client.from_credential(os.environ["PW_API_KEY"]) as client:
# Fetch buckets and clusters concurrently
buckets_response, clusters_response = await asyncio.gather(
client.get("/api/buckets"),
client.get("/api/clusters"),
)
buckets_response.raise_for_status()
clusters_response.raise_for_status()
buckets = buckets_response.json()
clusters = clusters_response.json()
print(f"Found {len(buckets)} buckets and {len(clusters)} clusters")
# Make additional async requests
orgs_response = await client.get("/api/organizations")
orgs_response.raise_for_status()
print(f"Organizations: {orgs_response.json()}")
asyncio.run(main())
```
--------------------------------
### Credential Helper Functions
Source: https://github.com/parallelworks/sdk/blob/canary/python/README.md
Provides utility functions to check credential types (API key or token) and extract the platform host from a credential.
```python
from parallelworks_client import is_api_key, is_token, extract_platform_host
is_api_key("pwt_abc.xyz") # True
is_token("eyJ.abc.def") # True
extract_platform_host("pwt_...") # "cloud.parallel.works"
```
--------------------------------
### Handle API Errors in Go Client
Source: https://github.com/parallelworks/sdk/blob/canary/go/README.md
Demonstrates how to handle API errors returned by the Parallel Works client using the `errors.Is` function to match against sentinel errors like `ErrNotFound` and `ErrUnauthorized`.
```go
import parallelworks "github.com/parallelworks/sdk/go/v7"
import "context"
import "errors"
// Assume client is already initialized
ctx := context.Background()
_, err := client.ListWorkflows(ctx)
if errors.Is(err, parallelworks.ErrNotFound) {
// handle 404
} else if errors.Is(err, parallelworks.ErrUnauthorized) {
// handle 401
}
```
--------------------------------
### Managing Workflow Runs API
Source: https://context7.com/parallelworks/sdk/llms.txt
Create, monitor, and manage workflow executions programmatically.
```APIDOC
## POST /api/workflow-runs
### Description
Create a new workflow run.
### Method
POST
### Endpoint
/api/workflow-runs
### Request Body
- **workflow** (string) - Required - The name or ID of the workflow to run.
- **name** (string) - Optional - A custom name for the workflow run.
- **inputs** (object) - Optional - Key-value pairs for workflow inputs.
### Request Example
```json
{
"workflow": "my-workflow-name",
"name": "My Run",
"inputs": {
"param1": "value1",
"param2": 42
}
}
```
### Response
#### Success Response (200)
- **slug** (string) - The unique identifier for the workflow run.
- **status** (string) - The current status of the workflow run.
#### Response Example
```json
{
"slug": "run-abc123",
"status": "pending"
}
```
## GET /api/workflow-runs/{slug}
### Description
Retrieve details for a specific workflow run.
### Method
GET
### Endpoint
/api/workflow-runs/{slug}
### Path Parameters
- **slug** (string) - Required - The unique identifier of the workflow run.
### Response
#### Success Response (200)
- **status** (string) - The current status of the workflow run.
#### Response Example
```json
{
"status": "running"
}
```
## GET /api/workflow-runs
### Description
List workflow runs with optional filters.
### Method
GET
### Endpoint
/api/workflow-runs
### Query Parameters
- **status** (array of strings) - Optional - Filter runs by status (e.g., `['running', 'pending']`).
- **limit** (integer) - Optional - The maximum number of runs to return.
### Response
#### Success Response (200)
- **items** (array) - An array of workflow run objects.
#### Response Example
```json
{
"items": [
{
"slug": "run-abc123",
"status": "running"
}
]
}
```
## POST /api/workflow-runs/{slug}/cancel
### Description
Cancel a running workflow run.
### Method
POST
### Endpoint
/api/workflow-runs/{slug}/cancel
### Path Parameters
- **slug** (string) - Required - The unique identifier of the workflow run to cancel.
### Response
#### Success Response (200)
Indicates the cancellation request was accepted. The response body may be empty or contain a confirmation message.
#### Response Example
```json
{
"message": "Cancellation request accepted."
}
```
```
--------------------------------
### Credential Helper Functions
Source: https://github.com/parallelworks/sdk/blob/canary/typescript/README.md
Provides utility functions to check credential types (`isApiKey`, `isToken`) and extract the platform host from a credential string.
```typescript
import { isApiKey, isToken, extractPlatformHost } from '@parallelworks/client'
isApiKey('pwt_abc.xyz') // true
isToken('eyJ.abc.def') // true
extractPlatformHost('pwt_...') // "cloud.parallel.works"
```
--------------------------------
### Credential Helper Functions (TypeScript, Python)
Source: https://context7.com/parallelworks/sdk/llms.txt
Provides utility functions for validating credential types (API key or JWT token) and extracting the platform host from them. These helpers are available in both TypeScript and Python SDKs.
```typescript
// TypeScript credential helpers
import { isApiKey, isToken, extractPlatformHost } from '@parallelworks/client'
const credential = process.env.PW_CREDENTIAL!
// Check credential type
console.log(isApiKey('pwt_abc.xyz')) // true
console.log(isToken('eyJ.abc.def')) // true
// Extract platform host from credential
const host = extractPlatformHost('pwt_Y2xvdWQucGFyYWxsZWwud29ya3M.xxxxx')
console.log(host) // "cloud.parallel.works"
```
```python
# Python credential helpers
from parallelworks_client import is_api_key, is_token, extract_platform_host
```
--------------------------------
### Error Handling API
Source: https://context7.com/parallelworks/sdk/llms.txt
All clients provide structured error handling with typed API errors for common HTTP status codes.
```APIDOC
## Error Handling
### Description
All clients provide structured error handling with typed API errors for common HTTP status codes.
### Response
#### Error Response (e.g., 400, 401, 404, 500)
- **code** (string) - An error code.
- **message** (string) - A human-readable error message.
#### Error Response Example
```json
{
"code": "INVALID_REQUEST",
"message": "The provided workflow ID does not exist."
}
```
### CredentialError
- **message** (string) - Specific message indicating a credential issue.
#### CredentialError Example
```
Invalid credential: API key is missing or invalid.
```
```
--------------------------------
### List Workflows with Parallelworks SDK
Source: https://context7.com/parallelworks/sdk/llms.txt
Retrieve all workflows available to the authenticated user, with options to filter for favorite workflows. This function requires authentication via an API key and returns a list of workflow objects or an error.
```typescript
// TypeScript - List workflows
import { Client } from '@parallelworks/client'
const client = Client.fromCredential(process.env.PW_API_KEY!)
// List all workflows
const { data: workflows, error } = await client.GET('/api/workflows')
if (error) {
console.error('Error:', error)
} else {
console.log('Workflows:')
for (const workflow of workflows ?? []) {
console.log(` - ${workflow.name}: ${workflow.description}`)
}
}
// List only favorite workflows
const { data: favorites } = await client.GET('/api/workflows', {
params: { query: { favoriteOnly: true } }
})
```
```go
// Go - List workflows with typed responses
package main
import (
"context"
"fmt"
"log"
"os"
parallelworks "github.com/parallelworks/sdk/go/v7"
)
func main() {
client, _ := parallelworks.NewClientFromCredential(os.Getenv("PW_API_KEY"))
ctx := context.Background()
// List all workflows
workflows, err := client.ListWorkflows(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("Workflows:")
for _, wf := range *workflows {
fmt.Printf(" - %s: %s\n", wf.Name, wf.Description)
}
// List only favorites
favOnly := true
favorites, _ := client.ListWorkflows(ctx, parallelworks.ListWorkflowsParams{
FavoriteOnly: &favOnly,
})
fmt.Printf("Favorite workflows: %d\n", len(*favorites))
}
```