### Run Example Source: https://github.com/metronome-industries/metronome-go/blob/main/CONTRIBUTING.md Execute your added example using the go run command. ```sh $ go run ./examples/ ``` -------------------------------- ### Add Example to SDK Source: https://github.com/metronome-industries/metronome-go/blob/main/CONTRIBUTING.md Create new example files within the examples/ directory. The generator will not modify this directory. ```go # add an example to examples//main.go package main func main() { // ... } ``` -------------------------------- ### Install Metronome Go SDK Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/00-index.md Use `go get` to install the Metronome Go SDK. Ensure your Go version is 1.22 or higher. ```bash go get github.com/Metronome-Industries/metronome-go/v3 ``` -------------------------------- ### Bootstrap and Lint Repository Source: https://github.com/metronome-industries/metronome-go/blob/main/CONTRIBUTING.md Run these scripts to install dependencies and build the SDK. Ensure Go 1.22+ is installed. ```sh $ ./scripts/bootstrap $ ./scripts/lint ``` -------------------------------- ### Example Output of DumpResponse() Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/05-error-handling.md Shows an example of the serialized HTTP response details that can be obtained using the `DumpResponse(true)` method. ```text HTTP/1.1 400 Bad Request Content-Type: application/json Date: Mon, 15 Jan 2024 10:30:00 GMT {"error_code": "INVALID_REQUEST", "message": "customer_id is required"} ``` -------------------------------- ### Example Output of DumpRequest() Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/05-error-handling.md Shows an example of the serialized HTTP request details that can be obtained using the `DumpRequest(true)` method. ```text POST /v1/customers HTTP/1.1 Host: api.metronome.com Authorization: Bearer ... Content-Type: application/json {"customer_id": "cust_123", ...} ``` -------------------------------- ### Manual Pagination Example Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/04-pagination.md Iterates through all pages of results manually by repeatedly calling GetNextPage until all data is fetched. ```go page, err := client.V1.Customers.List(ctx, params) if err != nil { panic(err) } for page != nil { for _, customer := range page.Data { fmt.Printf("Customer: %s\n", customer.ID) } page, err = page.GetNextPage() if err != nil { panic(err) } } ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/metronome-industries/metronome-go/blob/main/README.md Provides an example of enabling debug logging for the request options, which can be helpful during debugging. ```go option.WithDebugLog(nil) ``` -------------------------------- ### Create Customer with Optional Parameters Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/03-parameters-and-responses.md Example of creating a new customer, setting a required field and optional fields using factory functions. ```go params := metronome.V1CustomerNewParams{ CustomerID: "required-field", Name: metronome.String("optional-name"), Archived: metronome.Bool(false), } ``` -------------------------------- ### Example Usage of DumpResponse() Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/05-error-handling.md Demonstrates how to use the `DumpResponse()` method to print the serialized HTTP response, including the body, to standard output. ```go fmt.Println(string(apierr.DumpResponse(true))) ``` -------------------------------- ### List Plans Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves a paginated list of plans. Use this to get an overview of available plans. ```go client.V1.Plans.List(ctx context.Context, query metronome.V1PlanListParams) (*pagination.CursorPage[metronome.V1PlanListResponse], error) ``` -------------------------------- ### Example Usage of DumpRequest() Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/05-error-handling.md Demonstrates how to use the `DumpRequest()` method to print the serialized HTTP request, including the body, to standard output. ```go fmt.Println(string(apierr.DumpRequest(true))) ``` -------------------------------- ### Initialize Metronome Client and Ingest Usage Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/00-index.md Create a Metronome client using `NewClient` and optionally provide a bearer token. This example demonstrates sending a single usage event. ```go package main import ( "context" "github.com/Metronome-Industries/metronome-go/v3" "github.com/Metronome-Industries/metronome-go/v3/option" ) func main() { // Create client (reads METRONOME_BEARER_TOKEN from environment) client := metronome.NewClient( option.WithBearerToken("my-api-token"), ) // Send usage event err := client.V1.Usage.Ingest(context.Background(), metronome.V1UsageIngestParams{ Usage: []metronome.V1UsageIngestParamsUsage{ { TransactionID: "evt_12345", CustomerID: "cust_abc", EventType: "api_request", Timestamp: "2024-01-15T10:30:00Z", Properties: map[string]any{ "endpoint": "/api/users", "method": "GET", }, }, }, }, ) if err != nil { panic(err) } } ``` -------------------------------- ### Get Package Details Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieve details for a specific package using its parameters. Requires a context and package identification parameters. ```go client.V1.Packages.Get(ctx context.Context, body metronome.V1PackageGetParams) (*metronome.V1PackageGetResponse, error) ``` -------------------------------- ### Automatic Pagination Example Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/04-pagination.md Iterates through all items across all pages using the automatic pagination iterator. Ensures to check for errors after iteration. ```go iter := client.V1.Customers.ListAutoPaging(ctx, params) for iter.Next() { customer := iter.Current() fmt.Printf("Customer: %s\n", customer.ID) } if err := iter.Err(); err != nil { panic(err) } ``` -------------------------------- ### Create a New Contract Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/api-reference/03-contracts.md Use this method to establish pricing terms, billing periods, and define billable products for a customer. It requires customer ID and a start date, with optional fields for name, end date, custom fields, and billing cycle anchor day. ```go package main import ( "context" "fmt" "time" "github.com/Metronome-Industries/metronome-go/v3" "github.com/Metronome-Industries/metronome-go/v3/option" ) func main() { client := metronome.NewClient( option.WithBearerToken("my-token"), ) resp, err := client.V1.Contracts.New(context.Background(), metronome.V1ContractNewParams{ CustomerID: "cust_123", StartingAt: time.Now(), Name: metronome.String("Standard Plan"), BillingCycleAnchorDay: metronome.Int(1), }, ) if err != nil { panic(err) } fmt.Printf("Created contract: %s\n", resp.Data.ID) } ``` -------------------------------- ### Get Plan Details Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves detailed information for a specific plan. Use this when you need in-depth data about a single plan. ```go client.V1.Plans.GetDetails(ctx context.Context, query metronome.V1PlanGetDetailsParams) (*metronome.V1PlanGetDetailsResponse, error) ``` -------------------------------- ### Configure Custom HTTP Client Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/02-request-options.md Replace the default HTTP client with a custom implementation, for example, to set specific timeouts or transport configurations. ```go httpClient := &http.Client{ Timeout: 30 * time.Second, Transport: &http.Transport{ MaxIdleConns: 100, }, } client := metronome.NewClient( option.WithHTTPClient(httpClient), ) ``` -------------------------------- ### Get Customer Billing Configurations (Go) Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves the current billing provider configurations for a customer. Requires a context and parameters specifying which configurations to fetch. ```go client.V1.Customers.GetBillingConfigurations(ctx context.Context, body metronome.V1CustomerGetBillingConfigurationsParams) (*metronome.V1CustomerGetBillingConfigurationsResponse, error) ``` -------------------------------- ### Go: Add Customer Plan Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/api-reference/05-invoices-and-plans.md Adds a plan to a customer, specifying the customer ID, plan ID, and start time. Handles potential errors during addition. ```go resp, err := client.V1.Customers.Plans.Add(context.Background(), metronome.V1CustomerPlanAddParams{ CustomerID: "cust_123", PlanID: "plan_standard", StartingAt: metronome.Time(time.Now()), }, ) if err != nil { panic(err) } fmt.Printf("Added plan: %s\n", resp.Data.ID) ``` -------------------------------- ### Convenience HTTP Methods (Get, Post, Put, Patch, Delete) Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/01-client-initialization.md Provides convenience methods for common HTTP operations. These methods delegate to the `Execute` method and simplify making standard requests. ```go func (r *Client) Get(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error func (r *Client) Post(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error func (r *Client) Put(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error func (r *Client) Patch(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error func (r *Client) Delete(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error ``` ```go var result map[string]interface{} err := client.Get(context.Background(), "/custom/endpoint", nil, &result) if err != nil { panic(err) } ``` -------------------------------- ### Client Creation Configuration Validation Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/07-configuration.md Invalid options provided during client creation will cause a panic. This example shows a negative value for MaxRetries, which is an invalid configuration. ```go // These panic during NewClient if invalid client := metronome.NewClient( option.WithMaxRetries(-1), // Panics: cannot be negative ) ``` -------------------------------- ### Get Contract Details (Go) Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves detailed information for a specific contract using its parameters. Requires the context and contract parameters. ```go client.V2.Contracts.Get(ctx context.Context, body metronome.V2ContractGetParams) (*metronome.V2ContractGetResponse, error) ``` -------------------------------- ### Get Contract Pricing Product Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieve details of a specific contract pricing product using its parameters. Requires a context and product identification parameters. ```go client.V1.Contracts.Products.Get(ctx context.Context, body metronome.V1ContractProductGetParams) (*metronome.V1ContractProductGetResponse, error) ``` -------------------------------- ### Apply Middleware to Requests Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/02-request-options.md Add one or more middleware functions to process requests and responses. Middleware functions are executed in the order they are provided. Example includes a logging middleware. ```go func LoggingMiddleware(req *http.Request, next option.MiddlewareNext) (*http.Response, error) { log.Printf("Request: %s %s", req.Method, req.URL) res, err := next(req) if err != nil { log.Printf("Error: %v", err) } else { log.Printf("Response: %d", res.StatusCode) } return res, err } client := metronome.NewClient( option.WithMiddleware(LoggingMiddleware), ) ``` -------------------------------- ### Add Authentication and Logging Middleware Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/07-configuration.md Implement custom middleware to intercept and modify requests or responses. This example logs request details and response status codes. ```go func AuthLoggingMiddleware(req *http.Request, next option.MiddlewareNext) (*http.Response, error) { // Before request fmt.Printf("Request: %s %s\n", req.Method, req.URL) // Call next handler res, err := next(req) // After response if err != nil { fmt.Printf("Error: %v\n", err) } else { fmt.Printf("Response: %d\n", res.StatusCode) } return res, err } client := metronome.NewClient( option.WithMiddleware(AuthLoggingMiddleware), ) ``` -------------------------------- ### Fetch Single Page and Get Next Page Source: https://github.com/metronome-industries/metronome-go/blob/main/README.md Illustrates fetching a single page of results using `.List()` and then using `.GetNextPage()` to retrieve subsequent pages. ```go page, err := client.V1.Contracts.Products.List(context.TODO(), metronome.V1ContractProductListParams{}) for page != nil { for _, product := range page.Data { fmt.Printf("%+v\n", product) } page, err = page.GetNextPage() } if err != nil { panic(err.Error()) } ``` -------------------------------- ### Set up Mock Server Source: https://github.com/metronome-industries/metronome-go/blob/main/CONTRIBUTING.md Run this script to set up a mock server required for running most tests against the OpenAPI spec. ```sh $ ./scripts/mock ``` -------------------------------- ### Initialize Metronome Client and Ingest Usage Data Source: https://github.com/metronome-industries/metronome-go/blob/main/README.md Initialize the Metronome client with a bearer token and ingest usage data. This example demonstrates a typical API call for tracking usage events. ```go package main import ( "context" "github.com/Metronome-Industries/metronome-go/v3" "github.com/Metronome-Industries/metronome-go/v3/option" ) func main() { client := metronome.NewClient( option.WithBearerToken("My Bearer Token"), // defaults to os.LookupEnv("METRONOME_BEARER_TOKEN") ) err := client.V1.Usage.Ingest(context.TODO(), metronome.V1UsageIngestParams{ Usage: []metronome.V1UsageIngestParamsUsage{{ TransactionID: "90e9401f-0f8c-4cd3-9a9f-d6beb56d8d72", CustomerID: "team@example.com", EventType: "heartbeat", Timestamp: "2024-01-01T00:00:00Z", Properties: map[string]any{ "cluster_id": "42", "cpu_seconds": 60, "region": "Europe", }, }}, }) if err != nil { panic(err.Error()) } } ``` -------------------------------- ### Create a New Package Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Use this to create a new package. It requires a context and parameters for the new package. ```go client.V1.Packages.New(ctx context.Context, body metronome.V1PackageNewParams) (*metronome.V1PackageNewResponse, error) ``` -------------------------------- ### Work with Optional Parameters Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/00-index.md Demonstrates how to set optional parameters, check if they were omitted, and explicitly set a parameter to null using helper functions. ```go params := metronome.V1CustomerNewParams{ CustomerID: "required-field", Name: metronome.String("optional-name"), CustomFields: metronome.Map(map[string]any{ "account_type": "enterprise", }), } // Check if field is omitted if param.IsOmitted(params.Name) { fmt.Println("Name was not provided") } // Set to null instead of omitting params.Name = param.Null[string]() ``` -------------------------------- ### Get, Post, Put, Patch, Delete Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/01-client-initialization.md Convenience methods for standard HTTP methods (GET, POST, PUT, PATCH, DELETE). These methods delegate to the `Execute` method for simplified request execution. ```APIDOC ## Get, Post, Put, Patch, Delete ```go func (r *Client) Get(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error func (r *Client) Post(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error func (r *Client) Put(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error func (r *Client) Patch(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error func (r *Client) Delete(ctx context.Context, path string, params any, res any, opts ...option.RequestOption) error ``` ### Description Convenience methods for standard HTTP methods. All delegate to `Execute()`. ### Example ```go var result map[string]interface{} err := client.Get(context.Background(), "/custom/endpoint", nil, &result) if err != nil { panic(err) } ``` ``` -------------------------------- ### Get Invoice Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/api-reference/05-invoices-and-plans.md Retrieve a specific invoice by its ID. ```APIDOC ## Get Invoice ### Description Retrieve a specific invoice by its ID. ### Method GET ### Endpoint /v1/invoices/{invoice_id} ### Parameters #### Path Parameters - **invoice_id** (string) - Required - The invoice ID to retrieve ### Response #### Success Response (200) - **Data** (Invoice) - Invoice object with full details ### Response Example ```json { "data": { "id": "invoice_xyz123", "invoice_number": "INV-00002", "status": "FINALIZED", "total": 25000, "issued_at": "2023-10-28T11:00:00Z" } } ``` ``` -------------------------------- ### Initialize Client with Request Options Source: https://github.com/metronome-industries/metronome-go/blob/main/README.md Demonstrates initializing the Metronome client with functional options, such as adding a custom header to all requests. ```go client := metronome.NewClient( // Adds a header to every request made by the client option.WithHeader("X-Some-Header", "custom_header_info"), ) ``` -------------------------------- ### Initialize Client with Base URL Option Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/07-configuration.md Provide a custom API base URL when creating the client using option.WithBaseURL(). ```go client := metronome.NewClient( option.WithBaseURL("https://custom.api.example.com/"), ) ``` -------------------------------- ### Get Net Balance Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves the net balance for a customer's contract. ```APIDOC ## POST /v1/contracts/customerBalances/getNetBalance ### Description Retrieves the net balance for a customer's contract. ### Method POST ### Endpoint /v1/contracts/customerBalances/getNetBalance ### Request Body - **body** (V1ContractGetNetBalanceParams) - Required - Parameters for retrieving the net balance. ``` -------------------------------- ### Get Rate Schedule Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves the rate schedule for a specific contract rate card. ```APIDOC ## POST /v1/contract-pricing/rate-cards/getRateSchedule ### Description Retrieves the rate schedule for a specific contract rate card. ### Method POST ### Endpoint /v1/contract-pricing/rate-cards/getRateSchedule ### Parameters #### Query Parameters - **params** (V1ContractRateCardGetRateScheduleParams) - Required - Parameters to identify the rate card for which to retrieve the schedule. ### Response #### Success Response (200) - **V1ContractRateCardGetRateScheduleResponse** - The rate schedule details for the specified rate card. ``` -------------------------------- ### Get Billable Metric Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves details for a specific billable metric using its ID. ```APIDOC ## GET /v1/billable-metrics/{billable_metric_id} ### Description Retrieves details for a specific billable metric. ### Method GET ### Endpoint /v1/billable-metrics/{billable_metric_id} ### Parameters #### Query Parameters - **query** (metronome.V1BillableMetricGetParams) - Required - Parameters for retrieving a billable metric, typically including the billable_metric_id. ### Response #### Success Response (200) - **response** (*metronome.V1BillableMetricGetResponse) - The response object containing details of the requested billable metric. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Initialize Client with Custom Header Options Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/07-configuration.md Add custom headers to all requests by providing them individually using option.WithHeader() when creating the client. ```go client := metronome.NewClient( option.WithHeader("X-Request-ID", "correlation-123"), option.WithHeader("X-Tenant-ID", "tenant-456"), ) ``` -------------------------------- ### Create Customer and Ingest Usage Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/00-index.md Demonstrates the process of creating a new customer, sending a usage event, and then retrieving customer details using the V1Service. ```go client.V1 ├── Customers - Customer lifecycle management │ ├── Alerts - Spending alerts │ ├── Plans - Customer pricing plans │ ├── Invoices - Customer billing │ ├── BillingConfig - Payment provider configuration │ ├── Credits - Credit balance management │ ├── Commits - Commitment tracking │ └── NamedSchedules - Custom time-series data ├── Usage - Event ingestion and aggregation ├── Contracts - Pricing agreements │ ├── Products - Contract products │ ├── RateCards - Pricing tables │ └── NamedSchedules - Custom pricing data ├── CreditGrants - Promotional credits ├── Invoices - Invoice retrieval ├── Plans - Pricing plan management ├── Alerts - Account-level alerts ├── CustomFields - Custom entity metadata ├── BillableMetrics - Consumption definitions ├── PricingUnits - Pricing unit configuration ├── Dashboards - Analytics endpoints ├── Settings - Account settings ├── AuditLogs - Security audit logging └── Services - Service metadata client.V2 ├── Contracts - Enhanced contract operations └── ... - Additional V2 endpoints ``` ```go // 1. Create customer customerResp, _ := client.V1.Customers.New(ctx, metronome.V1CustomerNewParams{ CustomerID: "acme-corp", Name: metronome.String("ACME Corporation"), }, ) // 2. Send usage event _ = client.V1.Usage.Ingest(ctx, metronome.V1UsageIngestParams{ Usage: []metronome.V1UsageIngestParamsUsage{ { TransactionID: "evt_123", CustomerID: customerResp.Data.ID, EventType: "api_request", Timestamp: time.Now().Format(time.RFC3339), Properties: map[string]any{"endpoint": "/api/data"}, }, }, }, ) // 3. Retrieve customer details detailResp, _ := client.V1.Customers.Get(ctx, metronome.V1CustomerGetParams{ CustomerID: customerResp.Data.ID, }, ) ``` -------------------------------- ### Get Customer Billing Provider Configurations Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves the billing provider configurations for a specific customer. ```APIDOC ## POST /v1/getCustomerBillingProviderConfigurations ### Description Retrieves the billing provider configurations for a specific customer. ### Method POST ### Endpoint /v1/getCustomerBillingProviderConfigurations ### Parameters #### Request Body - **customer_id** (string) - Required - The ID of the customer whose billing configurations are to be retrieved. ### Response #### Success Response (200) - **configurations** (object) - An object containing the billing provider configurations. #### Response Example { "configurations": { "provider": "stripe", "api_key": "sk_test_..." } } ``` -------------------------------- ### List Packages Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Fetch a paginated list of packages. Accepts a context and pagination parameters. ```go client.V1.Packages.List(ctx context.Context, params metronome.V1PackageListParams) (*pagination.CursorPage[metronome.V1PackageListResponse], error) ``` -------------------------------- ### Get Plan Details Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/api-reference/05-invoices-and-plans.md Retrieve details for a specific pricing plan using its unique ID. ```APIDOC ## Get Plan Details ### Description Retrieve details for a specific pricing plan. ### Method GET ### Endpoint /v1/plans/{plan_id} ### Parameters #### Path Parameters - **plan_id** (string) - Required - The ID of the plan to retrieve. #### Query Parameters None #### Request Body None ### Request Example ```go resp, err := client.V1.Plans.Get(context.Background(), metronome.V1PlanGetParams{ PlanID: "plan_standard_monthly" }) if err != nil { panic(err) } fmt.Printf("Plan: %s\n", resp.Data.Name) ``` ### Response #### Success Response (200) - **Data** (*V1PlanGetResponse) - Plan object with pricing details ``` -------------------------------- ### Create Contract Pricing Product Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Use this method to create a new contract pricing product. It requires a context and parameters for the new product. ```go client.V1.Contracts.Products.New(ctx context.Context, body metronome.V1ContractProductNewParams) (*metronome.V1ContractProductNewResponse, error) ``` -------------------------------- ### Run Tests Source: https://github.com/metronome-industries/metronome-go/blob/main/CONTRIBUTING.md Execute the test suite for the SDK. ```sh $ ./scripts/test ``` -------------------------------- ### V1 Contract Named Schedules Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Provides methods to get and update general named schedules for contracts. ```APIDOC ## POST /v1/contract-pricing/rate-cards/getNamedSchedule ### Description Retrieves a specific named schedule for contract pricing. ### Method POST ### Endpoint /v1/contract-pricing/rate-cards/getNamedSchedule ### Parameters #### Request Body - **body** (V1ContractNamedScheduleGetParams) - Required - Parameters for retrieving a named schedule. ### Response #### Success Response (200) - **V1ContractNamedScheduleGetResponse** - The details of the named schedule. ## POST /v1/contract-pricing/rate-cards/updateNamedSchedule ### Description Updates a specific named schedule for contract pricing. ### Method POST ### Endpoint /v1/contract-pricing/rate-cards/updateNamedSchedule ### Parameters #### Request Body - **body** (V1ContractNamedScheduleUpdateParams) - Required - Parameters for updating a named schedule. ### Response #### Success Response (200) - **error** - Returns an error if the update fails. ``` -------------------------------- ### Get Customer Alert Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves a specific customer alert. Requires the alert details in the request body. ```APIDOC ## POST /v1/customer-alerts/get ### Description Retrieves a specific customer alert. ### Method POST ### Endpoint /v1/customer-alerts/get ### Parameters #### Request Body - **alert_id** (string) - Required - The ID of the alert to retrieve. ### Request Example ```json { "alert_id": "alert-123" } ``` ### Response #### Success Response (200) - **alert** (metronome.CustomerAlert) - The retrieved customer alert object. #### Response Example ```json { "alert": { "id": "alert-123", "message": "Example alert message" } } ``` ``` -------------------------------- ### Initialize Client with Bearer Token Option Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/07-configuration.md Alternatively, provide the bearer token explicitly when creating the client using option.WithBearerToken(). ```go client := metronome.NewClient( option.WithBearerToken("sk_live_abc123def456..."), ) ``` -------------------------------- ### Get Customer Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves a specific customer by their ID. Requires customer ID and optional query parameters. ```APIDOC ## GET /v1/customers/{customer_id} ### Description Retrieves a specific customer's details using their unique identifier. ### Method GET ### Endpoint /v1/customers/{customer_id} ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier of the customer. #### Query Parameters - **query** (metronome.V1CustomerGetParams) - Required - Parameters for retrieving the customer. ### Response #### Success Response (200) - **V1CustomerGetResponse** (metronome.V1CustomerGetResponse) - The details of the requested customer. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Get Net Balance Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/api-reference/03-contracts.md Retrieves the combined current balance across credits and commits for a specific customer. ```APIDOC ## Get Net Balance ### Description Retrieve the combined current balance across any grouping of credits and commits for a customer. ### Purpose - Display real-time available balance to customers in billing dashboards - Validate expected vs. actual balance during reconciliation - Build finance dashboards showing credit utilization ### Method `GetNetBalance` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **body** (`V1ContractGetNetBalanceParams`) - Required - Balance query parameters - **CustomerID** (`string`) - Required - Customer to query balance for - **BalanceFilters** (`param.Opt[[]any]`) - Optional - Filters for specific balances - **InvoiceInclusionMode** (`param.Opt[string]`) - Optional - Include draft invoices (default: "FINALIZED_AND_DRAFT") - **CreditTypeID** (`param.Opt[string]`) - Optional - Specific credit type filter ### Response #### Success Response - `*V1ContractGetNetBalanceResponse`: Combined balance object ### Example ```go resp, err := client.V1.Contracts.GetNetBalance(context.Background(), metronome.V1ContractGetNetBalanceParams{ CustomerID: "cust_123", }, ) if err != nil { panic(err) } fmt.Printf("Available balance: %.2f cents\n", resp.Data.Balance) ``` ``` -------------------------------- ### Production Client Configuration Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/07-configuration.md Configure the client for production with a robust retry strategy and multiple middleware for logging and metrics. Use context with timeout for requests. ```go client := metronome.NewClient( // Bearer token from environment option.WithMaxRetries(3), // Robust retry strategy option.WithMiddleware(LoggingMiddleware, MetricsMiddleware), ) // Set context timeout per request ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() ``` -------------------------------- ### Constructing Usage List Parameters Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/api-reference/02-usage.md Use this snippet to define parameters for fetching usage data, specifying a date range and window size. Ensure timestamps are in RFC3339 format. ```go now := time.Now().UTC() startOfMonth := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC) params := metronome.V1UsageListParams{ StartingOn: startOfMonth.Format(time.RFC3339), EndingBefore: now.Format(time.RFC3339), WindowSize: metronome.String("day"), } ``` -------------------------------- ### Get Customer Net Balance Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/README.md Fetch the net balance for a specific customer. The balance is returned in cents. ```go resp, _ := client.V1.Contracts.GetNetBalance(ctx, metronome.V1ContractGetNetBalanceParams{ CustomerID: "cust_123", }, ) fmt.Printf("Balance: %s cents\n", resp.Data.Balance) ``` -------------------------------- ### Example Output of Error() Method Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/05-error-handling.md Illustrates the formatted error message produced by the `Error()` method of the `metronome.Error` type. ```text POST "/v1/customers": 400 Bad Request {"error": "customer_id is required"} ``` -------------------------------- ### Get Customer Invoice Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves a specific invoice for a given customer. Requires customer ID and invoice ID. ```APIDOC ## GET /v1/customers/{customer_id}/invoices/{invoice_id} ### Description Retrieves a specific invoice for a given customer. ### Method GET ### Endpoint /v1/customers/{customer_id}/invoices/{invoice_id} ### Parameters #### Path Parameters - **customer_id** (string) - Required - The ID of the customer. - **invoice_id** (string) - Required - The ID of the invoice. ### Response #### Success Response (200) - **V1CustomerInvoiceGetResponse** (*metronome.V1CustomerInvoiceGetResponse) - The response object containing invoice details. ``` -------------------------------- ### User Code: Constructing a Request with New SDK Patterns Source: https://github.com/metronome-industries/metronome-go/blob/main/MIGRATION.md Illustrates how to construct a request object using the updated SDK, replacing calls to `metronome.F` with direct assignments and utilizing `metronome.String` for optional primitives. ```go foo = FooParams{ - RequiredString: metronome.String("hello"), + RequiredString: "hello", - OptionalString: metronome.String("hi"), + OptionalString: metronome.String("hi"), - Array: metronome.F([]BarParam{ - BarParam{Prop: ... } - }), + Array: []BarParam{ + BarParam{Prop: ... } + }, - RequiredObject: metronome.F(BarParam{ ... }), + RequiredObject: BarParam{ ... }, - OptionalObject: metronome.F(BarParam{ ... }), + OptionalObject: BarParam{ ... }, - StringEnum: metronome.F[BazEnum]("baz-ok"), + StringEnum: "baz-ok", } ``` -------------------------------- ### Get Customer Alert Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves a specific customer alert using its identifier. The response includes details about the alert. ```go client.V1.Customers.Alerts.Get(ctx context.Context, body metronome.V1CustomerAlertGetParams) (*metronome.V1CustomerAlertGetResponse, error) ``` -------------------------------- ### List All Pricing Plans Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/api-reference/05-invoices-and-plans.md Retrieve a paginated list of all pricing plans available in the system. This method allows for fetching plans in batches, controlled by a limit parameter. ```go page, err := client.V1.Plans.List(context.Background(), metronome.V1PlanListParams{ Limit: metronome.Int(50), }, ) if err != nil { panic(err) } for _, plan := range page.Data { fmt.Printf("- %s (ID: %s)\n", plan.Name, plan.ID) } ``` -------------------------------- ### Get Contract Rate Schedule (Go) Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves the rate schedule for a specific contract rate card. Requires V1ContractRateCardGetRateScheduleParams. ```go client.V1.Contracts.RateCards.GetRateSchedule(ctx context.Context, params metronome.V1ContractRateCardGetRateScheduleParams) (*metronome.V1ContractRateCardGetRateScheduleResponse, error) ``` -------------------------------- ### Get Rate Card Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves an existing rate card. This operation requires a context and parameters to identify the rate card. ```APIDOC ## POST /v1/contract-pricing/rate-cards/get ### Description Retrieves an existing rate card. ### Method POST ### Endpoint /v1/contract-pricing/rate-cards/get ### Parameters #### Request Body - **body** (V1ContractRateCardGetParams) - Required - Parameters to identify the rate card. ### Response #### Success Response (200) - **response** (*V1ContractRateCardGetResponse) - The response object containing details of the retrieved rate card. #### Error Handling - Returns an error if the rate card retrieval fails. ``` -------------------------------- ### Get Named Schedule Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves a specific named schedule for a customer. Requires a context and parameters defining the schedule to retrieve. ```go client.V1.Customers.NamedSchedules.Get(ctx context.Context, body metronome.V1CustomerNamedScheduleGetParams) (*metronome.V1CustomerNamedScheduleGetResponse, error) ``` -------------------------------- ### Batch Customer Creation with Metronome Go SDK Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/08-advanced-patterns.md Create multiple customers in a loop using the Metronome Go SDK. Handles individual errors by logging and continuing to the next customer. ```go func bulkCreateCustomers(ctx context.Context, client *metronome.Client, customerList []string) ([]string, error) { createdIDs := make([]string, 0) for _, name := range customerList { resp, err := client.V1.Customers.New(ctx, metronome.V1CustomerNewParams{ CustomerID: name, Name: metronome.String(name), }, ) if err != nil { // Handle error - could skip, log, or fail fmt.Printf("Failed to create customer %s: %v\n", name, err) continue } createdIDs = append(createdIDs, resp.Data.ID) } return createdIDs, nil } ``` -------------------------------- ### Get Customer Invoice PDF Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves the PDF for a specific customer invoice. Requires customer ID and invoice ID. ```APIDOC ## GET /v1/customers/{customer_id}/invoices/{invoice_id}/pdf ### Description Retrieves the PDF for a specific customer invoice. ### Method GET ### Endpoint /v1/customers/{customer_id}/invoices/{invoice_id}/pdf ### Parameters #### Path Parameters - **customer_id** (string) - Required - The ID of the customer. - **invoice_id** (string) - Required - The ID of the invoice. #### Query Parameters - **query** (*metronome.V1CustomerInvoiceGetPdfParams) - Required - Parameters for retrieving the invoice PDF. ``` -------------------------------- ### Initialize Client Automatically Reading Environment Variables Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/07-configuration.md Create a new Metronome client. If no options are provided, it automatically reads configuration from environment variables. ```go client := metronome.NewClient() ``` -------------------------------- ### Get Customer by ID Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves a specific customer using their unique identifier. Requires a context and customer ID parameters. ```go client.V1.Customers.Get(ctx context.Context, query metronome.V1CustomerGetParams) (*metronome.V1CustomerGetResponse, error) ``` -------------------------------- ### List Customers with Manual and Auto Pagination Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/00-index.md Shows how to retrieve a list of customers using both manual pagination (handling page tokens) and automatic pagination (using an iterator). ```go // Manual pagination page, _ := client.V1.Customers.List(ctx, metronome.V1CustomerListParams{ Limit: metronome.Int(50), }, ) for page != nil { for _, customer := range page.Data { fmt.Printf("Customer: %s\n", customer.Name) } if page.NextPage == "" { break } page, _ = page.GetNextPage() } // Or automatic pagination iter := client.V1.Customers.ListAutoPaging(ctx, metronome.V1CustomerListParams{}, ) for iter.Next() { customer := iter.Current() fmt.Printf("Customer: %s\n", customer.Name) } ``` -------------------------------- ### Using Auto-Paging for Iteration Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/04-pagination.md Demonstrates the recommended approach for iterating through paginated results using the auto-paging feature for simplicity. ```go // Good: Automatic paging iter := client.V1.Customers.ListAutoPaging(ctx, params) for iter.Next() { process(iter.Current()) } ``` -------------------------------- ### List All Pricing Plans Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/api-reference/05-invoices-and-plans.md List all available pricing plans, with options for pagination. ```APIDOC ## List All Pricing Plans ### Description List all pricing plans. Supports pagination. ### Method GET ### Endpoint /v1/plans ### Parameters #### Path Parameters None #### Query Parameters - **Limit** (param.Opt[int64]) - Optional - Items per page. - **NextPage** (param.Opt[string]) - Optional - Pagination cursor. #### Request Body None ### Request Example ```go page, err := client.V1.Plans.List(context.Background(), metronome.V1PlanListParams{ Limit: metronome.Int(50) }) if err != nil { panic(err) } for _, plan := range page.Data { fmt.Printf("- %s (ID: %s)\n", plan.Name, plan.ID) } ``` ### Response #### Success Response (200) - **Data** (*pagination.CursorPage[Plan]) - Page of plan objects ``` -------------------------------- ### Get Contract Rate Schedule Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves the rate schedule for a specific contract. This is useful for understanding the pricing and billing structure of a contract. ```APIDOC ## POST /v1/contracts/getContractRateSchedule ### Description Retrieves the rate schedule for a specific contract. This is useful for understanding the pricing and billing structure of a contract. ### Method POST ### Endpoint /v1/contracts/getContractRateSchedule ### Parameters #### Request Body - **params** (V1ContractGetRateScheduleParams) - Required - Parameters for retrieving the contract rate schedule. ### Response #### Success Response (200) - **V1ContractGetRateScheduleResponse** - The response containing the contract's rate schedule. ``` -------------------------------- ### Development Client Configuration Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/07-configuration.md Configure the client for development with a bearer token from an environment variable and disabled retries for fast failure feedback. Set a short request timeout. ```go client := metronome.NewClient( option.WithBearerToken(os.Getenv("METRONOME_BEARER_TOKEN")), option.WithMaxRetries(0), // Fast failures during development option.WithRequestTimeout(5*time.Second), ) ``` -------------------------------- ### POST /v1/packages/create Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Creates a new package. This operation requires a context and package creation parameters. ```APIDOC ## POST /v1/packages/create ### Description Creates a new package. ### Method POST ### Endpoint /v1/packages/create ### Parameters #### Request Body - **body** (metronome.V1PackageNewParams) - Required - Parameters for creating a new package. ### Response #### Success Response (200) - **response** (metronome.V1PackageNewResponse) - The response object upon successful package creation. #### Error Response - **error** (error) - An error object if the package creation fails. ``` -------------------------------- ### Apply Request Options to Individual Requests Source: https://github.com/metronome-industries/metronome-go/blob/main/README.md Shows how to override client-level options or add specific options, like setting a JSON path, for individual requests. ```go client.V1.Contracts.New(context.TODO(), ..., // Override the header option.WithHeader("X-Some-Header", "some_other_custom_header_info"), // Add an undocumented field to the request body, using sjson syntax option.WithJSONSet("some.json.path", map[string]string{"my": "object"}), ) ``` -------------------------------- ### POST /v1/packages/list Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Lists all packages. This operation requires a context and pagination parameters. ```APIDOC ## POST /v1/packages/list ### Description Lists all packages with optional pagination. ### Method POST ### Endpoint /v1/packages/list ### Parameters #### Query Parameters - **params** (metronome.V1PackageListParams) - Required - Parameters for listing packages, including pagination. ### Response #### Success Response (200) - **response** (pagination.CursorPage[metronome.V1PackageListResponse]) - A paginated list of packages. #### Error Response - **error** (error) - An error object if the package listing fails. ``` -------------------------------- ### V1 Contract Rate Card Named Schedules Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Provides methods to get and update named schedules associated with contract rate cards. ```APIDOC ## POST /v1/contracts/getNamedSchedule ### Description Retrieves a specific named schedule associated with a contract rate card. ### Method POST ### Endpoint /v1/contracts/getNamedSchedule ### Parameters #### Request Body - **body** (V1ContractRateCardNamedScheduleGetParams) - Required - Parameters for retrieving a named schedule. ### Response #### Success Response (200) - **V1ContractRateCardNamedScheduleGetResponse** - The details of the named schedule. ## POST /v1/contracts/updateNamedSchedule ### Description Updates an existing named schedule associated with a contract rate card. ### Method POST ### Endpoint /v1/contracts/updateNamedSchedule ### Parameters #### Request Body - **body** (V1ContractRateCardNamedScheduleUpdateParams) - Required - Parameters for updating a named schedule. ### Response #### Success Response (200) - **error** - Returns an error if the update fails. ``` -------------------------------- ### Get Contract Pricing Product Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves details of a specific contract pricing product. This method is part of the V1 Contract Product Service. ```APIDOC ## POST /v1/contract-pricing/products/get ### Description Retrieves details of a specific contract pricing product. ### Method POST ### Endpoint /v1/contract-pricing/products/get ### Parameters #### Request Body - **body** (metronome.V1ContractProductGetParams) - Required - Parameters for retrieving a contract product. ### Response #### Success Response (200) - **response** (*metronome.V1ContractProductGetResponse) - The response object containing details of the requested product. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Get Net Balance for Contract Customer Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves the net balance for a customer associated with a contract. Requires specifying the customer and contract context. ```go client.V1.Contracts.GetNetBalance(ctx context.Context, body metronome.V1ContractGetNetBalanceParams) (*metronome.V1ContractGetNetBalanceResponse, error) ``` -------------------------------- ### Archive a Package Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Archive an existing package. This operation requires a context and parameters specifying the package to archive. ```go client.V1.Packages.Archive(ctx context.Context, body metronome.V1PackageArchiveParams) (*metronome.V1PackageArchiveResponse, error) ``` -------------------------------- ### Manual Paging for Granular Control Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/04-pagination.md Illustrates manual pagination, suitable for scenarios requiring finer control over page processing, streaming, or custom backoff strategies. ```go // Better control over pagination page, _ := client.V1.Customers.List(ctx, params) for page != nil { // Process page... page, _ = page.GetNextPage() } ``` -------------------------------- ### Get Named Schedule Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves a specific named schedule for a customer. This method allows fetching schedule details using provided parameters. ```APIDOC ## POST /v1/customers/getNamedSchedule ### Description Retrieves a specific named schedule for a customer. ### Method POST ### Endpoint /v1/customers/getNamedSchedule ### Parameters #### Request Body - **body** (V1CustomerNamedScheduleGetParams) - Required - Parameters for retrieving a named schedule. ### Response #### Success Response (200) - **(V1CustomerNamedScheduleGetResponse)** - The response contains details of the named schedule. ``` -------------------------------- ### Get Billing Configuration Source: https://github.com/metronome-industries/metronome-go/blob/main/api.md Retrieves the billing configuration for a specific customer and billing provider type. This is useful for viewing current billing settings. ```APIDOC ## GET /v1/customers/{customer_id}/billing-config/{billing_provider_type} ### Description Retrieves the billing configuration for a specific customer and billing provider type. ### Method GET ### Endpoint /v1/customers/{customer_id}/billing-config/{billing_provider_type} ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier for the customer. - **billing_provider_type** (string) - Required - The type of the billing provider. #### Query Parameters - **query** (metronome.V1CustomerBillingConfigGetParams) - Required - The query parameters for retrieving the billing configuration. ### Response #### Success Response (200) - **response** (metronome.V1CustomerBillingConfigGetResponse) - The retrieved billing configuration details. ``` -------------------------------- ### Create a Credit Grant Source: https://github.com/metronome-industries/metronome-go/blob/main/_autodocs/README.md Issue a credit grant to a customer. Specify the customer ID, amount, and a name for the grant. ```go resp, _ := client.V1.CreditGrants.New(ctx, metronome.V1CreditGrantNewParams{ CustomerID: "cust_123", Amount: "10000", Name: "Promotional Credit", }, ) ```