### Using OneClickService List and InstallKubernetes Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/functions-1click.md Shows how to list 1-Click apps and install Kubernetes add-ons. The example lists apps of type 'kubernetes', prints their slugs, then installs the 'certbot' add-on to a cluster. ```go apps, _, err := client.OneClick.List(ctx, "kubernetes") if err != nil { panic(err) } for _, oc := range apps { println(oc.Slug) } msg, _, err := client.OneClick.InstallKubernetes(ctx, &godo.InstallKubernetesAppsRequest{Slugs: []string{"certbot"}, ClusterUUID: clusterID}) ``` -------------------------------- ### Get image by slug example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/images.md Shows how to retrieve an image using its slug, such as 'ubuntu-24-04-x64', and access its properties. Panics on error. ```go image, _, err := client.Images.GetBySlug(ctx, "ubuntu-24-04-x64") if err != nil { panic(err) } println(image.Distribution, image.Status, image.Public) ``` -------------------------------- ### Pagination Example with ListRepositoriesV2 Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/registry.md Shows how to page through all repositories using `ListRepositoriesV2` with token-based pagination. It loops until the last page, appending repositories to a list, and uses `resp.Links.NextPageToken()` to get the next page token. The `opt` (TokenListOptions) is updated with the token and passed again. ```go repo, resp, err := client.Registry.ListRepositoriesV2(ctx, registryName, &godo.TokenListOptions{}) for { append(list, repo...) if resp.Links == nil || resp.Links.IsLastPage() { break } token, err := resp.Links.NextPageToken() if err != nil { return ..., err } opt.Token = token repo, resp, err = client.Registry.ListRepositoriesV2(ctx, registryName, opt) } ``` -------------------------------- ### Create firewall and add droplets example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/firewalls-security.md Shows how to create a firewall with an inbound rule and then add droplets to it. The example panics on error. ```go fw, _, err := client.Firewalls.Create(ctx, &godo.FirewallRequest{ Name: "web", InboundRules: []godo.InboundRule{ godo.InboundRule{Protocol: "tcp", PortRange: "443", Sources: &godo.Sources{Addresses: []string{"0.0.0.0/0"}}}, }, }) if err != nil { panic(err) } _, err = client.Firewalls.AddDroplets(ctx, fw.ID, 123, 456) ``` -------------------------------- ### Example usage of client.Account.Get Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/account-billing.md Example call to client.Account.Get that panics on error and prints the account email and droplet limit. ```go account, resp, err := client.Account.Get(ctx) if err != nil { panic(err) } println(account.Email, account.DropletLimit) ``` -------------------------------- ### Do usage example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/client.md Example call to Do, decoding the response into an accountRoot struct. ```go root := new(accountRoot) resp, err := client.Do(ctx, req, root) ``` -------------------------------- ### Get Balance Example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/account-billing.md Calls the Balance.Get method to retrieve the balance and prints account balance and month-to-date usage. ```go bal, _, err := client.Balance.Get(ctx) if err != nil { panic(err) } println(bal.AccountBalance, bal.MonthToDateUsage) ``` -------------------------------- ### List actions example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/actions.md Example of listing actions with pagination options. Prints action ID, type, and status for each returned action. ```go actions, resp, err := client.Actions.List(ctx, &godo.ListOptions{Page: 1, PerPage: 50}) if err != nil { panic(err) } for _, a := range actions { println(a.ID, a.Type, a.Status) } ``` -------------------------------- ### Get action example with ArgError handling Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/actions.md Example of fetching a single action by ID. Handles *godo.ArgError for invalid IDs (id < 1) and panics on API errors. ```go action, _, err := client.Actions.Get(ctx, actionID) if err != nil { if argerr, ok := err.(*godo.ArgError); ok { println(argerr.Error()) // "id is invalid because cannot be less than 1" } else { panic(err) // API error } } ``` -------------------------------- ### GetRate usage example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/client.md Example of retrieving the current rate and printing the remaining requests. ```go rate := client.GetRate() println(rate.Remaining, "requests remaining") ``` -------------------------------- ### OnRequestCompleted usage example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/client.md Example of registering a callback that prints the request method and response status code. ```go client.OnRequestCompleted(func(req *http.Request, resp *http.Response) { println(req.Method, resp.StatusCode) }) ``` -------------------------------- ### ActionRequest usage example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/actions.md Example of constructing an ActionRequest for a resize action. Note: doAction is service-internal; use Resize() instead. ```go request := &godo.ActionRequest{ "type": "resize", "size": "s-2vcpu-2gb", "disk": true, } action, _, err := client.DropletActions.doAction(ctx, dropletID, request) // doAction is service-internal; use Resize() instead ``` -------------------------------- ### Chat completion and streaming examples Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/inference.md Shows how to create a chat completion and how to stream a response. The streaming example forces stream.Stream to true and iterates over the stream, printing the delta content. API-level errors are returned as *godo.ErrorResponse. ```go completion, _, err := client.Chat.Completions.New(ctx, &godo.ChatCompletionNewParams{ Model: "llama3.3-70b-instruct", Messages: []godo.ChatCompletionMessage{godo.UserMessage("Write me a haiku")}, }) if err != nil { panic(err) } // API-level errors are *godo.ErrorResponse ``` ```go stream, _, err := client.Chat.Completions.NewStreaming(ctx, &godo.ChatCompletionNewParams{Model: "llama3.3-70b-instruct", Messages: []godo.ChatCompletionMessage{godo.UserMessage("hi")}}) if err != nil { panic(err) } defer stream.Close() for stream.Next() { print(stream.Current().Choices[0].Delta.Content) } if err := stream.Err(); err != nil { panic(err) } ``` -------------------------------- ### GetAppInstances Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/apps.md Gets instances for an app. ```APIDOC ## GetAppInstances(appID string, opts *GetAppInstancesOpts) ([]*AppInstance, *Response, error) ### Description Retrieves instances (e.g., VMs) for an app, with optional filtering. ### Method GET ### Endpoint /v2/apps/{appID}/instances ### Parameters #### Path Parameters - **appID** (string) - Required - The ID of the app. #### Query Parameters - **component** (string) - Optional - Filter by component name. ### Request Example ```http GET /v2/apps/app-id/instances?component=web HTTP/1.1 Host: api.digitalocean.com Authorization: Bearer {{token}} ``` ### Response #### Success Response (200) - **instances** ([]*AppInstance) - List of instances. #### Response Example ```json { "instances": [ { "id": "instance-id", "component": "web", "status": "RUNNING" } ] } ``` ``` -------------------------------- ### NewRequest usage example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/client.md Example call to NewRequest for a GET request to the v2/account endpoint with no body. ```go req, err := client.NewRequest(ctx, http.MethodGet, "v2/account", nil) ``` -------------------------------- ### Initialize godo client with options Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/client.md Example of initializing a new godo client using multiple configuration options including BaseURL, UserAgent, RequestHeaders, and StaticRateLimit. ```go client, err := godo.New(httpClient, godo.SetBaseURL("https://api.digitalocean.com/"), godo.SetUserAgent("my-app"), godo.SetRequestHeaders(map[string]string{"X-Env": "prod"}), godo.SetStaticRateLimit(5.0)) ``` -------------------------------- ### List sizes with GPU info example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/regions-sizes.md Lists all sizes and prints the slug, GPU model, and VRAM amount for sizes that have GPU information. ```go sizes, _, err := client.Sizes.List(ctx, nil) if err == nil { for _, size := range sizes { if size.GPUInfo != nil { println(size.Slug, size.GPUInfo.Model, size.GPUInfo.VRAM.Amount) } } } ``` -------------------------------- ### Create project and assign resource example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/projects-tags.md Shows how to create a project and assign a resource to it using the client. The AssignResources call accepts a URN string or a ProjectResource value; here a URN is built with godo.ToURN. ```go project, _, err := client.Projects.Create(ctx, &godo.CreateProjectRequest{ Name: "team-infra", Purpose: "Infrastructure", Environment: "Production", }) if err != nil { panic(err) } _, err = client.Projects.AssignResources(ctx, project.ID, godo.ToURN("Droplet", 1234567)) ``` -------------------------------- ### GET /v2/monitoring/metrics/database/mysql/{metric} Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/monitoring-uptime.md Retrieves DBaaS MySQL metrics using a metric name and query parameters database_id, start, and end. ```APIDOC ## GET /v2/monitoring/metrics/database/mysql/{metric} ### Description Retrieves DBaaS MySQL metrics using a metric name and query parameters database_id, start, and end. ### Method GET ### Endpoint /v2/monitoring/metrics/database/mysql/{metric} ### Parameters #### Path Parameters - **metric** (string) - Required - The metric name. Use constants like DbaasFifteenMinuteLoadAverage, DbaasMemoryUtilizationPercent, etc. #### Query Parameters - **database_id** (string) - Required - The database ID. - **start** (string) - Required - Start time in RFC3339 format. - **end** (string) - Required - End time in RFC3339 format. ### Response #### Success Response (200) - **metrics** (MetricsResponse) - Contains status and data with result streams. ### Response Example { "status": "success", "data": { "resultType": "matrix", "result": [] } } ``` -------------------------------- ### GET /v2/monitoring/metrics/load_balancer/{metric} Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/monitoring-uptime.md Retrieves metrics for a specific Load Balancer using a metric name and query parameters load_balancer_id, start, and end. ```APIDOC ## GET /v2/monitoring/metrics/load_balancer/{metric} ### Description Retrieves metrics for a specific Load Balancer using a metric name and query parameters load_balancer_id, start, and end. ### Method GET ### Endpoint /v2/monitoring/metrics/load_balancer/{metric} ### Parameters #### Path Parameters - **metric** (string) - Required - The metric name. Use constants like LoadBalancerCPUUtilizationPercent. #### Query Parameters - **load_balancer_id** (string) - Required - The Load Balancer ID. - **start** (string) - Required - Start time in RFC3339 format. - **end** (string) - Required - End time in RFC3339 format. ### Response #### Success Response (200) - **metrics** (MetricsResponse) - Contains status and data with result streams. ### Response Example { "status": "success", "data": { "resultType": "matrix", "result": [] } } ``` -------------------------------- ### GET /v2/monitoring/metrics/droplet/{metric} Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/monitoring-uptime.md Retrieves metrics for a specific Droplet using a metric name and query parameters host_id, start, and end in RFC3339 format. ```APIDOC ## GET /v2/monitoring/metrics/droplet/{metric} ### Description Retrieves metrics for a specific Droplet using a metric name and query parameters host_id, start, and end in RFC3339 format. ### Method GET ### Endpoint /v2/monitoring/metrics/droplet/{metric} ### Parameters #### Path Parameters - **metric** (string) - Required - The metric name. Use constants like DropletCPUUtilizationPercent, DropletMemoryUtilizationPercent, etc. #### Query Parameters - **host_id** (string) - Required - The Droplet ID. - **start** (string) - Required - Start time in RFC3339 format. - **end** (string) - Required - End time in RFC3339 format. ### Response #### Success Response (200) - **metrics** (MetricsResponse) - Contains status and data with result streams. ### Response Example { "status": "success", "data": { "resultType": "matrix", "result": [] } } ### Error Handling If the request fails, an error is returned (see example). ``` -------------------------------- ### Create and pause microdroplet example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/nfs-microdroplets.md Shows how to create a microdroplet with a name, image, size, and region, then pause it, panicking on errors. ```go md, _, err := client.MicroDroplets.Create(ctx, &godo.MicroDropletCreateRequest{ Name: "devbox", Image: "ubuntu-24-04", Size: "micro-1", Region: "nyc3", }) if err != nil { panic(err) } md2, _, err := client.MicroDroplets.Pause(ctx, md.ID) ``` -------------------------------- ### Get Droplet CPU Metrics Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/monitoring-uptime.md Fetches CPU utilization metrics for a specific droplet using the Monitoring.GetDropletCPU method. Requires a DropletMetricsRequest with HostID, Start, and End times. The response contains a MetricsData object with Result streams that can be iterated. ```go metrics, _, err := client.Monitoring.GetDropletCPU(ctx, &godo.DropletMetricsRequest{ HostID: dropletID, Start: start, End: end, }) if err != nil { panic(err) } for _, stream := range metrics.Data.Result { println(stream) } ``` -------------------------------- ### Usage example: create client and send chat completion Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/inference.md Shows how to instantiate an AgentInferenceClient using environment variables and a custom user agent, then call Chat.Completions.New with a user message. Panics on client creation error. ```go client, err := godo.NewAgentInferenceClient( os.Getenv("DIGITALOCEAN_AGENT_URL"), os.Getenv("DIGITALOCEAN_AGENT_ACCESS_KEY"), godo.SetAgentUserAgent("my-app"), ) if err != nil { panic(err) } completion, _, err := client.Chat.Completions.New(ctx, &godo.ChatCompletionNewParams{ Model: os.Getenv("DIGITALOCEAN_AGENT_MODEL"), Messages: []godo.ChatCompletionMessage{godo.UserMessage("hi")}, }) ``` -------------------------------- ### ActionsServiceOp Get method signature Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/actions.md Signature for the Get method implementation. Calls GET v2/actions/{id}. Throws *ArgError if id < 1. ```go func (s *ActionsServiceOp) Get(ctx context.Context, id int) (*Action, *Response, error) ``` -------------------------------- ### LBFirewall helper formatting example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/load-balancers.md Shows how to construct an LBFirewall using the IPSourceFirewall and CIDRSourceFirewall helpers. The Allow field uses a CIDR source rule, and the Deny field uses an IP source rule. Use this pattern when setting the Firewall field on a load balancer. ```go lb.Firewall = &godo.LBFirewall{ Allow: []string{godo.CIDRSourceFirewall("192.0.2.0/24")}, Deny: []string{godo.IPSourceFirewall("203.0.113.72")}, } ``` -------------------------------- ### Create client with environment-based credentials Source: https://github.com/digitalocean/godo/blob/main/README.md Shows two ways to create a client using either a full-access PAT or a Gradient Model Access Key. The comment indicates that either credential works with godo.NewFromToken. ```go // Either credential works with godo.NewFromToken: client := godo.NewFromToken(os.Getenv("DIGITALOCEAN_TOKEN")) // full-access PAT client := godo.NewFromToken(os.Getenv("MODEL_ACCESS_KEY")) // Gradient model access key ``` -------------------------------- ### Attach and reassign NFS share example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/nfs-microdroplets.md Shows how to attach an NFS share to a VPC and then reassign it to a new VPC, handling errors with panic. ```go action, _, err := client.NfsActions.Attach(ctx, share.ID, vpcID, "nyc3") if err == nil { _, _, err = client.NfsActions.Reassign(ctx, share.ID, oldVPC, newVPC) } ``` -------------------------------- ### DoStream usage example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/client.md Example call to DoStream. The caller must close resp.Body when done. ```go resp, err := client.DoStream(ctx, req) // caller must close resp.Body when done ``` -------------------------------- ### SSEReader usage example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/helpers.md Example of reading events from an SSEReader until io.EOF, printing each event's data. ```go reader := godo.NewSSEReader(resp.Body) defer readerNext: for { evt, err := reader.Next() if err == io.EOF { break } println(string(evt.Data)) } ``` -------------------------------- ### Initialize godo client with RetryConfig Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/client.md Example of initializing a godo client with custom retry configuration using WithRetryAndBackoffs. ```go client, err := godo.New(oauth_client, godo.WithRetryAndBackoffs(godo.RetryConfig{ RetryMax: 3, RetryWaitMin: godo.PtrTo(3.0), RetryWaitMax: godo.PtrTo(6.0), })) ``` -------------------------------- ### Create namespace and access key example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/functions-1click.md Shows how to create a namespace and then an access key within it. The access key's Secret field is printed as the bearer secret for the namespace API host. Panics on error. ```go ns, _, err := client.Functions.CreateNamespace(ctx, &godo.FunctionsNamespaceCreateRequest{Label: "prod", Region: "nyc3"}) if err != nil { panic(err) } key, _, err := client.Functions.CreateAccessKey(ctx, ns.Namespace, &godo.FunctionsAccessKeyCreateRequest{Name: "ci"}) println(key.Secret) // bearer secret for the namespace API host ``` -------------------------------- ### VectorDBsService Interface Definition Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/databases.md Defines the VectorDBsService interface with methods for listing, getting, creating, updating, deleting, resizing, updating tags, getting credentials, listing backups, restoring backups, and getting restore status for vector databases. ```go type VectorDBsService interface { List(context.Context, *ListOptions) ([]VectorDB, *Response, error) Get(context.Context, string) (*VectorDB, *Response, error) Create(context.Context, *VectorDBCreateRequest) (*VectorDB, *Response, error) Update(context.Context, string, *VectorDBUpdateRequest) (*VectorDB, *Response, error) Delete(context.Context, string) (*Response, error) Resize(context.Context, string, *VectorDBResizeRequest) (*VectorDB, *Response, error) UpdateTags(context.Context, string, *VectorDBUpdateTagsRequest) (*VectorDB, *Response, error) GetCredentials(context.Context, string) (*VectorDBAdminCredentials, *Response, error) ListBackups(context.Context, string) ([]VectorDBBackup, *Response, error) RestoreBackup(context.Context, string, string, *VectorDBRestoreBackupRequest) (*VectorDBRestoreBackupResponse, *Response, error) GetRestoreStatus(context.Context, string, string) (*VectorDBRestoreStatus, *Response, error) } ``` -------------------------------- ### Create snapshot and list volume snapshots Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/storage-snapshots.md Creates a snapshot with a given name and then lists volume snapshots. Panics on error, with a note about capacity limit exceeded. ```go snap, _, err := client.Storage.CreateSnapshot(ctx, &godo.SnapshotCreateRequest{VolumeID: vol.ID, Name: "pre-upgrade"}) if err != nil { panic(err) } // "capacity limit exceeded" → match godo.ErrVolumeCapacityLimitExceeded snaps, _, err := client.Snapshots.ListVolume(ctx, nil) ``` -------------------------------- ### Create a certificate Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/cdns-certificates.md Creates a certificate with the given name, DNS names, and type. The example uses type 'lets_encrypt'. Panics on error. ```go cert, _, err := client.Certificates.Create(ctx, &godo.CertificateRequest{ Name: "api-cert", DNSNames: []string{"api.example.com"}, Type: "lets_encrypt", }) if err != nil { panic(err) } ``` -------------------------------- ### Create client with custom options Source: https://github.com/digitalocean/godo/blob/main/_autodocs/configuration.md Shows how to instantiate a godo client with a custom base URL, user agent, request headers, static rate limit, and retry configuration. The retryable client is enabled because RetryMax is greater than zero. The example panics on error. ```go client, err := godo.New(httpClient, godo.SetBaseURL("https://api.digitalocean.com/"), godo.SetUserAgent("my-app/1.0"), godo.SetRequestHeaders(map[string]string{"X-Request-Tag": "prod"}), godo.SetStaticRateLimit(20.0), godo.WithRetryAndBackoffs(godo.RetryConfig{RetryMax: 5, RetryWaitMin: godo.PtrTo(0.5), RetryWaitMax: godo.PtrTo(10.0)}), ) if err != nil { panic(err) } ``` -------------------------------- ### Get method signature for AccountServiceOp Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/account-billing.md Signature for the Get method on the AccountServiceOp type. It calls the v2/account endpoint and returns the authenticated account. ```go func (s *AccountServiceOp) Get(ctx context.Context) (*Account, *Response, error) ``` -------------------------------- ### Invoice retrieval example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/account-billing.md Shows how to fetch an invoice with pagination options and iterate over its items, then retrieve the PDF. Errors are handled with panic; the PDF is written to disk when no error occurs. ```go invoice, _, err := client.Invoices.Get(ctx, uuid, &godo.ListOptions{PerPage: 100}) if err != nil { panic(err) } for _, item := range invoice.InvoiceItems { println(item.Description, item.Amount) } pdf, _, err := client.Invoices.GetPDF(ctx, uuid) if err == nil { // write pdf to disk } ``` -------------------------------- ### Create NFS share and snapshot Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/nfs-microdroplets.md Shows how to create an NFS share and then take a snapshot of it. The share is created with a name, size in GiB, and region, and the snapshot is taken with a name and the share's ID. ```go share, _, err := client.Nfs.Create(ctx, &godo.NfsCreateRequest{Name: "models", SizeGib: 100, Region: "nyc3"}) if err != nil { panic(err) } snap, _, err := client.NfsActions.Snapshot(ctx, share.ID, "before-upgrade", "nyc3") ``` -------------------------------- ### Create Project Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/projects-tags.md Creates a new project with the specified configuration. ```APIDOC ## POST /v2/projects ### Description Creates a new project with the provided name, purpose, and environment. ### Method POST ### Endpoint `/v2/projects` ### Parameters #### Request Body - **name** (string) - Required - The project's name. - **description** (string) - Optional - A description for the project. - **purpose** (string) - Optional - The project's purpose. - **environment** (string) - Optional - The environment (e.g., Production, Staging). ### Request Example ```go project, _, err := client.Projects.Create(ctx, &godo.CreateProjectRequest{ Name: "team-infra", Purpose: "Infrastructure", Environment: "Production", }) ``` ### Response #### Success Response (201) - **project** (*Project) - The created project. - **resp** (*Response) - HTTP response metadata. #### Response Example ```json { "project": { "id": "string", "owner_uuid": "string", "owner_id": 0, "name": "team-infra", "description": "", "purpose": "Infrastructure", "environment": "Production", "is_default": false, "created_at": "string", "updated_at": "string" } } ``` ``` -------------------------------- ### Install latest Godo version Source: https://github.com/digitalocean/godo/blob/main/README.md Use this command to install the latest version of the Godo library, suitable for non-Go modules usage or when you want the latest release. ```sh go get github.com/digitalocean/godo ``` -------------------------------- ### Install Godo with specific version Source: https://github.com/digitalocean/godo/blob/main/README.md Use this command to install a specific version of the Godo library. Replace X.Y.Z with the desired version number from the releases page. ```sh go get github.com/digitalocean/godo@vX.Y.Z ``` -------------------------------- ### Using ToURN with println Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/helpers.md Example of generating a URN for a droplet. ```go println(godo.ToURN("Droplet", 123)) // do:droplet:123 ``` -------------------------------- ### List regions example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/regions-sizes.md Lists all available regions and prints the slug of each available region. ```go regions, _, err := client.Regions.List(ctx, nil) if err == nil { for _, reg := range regions { if reg.Available { println(reg.Slug) } } } ``` -------------------------------- ### Get(ctx context.Context, id int) (*Action, *Response, error) Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/actions.md Gets a specific action by its ID. Returns the Action object, the HTTP response, and any error. Throws *ArgError if the ID is less than 1. ```APIDOC ## GET v2/actions/{id} ### Description Gets a specific action by ID. Returns the Action object, the HTTP response, and any error. Throws `*ArgError` if `id` is less than 1. ### Method GET ### Endpoint v2/actions/{id} ### Parameters #### Path Parameters - **id** (int) - Required - The ID of the action to retrieve. Must be >= 1. ### Request Example ```go action, _, err := client.Actions.Get(ctx, actionID) if err != nil { if argerr, ok := err.(*godo.ArgError); ok { println(argerr.Error()) // "id is invalid because cannot be less than 1" } else { panic(err) // API error } } ``` ### Response #### Success Response (200) - **action** (*Action) - The Action object - **resp** (*Response) - HTTP response object #### Response Example (Not explicitly provided in source) ### Error Handling - **ArgError**: If `id < 1`, returns `NewArgError("id", "cannot be less than 1")` in the error position with `(nil, nil)`. ``` -------------------------------- ### GetEventLogs Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/apps.md Gets logs for an event. ```APIDOC ## GetEventLogs(appID, eventID string, opts *GetEventLogsOptions) (*AppLogs, *Response, error) ### Description Retrieves logs for a specific event. ### Method GET ### Endpoint /v2/apps/{appID}/events/{eventID}/logs ### Parameters #### Path Parameters - **appID** (string) - Required - The ID of the app. - **eventID** (string) - Required - The ID of the event. #### Query Parameters - **log_type** (AppLogType) - Optional - Type of log. - **follow** (bool) - Optional - Stream logs. - **tail_lines** (int) - Optional - Number of lines to tail. ### Request Example ```http GET /v2/apps/app-id/events/event-id/logs?log_type=DEPLOY&tail_lines=50 HTTP/1.1 Host: api.digitalocean.com Authorization: Bearer {{token}} ``` ### Response #### Success Response (200) - **app_logs** (AppLogs) - The logs object. #### Response Example ```json { "app_logs": { "live_url": "wss://logs.digitalocean.com/...", "historic_url": "https://logs.digitalocean.com/..." } } ``` ``` -------------------------------- ### OneClickService.InstallKubernetes Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/functions-1click.md Installs Kubernetes add-ons for a specified cluster. Sends a POST request to v2/1-clicks/kubernetes with a request body containing addon slugs and cluster UUID, and returns an InstallKubernetesAppsResponse. ```APIDOC ## POST v2/1-clicks/kubernetes ### Description Installs Kubernetes add-ons for a specified cluster. ### Method POST ### Endpoint v2/1-clicks/kubernetes ### Parameters #### Request Body - **addon_slugs** ([]string) - Required - List of addon slugs to install. - **cluster_uuid** (string) - Required - UUID of the cluster to install add-ons on. ### Request Example ```json { "addon_slugs": ["certbot"], "cluster_uuid": "your-cluster-id" } ``` ### Response #### Success Response (200) - **message** (string) - Response message. #### Response Example ```json { "message": "Add-ons installed successfully" } ``` ``` -------------------------------- ### GetEvent Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/apps.md Gets a specific event. ```APIDOC ## GetEvent(appID, eventID string) (*Event, *Response, error) ### Description Retrieves a single event by ID. ### Method GET ### Endpoint /v2/apps/{appID}/events/{eventID} ### Parameters #### Path Parameters - **appID** (string) - Required - The ID of the app. - **eventID** (string) - Required - The ID of the event. ### Request Example ```http GET /v2/apps/app-id/events/event-id HTTP/1.1 Host: api.digitalocean.com Authorization: Bearer {{token}} ``` ### Response #### Success Response (200) - **event** (Event) - The event object. #### Response Example ```json { "event": { "id": "event-id", "type": "deployment", "created_at": "2024-01-01T00:00:00Z" } } ``` ``` -------------------------------- ### Create uptime check and get state Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/monitoring-uptime.md Shows how to create an uptime check and immediately retrieve its state. The check targets https://example.com with regions 'us' and 'eu' and is enabled. ```go check, _, err := client.UptimeChecks.Create(ctx, &godo.CreateUptimeCheckRequest{ Name: "homepage", Target: "https://example.com", Type: "https", Regions: []string{"us", "eu"}, Enabled: true, }) if err != nil { panic(err) } state, _, err := client.UptimeChecks.GetState(ctx, check.ID) ``` -------------------------------- ### PrepaymentService interface definition Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/account-billing.md Defines the PrepaymentService interface with GetConfig and GetStatus methods. GetConfig calls GET v2/customers/my/prepayment_config and returns a PrepaymentConfigResponse containing both Config and Status. GetStatus calls GET v2/customers/my/prepayment_status and returns a PrepaymentStatusResponse with Status. ```go type PrepaymentService interface { GetConfig(context.Context) (*PrepaymentConfigResponse, *Response, error) GetStatus(context.Context) (*PrepaymentStatusResponse, *Response, error) } ``` -------------------------------- ### Create tag and tag resources example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/projects-tags.md Shows how to create a tag named "prod" and then tag a droplet resource with ID "1234567" using the client. Panics on error; requires a valid godo client and context. ```go tag, _, err := client.Tags.Create(ctx, &godo.TagCreateRequest{Name: "prod"}) if err != nil { panic(err) } _, err = client.Tags.TagResources(ctx, tag.Name, &godo.TagResourcesRequest{ Resources: []godo.Resource{godo.Resource{ID: "1234567", Type: godo.DropletResourceType}}, }) ``` -------------------------------- ### Create VectorDB and Get Credentials Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/databases.md Creates a vector database with a request struct (fields omitted for brevity) and then retrieves its admin credentials, printing the HTTP endpoint. Panics on error. ```go vdb, _, err := client.VectorDBs.Create(ctx, &godo.VectorDBCreateRequest{...}) if err != nil { panic(err) } creds, _, err := client.VectorDBs.GetCredentials(ctx, vdb.ID) println(creds.HTTP) ``` -------------------------------- ### Meta struct definition and usage example Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/request-response.md Defines the Meta type with JSON tags for page, pages, and total. The example shows how to access the total number of records from a response's Meta field after listing droplets. ```go // Meta describes generic information about a response. type Meta struct { Page int `json:"page,,omitempty"` Pages int `json:"pages,,omitempty"` Total int `json:"total"` } ``` ```go droplets, resp, _ := client.Droplets.List(ctx, opt) println(resp.Meta.Total) ``` -------------------------------- ### GetJobInvocationLogs Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/apps.md Gets logs for a job invocation. ```APIDOC ## GetJobInvocationLogs(appID, jobInvocationId string, opts *GetJobInvocationLogsOptions) (*AppLogs, *Response, error) ### Description Retrieves logs for a specific job invocation. ### Method GET ### Endpoint /v2/apps/{appID}/jobs/{jobInvocationId}/logs ### Parameters #### Path Parameters - **appID** (string) - Required - The ID of the app. - **jobInvocationId** (string) - Required - The ID of the job invocation. #### Query Parameters - **log_type** (AppLogType) - Optional - Type of log (e.g., RUN, BUILD). - **follow** (bool) - Optional - Stream logs. - **tail_lines** (int) - Optional - Number of lines to tail. ### Request Example ```http GET /v2/apps/app-id/jobs/invocation-id/logs?log_type=RUN&tail_lines=50 HTTP/1.1 Host: api.digitalocean.com Authorization: Bearer {{token}} ``` ### Response #### Success Response (200) - **app_logs** (AppLogs) - The logs object. #### Response Example ```json { "app_logs": { "live_url": "wss://logs.digitalocean.com/...", "historic_url": "https://logs.digitalocean.com/..." } } ``` ``` -------------------------------- ### GetJobInvocation Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/apps.md Gets a specific job invocation. ```APIDOC ## GetJobInvocation(appID string, jobInvocationId string, opts *GetJobInvocationOptions) (*JobInvocation, *Response, error) ### Description Retrieves a single job invocation by its ID. ### Method GET ### Endpoint /v2/apps/{appID}/jobs/{jobInvocationId} ### Parameters #### Path Parameters - **appID** (string) - Required - The ID of the app. - **jobInvocationId** (string) - Required - The ID of the job invocation. ### Request Example ```http GET /v2/apps/app-id/jobs/invocation-id HTTP/1.1 Host: api.digitalocean.com Authorization: Bearer {{token}} ``` ### Response #### Success Response (200) - **job_invocation** (JobInvocation) - The job invocation object. #### Response Example ```json { "job_invocation": { "id": "invocation-id", "job_id": "job-id", "status": "COMPLETED" } } ``` ``` -------------------------------- ### Create Agent and List Available Models with client.GradientAI Source: https://github.com/digitalocean/godo/blob/main/_autodocs/api-reference/inference.md Creates an agent and lists available models using the GradientAI service. The CreateAgent call requires a name and model identifier; ListAvailableModels with PublicOnly filters to public models. Both return a response and error, with errors handled via panic in this example. ```go agent, _, err := client.GradientAI.CreateAgent(ctx, &godo.AgentCreateRequest{Name: "support-bot", Model: "llama3.3-70b-instruct"}) if err != nil { panic(err) } models, _, err := client.GradientAI.ListAvailableModels(ctx, &godo.ListOptions{PublicOnly: true}) ```