### Example: Get Deploy Details Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/deploy.md Example of how to retrieve and print details of a specific Netlify deployment. Includes error handling. ```go deploy, err := client.GetDeploy(ctx, "deploy-id-123") if err != nil { return err } fmt.Printf("Deploy State: %s\n", deploy.State) fmt.Printf("URL: %s\n", deploy.DeployURL) fmt.Printf("Draft: %v\n", deploy.Draft) ``` -------------------------------- ### Go Client Installation Source: https://github.com/netlify/open-api/blob/master/_autodocs/README.md Instructions for installing the Netlify Open API Go client library. ```APIDOC ## Go Client Installation ### Description Install the Netlify Open API Go client library using the `go get` command. ### Command ```bash go get github.com/netlify/open-api/v2/go/... ``` ``` -------------------------------- ### Install Netlify Go Client Source: https://github.com/netlify/open-api/blob/master/README.md Use this command to get the Netlify Go client library. It includes high-level and low-level operations, as well as models. ```bash $ go get github.com/netlify/open-api/... ``` -------------------------------- ### Deploy Observer Implementation Example Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/porcelain-client.md Provides an example implementation of the DeployObserver interface, specifically handling successful steps during a deploy. This demonstrates how to integrate the observer pattern for deploy progress tracking. ```go type DeployProgress struct{} func (dp *DeployProgress) OnSuccessfulStep(bundle *FileBundle) error { fmt.Printf("Uploaded: %s (%d bytes)\n", bundle.Name, *bundle.Size) return nil } // ... implement other methods ... opts := &DeployOptions{ Observer: &DeployProgress{}, } ``` -------------------------------- ### Install Go Client Source: https://github.com/netlify/open-api/blob/master/_autodocs/README.md Installs the Netlify Open API Go client library. This command should be run in your Go environment. ```bash go get github.com/netlify/open-api/v2/go/... ``` -------------------------------- ### Start Build Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Manually starts a specific build. ```APIDOC ## POST /builds/{build_id}/start ### Description Manually starts a specific build. ### Method POST ### Endpoint /builds/{build_id}/start ### Response #### Success Response (200) - Returns updated `build` object ``` -------------------------------- ### DeploySite Basic Example Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/deploy.md Creates a new deploy for a site by uploading files from a specified directory. Ensure the SiteID and Dir are correctly set. ```go options := &porcelain.DeployOptions{ SiteID: "site-id-123", Dir: "/path/to/build", } deploy, err := client.DeploySite(ctx, options) if err != nil { return err } fmt.Printf("Deployed! URL: %s\n", deploy.DeployURL) ``` -------------------------------- ### Install Netlify JS Client via npm Source: https://github.com/netlify/open-api/blob/master/README.md Install the Netlify JS client library using npm or yarn. This client provides similar 'porcelain' methods to the Go client and can also consume the OpenAPI spec directly. ```bash $ npm install @netlify/open-api ``` ```bash $ yarn add @netlify/open-api ``` -------------------------------- ### Create a Deploy Key Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/deploy-keys.md Generate a deploy key for one-time setup. Store the private key securely for subsequent deployments. ```go // One-time setup key, _ := client.CreateDeployKey(ctx) storePrivateKeySecurely(key.PrivateKey) // Later deployments can use the same key // via environment variables or configuration ``` -------------------------------- ### DeploySite With Functions Example Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/deploy.md Creates a new deploy for a site, including uploading Netlify Functions from a specified directory. Set the FunctionsDir option to the path of your functions. ```go options := &porcelain.DeployOptions{ SiteID: "site-id-123", Dir: "/path/to/build", FunctionsDir: "/path/to/functions", Branch: "main", } deploy, err := client.DeploySite(ctx, options) if err != nil { return err } fmt.Printf("Deployed with functions\n") ``` -------------------------------- ### Context Usage Example Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/porcelain-client.md Demonstrates how to create and use a context with authentication information for API requests. This is required for all porcelain methods. ```go ctx := context.Background() ctx = porcelain.context.WithAuthInfo(ctx, runtime.ClientAuthInfoWriter) sites, err := client.ListSites(ctx, &operations.ListSitesParams{}) ``` -------------------------------- ### DeploySite With Observer Example Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/deploy.md Creates a new deploy for a site while observing the deployment progress. Implement the DeployObserver interface to receive callbacks for different stages of the deployment process. ```go type deployProgress struct{} func (p *deployProgress) OnSetupWalk() error { fmt.Println("Scanning files...") return nil } func (p *deployProgress) OnSuccessfulStep(bundle *porcelain.FileBundle) error { fmt.Printf("Uploaded: %s\n", bundle.Name) return nil } // ... implement other observer methods ... options := &porcelain.DeployOptions{ SiteID: "site-id-123", Dir: "/path/to/build", Observer: &deployProgress{}, } deploy, err := client.DeploySite(ctx, options) ``` -------------------------------- ### Initialize Default HTTP Client Source: https://github.com/netlify/open-api/blob/master/_autodocs/configuration.md Use this to create a client with default API endpoint, base path, and scheme. No special setup is required. ```go import "github.com/netlify/open-api/v2/go/porcelain" client := porcelain.NewHTTPClient(nil) ``` -------------------------------- ### Basic Go Usage - List Sites Source: https://github.com/netlify/open-api/blob/master/_autodocs/README.md Example demonstrating how to use the Netlify Open API Go client to list sites associated with your account. ```APIDOC ## Basic Usage - List Sites ### Description This example shows how to initialize the Netlify Open API Go client and use it to retrieve a list of your sites. ### Method `client.ListSites` ### Parameters - `ctx` (context.Context) - The context for the request. - `params` (*operations.ListSitesParams) - Optional parameters for listing sites. ### Request Example ```go package main import ( "context" "fmt" "github.com/netlify/open-api/v2/go/porcelain" "github.com/netlify/open-api/v2/go/operations" ) func main() { // Create client (uses default API endpoint) client := porcelain.NewHTTPClient(nil) ctx := context.Background() // List your sites sites, err := client.ListSites(ctx, &operations.ListSitesParams{}) if err != nil { fmt.Printf("Error: %v\n", err) return } for _, site := range sites { fmt.Printf("Site: %s (URL: %s)\n", site.Name, site.DeployURL) } } ``` ### Response - `sites` ([]*models.Site) - A slice of Site objects. - `err` (error) - An error if the request failed. ``` -------------------------------- ### CreateSite Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/site.md Create a new site with specified configurations, optionally including DNS setup. ```APIDOC ## CreateSite ### Description Create a new site. ### Method POST ### Endpoint /sites ### Parameters #### Path Parameters None #### Query Parameters - **configureDNS** (bool) - Optional - Automatically configure DNS records for custom domain #### Request Body - **site** (*models.SiteSetup) - Required - Site configuration (name, domain, etc.) - **Name** (string) - Required - Site name - **CustomDomain** (string) - Optional - Custom domain (e.g., example.com) - **BuildImage** (string) - Optional - Build image identifier - **Repo** (*SiteSetupRepo) - Optional - Repository configuration for CI/CD - **Provider** (string) - Required - Repository provider (e.g., "github") - **RepoURL** (string) - Required - URL of the repository - **RepoBranch** (string) - Required - Branch of the repository ### Request Example ```json { "Name": "my-new-website", "CustomDomain": "example.com", "Repo": { "Provider": "github", "RepoURL": "https://github.com/user/repo", "RepoBranch": "main" } } ``` ### Response #### Success Response (200) - **site** (*models.Site) - Created site object with ID and URLs #### Response Example ```json { "ID": "5f1c2d8e9f3b2a1c5d8e9f3b", "Name": "my-new-website", "DeployURL": "https://my-new-website.netlify.app", "CustomDomain": "example.com" } ``` ### Errors - **400 Bad Request**: Invalid site configuration - **409 Conflict**: Site name already exists - **422 Unprocessable Entity**: Domain validation failed - **401 Unauthorized**: Invalid authentication ``` -------------------------------- ### Plumbing Client Method Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/plumbing-client.md Example of using the low-level Plumbing client to list sites. This provides direct control over API calls and response handling. ```go resp, err := client.Operations.ListSites(params, authWriter) if err != nil { return nil, err } sites := resp.Payload ``` -------------------------------- ### Example: Custom Endpoint Configuration Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/plumbing-client.md Demonstrates how to configure a custom API endpoint by modifying the TransportConfig. Creates a new client with the specified host and base path. ```go cfg := plumbing.DefaultTransportConfig() cfg = cfg.WithHost("custom-api.example.com") cfg = cfg.WithBasePath("/api/v2") transport := client.New(cfg.Host, cfg.BasePath, cfg.Schemes) client := plumbing.New(transport, nil) ``` -------------------------------- ### Get Build Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Retrieves details about a specific build. ```APIDOC ## GET /builds/{build_id} ### Description Retrieves details about a specific build. ### Method GET ### Endpoint /builds/{build_id} ### Parameters #### Path Parameters - **build_id** (string) - Required - The unique build identifier ### Response #### Success Response (200) - Returns `build` object with status and details ``` -------------------------------- ### ProgressTracker Implementation of DeployObserver Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/deploy.md An example implementation of the DeployObserver interface that tracks and prints progress information for each stage of a deployment. It measures time, counts uploaded files, and displays percentages. ```go type ProgressTracker struct { startTime time.Time uploaded int64 total int64 } func (p *ProgressTracker) OnSetupWalk() error { p.startTime = time.Now() fmt.Println("Scanning files...") return nil } func (p *ProgressTracker) OnSuccessfulStep(bundle *porcelain.FileBundle) error { fmt.Printf("✓ %s\n", bundle.Name) return nil } func (p *ProgressTracker) OnSuccessfulWalk(df *models.DeployFiles) error { p.total = int64(len(df.Files)) fmt.Printf("Found %d files to deploy\n", p.total) return nil } func (p *ProgressTracker) OnSetupDelta(df *models.DeployFiles) error { fmt.Println("Checking changes...") return nil } func (p *ProgressTracker) OnSuccessfulDelta(df *models.DeployFiles, d *models.Deploy) error { fmt.Printf("Deploy created: %s\n", d.ID) return nil } func (p *ProgressTracker) OnSetupUpload(bundle *porcelain.FileBundle) error { return nil } func (p *ProgressTracker) OnSuccessfulUpload(bundle *porcelain.FileBundle) error { if bundle.Size != nil { p.uploaded += *bundle.Size } pct := float64(p.uploaded) / float64(p.total) * 100 fmt.Printf("[%.1f%%] Uploaded %s\n", pct, bundle.Name) return nil } func (p *ProgressTracker) OnFailedUpload(bundle *porcelain.FileBundle) error { fmt.Printf("✗ Failed to upload %s\n", bundle.Name) return nil } func (p *ProgressTracker) OnFailedWalk() { fmt.Println("Failed to scan files") } func (p *ProgressTracker) OnFailedDelta(df *models.DeployFiles) { fmt.Println("Failed to create deploy") } ``` -------------------------------- ### Porcelain Client Method Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/plumbing-client.md Example of using the high-level Porcelain client to list sites. This method typically includes automatic retries and error handling. ```go sites, err := client.ListSites(ctx, params) ``` -------------------------------- ### Configure Custom API Endpoint Source: https://github.com/netlify/open-api/blob/master/_autodocs/configuration.md Example of configuring transport settings to point to a custom API endpoint and initializing the Netlify client. ```go cfg := porcelain.DefaultTransportConfig() cfg = cfg.WithHost("custom-api.example.com") cfg = cfg.WithBasePath("/api/v2") transport := client.New(cfg.Host, cfg.BasePath, cfg.Schemes) netlifyClient := porcelain.New(transport, nil) ``` -------------------------------- ### Batch Upload Site Assets Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/assets.md Uploads multiple files as site assets in a loop. This example demonstrates handling individual upload errors while continuing the batch process. ```Go files := []string{"image1.jpg", "image2.jpg", "image3.jpg"} for _, filename := range files { file, _ := os.Open(filename) info, _ := file.Stat() asset := &porcelain.SiteAsset{ SiteID: siteID, Name: filename, Size: info.Size(), Body: file, } result, err := client.UploadNewSiteAsset(ctx, asset) if err != nil { fmt.Printf("Error uploading %s: %v\n", filename, err) } else { fmt.Printf("Uploaded: %s\n", result.URL) } file.Close() } ``` -------------------------------- ### Handle API Errors with Specific Codes (Go) Source: https://github.com/netlify/open-api/blob/master/_autodocs/README.md Illustrates how to check for API errors and differentiate them by status code. This example shows handling 404 (Not Found) and 401 (Unauthorized) errors specifically, with a fallback for other API errors. ```go site, err := client.GetSite(ctx, siteID) if err != nil { if apiErr, ok := err.(runtime.ClientError); ok { switch apiErr.Code() { case 404: fmt.Println("Site not found") case 401: fmt.Println("Authentication failed") default: fmt.Printf("API error: %v\n", apiErr) } } return err } ``` -------------------------------- ### Use Environment Variables for Deploy Keys in CI/CD Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/deploy-keys.md Securely manage deploy keys in CI/CD pipelines by using environment variables. This example shows configuration for GitHub Actions. ```yaml # GitHub Actions example env: DEPLOY_KEY: ${{ secrets.NETLIFY_DEPLOY_KEY }} ``` -------------------------------- ### Basic Site Deployment Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/deploy.md Prepare deployment options, create a context with a timeout, and initiate the site deployment. This snippet shows the essential steps for a standard deployment. ```go // 1. Prepare configuration options := &porcelain.DeployOptions{ SiteID: "site-id-123", Dir: "./dist", FunctionsDir: "./functions", Branch: "main", Framework: "next", Observer: &MyProgressTracker{}, } // 2. Create context with timeout ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) deferr cancel() // 3. Deploy deploy, err := client.DeploySite(ctx, options) if err != nil { fmt.Printf("Deploy failed: %v\n", err) return err } // 4. Check results fmt.Printf("Deployed successfully!\n") fmt.Printf("ID: %s\n", deploy.ID) fmt.Printf("URL: %s\n", deploy.DeployURL) fmt.Printf("State: %s\n", deploy.State) ``` -------------------------------- ### NewHTTPClient Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/porcelain-client.md Creates a new Netlify HTTP client with default configuration. It's a convenient way to get started with the Netlify API. ```APIDOC ## NewHTTPClient ### Description Creates a new Netlify HTTP client with default configuration. ### Method Signature ```go func NewHTTPClient(formats strfmt.Registry) *Netlify ``` ### Parameters - **formats** (strfmt.Registry) - Format registry for type marshaling (pass nil for defaults) ### Returns - **`*Netlify`** - A configured client instance ### Example ```go client := porcelain.NewHTTPClient(nil) ``` ``` -------------------------------- ### Get Site TLS Certificate Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/site.md Retrieve the TLS certificate configured for a site. Use this to get current certificate details and expiration dates. ```go func (n *Netlify) GetSiteTLSCertificate(ctx context.Context, siteID string) (*models.SniCertificate, error) ``` ```go cert, err := client.GetSiteTLSCertificate(ctx, "site-id-123") if err != nil { return err } fmt.Printf("Domain: %s\n", cert.Domain) fmt.Printf("State: %s\n", cert.State) fmt.Printf("Expires: %s\n", cert.ExpiresAt) ``` -------------------------------- ### List Sites and Deploy to First Site (Go) Source: https://github.com/netlify/open-api/blob/master/_autodocs/README.md This Go snippet shows how to list existing sites and then deploy a directory to the first site found. It requires the 'porcelain' and 'plumbing/operations' packages from the Netlify OpenAPI client. ```go package main import ( "context" "fmt" "github.com/netlify/open-api/v2/go/porcelain" "github.com/netlify/open-api/v2/go/plumbing/operations" ) func main() { client := porcelain.NewHTTPClient(nil) ctx := context.Background() // List sites sites, _ := client.ListSites(ctx, &operations.ListSitesParams{}) fmt.Printf("Found %d sites\n", len(sites)) // Deploy to first site if len(sites) > 0 { options := &porcelain.DeployOptions{ SiteID: sites[0].ID, Dir: "./dist", } deploy, _ := client.DeploySite(ctx, options) fmt.Printf("Deployed: %s\n", deploy.DeployURL) } } ``` -------------------------------- ### Deploy a Site (Go) Source: https://github.com/netlify/open-api/blob/master/_autodocs/README.md Initiates a new deployment for a specified site. Ensure you have the site ID and the directory containing your build output. ```go options := &porcelain.DeployOptions{ SiteID: "site-id", Dir: "./dist", } deploy, err := client.DeploySite(ctx, options) ``` -------------------------------- ### Get Build Log Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Retrieves the log output for a specific build. ```APIDOC ## GET /builds/{build_id}/log ### Description Retrieves the log output for a specific build. ### Method GET ### Endpoint /builds/{build_id}/log ### Parameters #### Path Parameters - **build_id** (string) - Required - The unique build identifier ### Response #### Success Response (200) - Returns array of `buildLogMsg` objects with log lines ``` -------------------------------- ### Create a Site Model Instance Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/plumbing-client.md Demonstrates how to create an instance of the Site model from the Netlify API client library. Ensure the models package is imported. ```go import "github.com/netlify/open-api/v2/go/models" site := &models.Site{ Name: "my-site", ID: "site-id-123", } ``` -------------------------------- ### Get Site Asset Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Retrieves details for a specific site asset. ```APIDOC ## GET /sites/{site_id}/assets/{asset_id} ### Description Retrieves details for a specific site asset. ### Method GET ### Endpoint /sites/{site_id}/assets/{asset_id} ### Parameters #### Path Parameters - **site_id** (string) - Yes - The unique site identifier - **asset_id** (string) - Yes - The unique asset identifier ### Response #### Success Response (200 OK) - Returns `asset` object ``` -------------------------------- ### Get Deploy Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Retrieves the full details of a specific deploy by its unique identifier. ```APIDOC ## GET /deploys/{deploy_id} ### Description Retrieves the full details of a specific deploy by its unique identifier. ### Method GET ### Endpoint /deploys/{deploy_id} ### Parameters #### Path Parameters - **deploy_id** (string) - Yes - The unique deploy identifier ### Response #### Success Response (200 OK) - Returns a single `deploy` object with full details ``` -------------------------------- ### Configure Site TLS Certificate (Let's Encrypt) Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/site.md Initiate automatic TLS certificate provisioning using Let's Encrypt for a site's custom domain. Pass `nil` for the certificate details to trigger this behavior. The certificate state will be 'pending' or 'issued' upon completion. ```go func (n *Netlify) ConfigureSiteTLSCertificate(ctx context.Context, siteID string, cert *models.SniCertificate) (*models.SniCertificate, error) ``` ```go cert, err := client.ConfigureSiteTLSCertificate(ctx, "site-id-123", nil) if err != nil { return err } fmt.Printf("Certificate state: %s\n", cert.State) // Output: "pending" or "issued" ``` -------------------------------- ### Get Site TLS Certificate Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Retrieves the current TLS certificate details for a specific site. ```APIDOC ## GET /sites/{site_id}/ssl ### Description Retrieves the current TLS certificate details for a specific site. ### Method GET ### Endpoint /sites/{site_id}/ssl ### Parameters #### Path Parameters - **site_id** (string) - Yes - The unique site identifier ### Response #### Success Response (200 OK) - Returns `sniCertificate` object #### Example (Go) ```go cert, err := client.GetSiteTLSCertificate(ctx, "site-id-123") if err != nil { return err } fmt.Printf("Certificate state: %s, expires: %s\n", cert.State, cert.ExpiresAt) ``` ``` -------------------------------- ### Get Deploy Details Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Retrieve detailed information for a specific deploy using its unique identifier. ```http GET /deploys/{deploy_id} ``` -------------------------------- ### Get Asset Public Signature Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Retrieves a public signature for a site asset, typically used for secure downloads. ```APIDOC ## GET /sites/{site_id}/assets/{asset_id}/public_signature ### Description Retrieves a public signature for a site asset, typically used for secure downloads. ### Method GET ### Endpoint /sites/{site_id}/assets/{asset_id}/public_signature ### Parameters #### Path Parameters - **site_id** (string) - Yes - The unique site identifier - **asset_id** (string) - Yes - The unique asset identifier ### Response #### Success Response (200 OK) - Returns `assetPublicSignature` object with signed URL ``` -------------------------------- ### Response Types Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/plumbing-client.md Operations return type-specific responses that wrap the payload. Examples illustrate how to access the payload from the response object. ```APIDOC ## Response Types Operations return type-specific responses wrapping the payload: ```go resp, err := client.Operations.GetSite(params, authWriter) if err != nil { return nil, err } site := resp.Payload // *models.Site ``` Response types: - `GetSiteOK` → `Payload: *models.Site` - `ListSitesOK` → `Payload: []*models.Site` - `CreateSiteCreated` → `Payload: *models.Site` - etc. All response types are in `operations` package. ``` -------------------------------- ### Create Site with Repository Configuration Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/site.md Create a new site linked to a Git repository for CI/CD. Does not automatically configure DNS. ```go siteSetup := &models.SiteSetup{ Name: "connected-site", Repo: &models.SiteSetupRepo{ Provider: "github", RepoURL: "https://github.com/user/repo", RepoBranch: "main", }, } site, err := client.CreateSite(ctx, siteSetup, false) ``` -------------------------------- ### List Sites with Go Client Source: https://github.com/netlify/open-api/blob/master/_autodocs/README.md Demonstrates basic usage of the Netlify Open API Go client to list all sites associated with the authenticated user. Ensure the client is initialized and context is set up before making the call. ```go package main import ( "context" "fmt" "github.com/netlify/open-api/v2/go/porcelain" ) func main() { // Create client (uses default API endpoint) client := porcelain.NewHTTPClient(nil) ctx := context.Background() // List your sites sites, err := client.ListSites(ctx, &operations.ListSitesParams{}) if err != nil { fmt.Printf("Error: %v\n", err) return } for _, site := range sites { fmt.Printf("Site: %s (URL: %s)\n", site.Name, site.DeployURL) } } ``` -------------------------------- ### Check Errors When Getting a Deploy Source: https://github.com/netlify/open-api/blob/master/_autodocs/errors.md Always check for errors after API calls. Ignoring errors can lead to unexpected behavior. ```go // ✓ Good deploy, err := client.GetDeploy(ctx, deployID) if err != nil { return fmt.Errorf("failed to get deploy: %w", err) } // ✗ Bad deploy, _ := client.GetDeploy(ctx, deployID) // Ignores error ``` -------------------------------- ### Default Transport Config Function Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/plumbing-client.md Returns a new TransportConfig initialized with default values. Use this as a starting point for custom configurations. ```go func DefaultTransportConfig() *TransportConfig ``` -------------------------------- ### Get Environment Variables Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Retrieves a list of environment variables for a given account, with options to filter by context, scope, or site ID. ```APIDOC ## GET /accounts/{account_id}/env ### Description Retrieves a list of environment variables for a given account, with options to filter by context, scope, or site ID. ### Method GET ### Endpoint /accounts/{account_id}/env ### Parameters #### Path Parameters - **account_id** (string) - Yes - The unique account identifier #### Query Parameters - **context_name** (string) - No - Filter by context: 'all', 'dev', 'dev-server', 'branch-deploy', 'deploy-preview', 'production' - **scope** (string) - No - Filter by scope: 'builds', 'functions', 'runtime', 'post-processing' - **site_id** (string) - No - Filter to specific site's variables ### Response #### Success Response (200 OK) - Returns array of `envVar` objects ``` -------------------------------- ### Create New Plumbing HTTP Client Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/plumbing-client.md Instantiate a new low-level Netlify HTTP client. Pass nil for the default format registry. ```go client := plumbing.NewHTTPClient(nil) ``` -------------------------------- ### Create Site with Custom Domain Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/site.md Create a new site and automatically configure DNS records for a custom domain. Handles validation and conflict errors. ```go siteSetup := &models.SiteSetup{ Name: "my-site", CustomDomain: "example.com", } site, err := client.CreateSite(ctx, siteSetup, true) // true = auto-configure DNS if err != nil { return err } ``` -------------------------------- ### Get Environment Variables API Endpoint Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Retrieve environment variables for a specific account. You can filter by context, scope, and site ID. ```http GET /accounts/{account_id}/env ``` -------------------------------- ### CreateTicket Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/auth.md Create an authorization ticket to initiate OAuth flow. This function is part of the Netlify client and helps in starting the user authorization process. ```APIDOC ## CreateTicket ### Description Create an authorization ticket to initiate OAuth flow. ### Method `POST` (Implied by function signature and typical OAuth flow) ### Endpoint `/auth/ticket` (Inferred, not explicitly stated) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **clientID** (string) - Required - OAuth client identifier (provided during app registration) ### Request Example ```go ticket, err := client.CreateTicket(ctx, "my-app-client-id") if err != nil { return err } fmt.Printf("Ticket ID: %s\n", ticket.ID) fmt.Printf("Authorized: %v\n", ticket.Authorized) fmt.Printf("Expires: %s\n", ticket.ExpiresAt) ``` ### Response #### Success Response (200) - **ID** (string) - Unique ticket identifier (store for later exchange) - **Authorized** (bool) - Whether user has authorized (initially false) - **CreatedAt** (string) - ISO 8601 creation timestamp - **ExpiresAt** (string) - ISO 8601 expiration timestamp (usually 1 hour) #### Response Example ```json { "ID": "ticket-12345", "Authorized": false, "CreatedAt": "2023-10-27T10:00:00Z", "ExpiresAt": "2023-10-27T11:00:00Z" } ``` ### Errors - **400 Bad Request**: Invalid client ID - **500 Internal Server Error**: Service unavailable ``` -------------------------------- ### DeployOptions Structure Source: https://github.com/netlify/open-api/blob/master/_autodocs/configuration.md Defines all configuration options for a deployment, including target site, files to deploy, directory paths for functions and build outputs, draft status, retry logic, metadata, feature flags, timeouts, and progress callbacks. ```go type DeployOptions struct { // Required SiteID string // Target site ID Dir string // Files to deploy // Directories FunctionsDir string // Netlify Functions EdgeFunctionsDir string // Edge Functions EdgeRedirectsDir string // Edge redirects config DbMigrationsDir string // Database migrations BuildDir string // Build output directory // Deployment options IsDraft bool // Create draft (unpublished) SkipRetry bool // Disable retry logic // Metadata Title string // Deploy title Branch string // Git branch CommitRef string // Git commit SHA Framework string // Framework name FrameworkVersion string // Framework version // Features LargeMediaEnabled bool // Enable Netlify Large Media Environment []*models.DeployEnvironmentVariable // Timeouts UploadTimeout time.Duration // File upload timeout PreProcessTimeout time.Duration // Preprocessing timeout // Monitoring Observer DeployObserver // Progress callbacks } ``` -------------------------------- ### Site Deployment with Large Media Enabled Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/deploy.md Configure deployment options to enable Netlify Large Media for handling binary files. This is useful for projects with large assets. ```go options := &porcelain.DeployOptions{ SiteID: "site-id-123", Dir: "/path/to/build", LargeMediaEnabled: true, } deploy, err := client.DeploySite(ctx, options) ``` -------------------------------- ### Get Site Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Retrieves details for a specific site using its unique identifier. Includes an optional parameter for internal feature flag queries. ```APIDOC ## GET /sites/{site_id} ### Description Retrieves details for a specific site. ### Method GET ### Endpoint /sites/{site_id} ### Parameters #### Path Parameters - **site_id** (string) - Required - The unique site identifier #### Query Parameters - **feature_flags** (string) - Optional - Internal: feature flags query ### Response #### Success Response (200 OK) - Returns a single `site` object ``` -------------------------------- ### DeployOptions Go Struct Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/deploy.md Defines the configuration options for a deployment, including site ID, directories, build settings, and timeouts. ```go type DeployOptions struct { SiteID string Dir string FunctionsDir string EdgeFunctionsDir string EdgeRedirectsDir string DbMigrationsDir string BuildDir string LargeMediaEnabled bool Environment []*models.DeployEnvironmentVariable IsDraft bool SkipRetry bool Title string Branch string CommitRef string Framework string FrameworkVersion string UploadTimeout time.Duration PreProcessTimeout time.Duration Observer DeployObserver } ``` -------------------------------- ### DeployOptions Go Type Source: https://github.com/netlify/open-api/blob/master/_autodocs/types.md Specifies options for creating a new deploy. Includes site ID, directories for build artifacts and functions, and various configuration settings like framework and timeouts. ```go type DeployOptions struct { SiteID string Dir string FunctionsDir string EdgeFunctionsDir string EdgeRedirectsDir string DbMigrationsDir string BuildDir string LargeMediaEnabled bool Environment []*DeployEnvironmentVariable IsDraft bool SkipRetry bool Title string Branch string CommitRef string Framework string FrameworkVersion string UploadTimeout time.Duration PreProcessTimeout time.Duration Observer DeployObserver } ``` -------------------------------- ### Create New Site Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/site.md Create a new Netlify site with basic configuration. Handles 400 Bad Request, 409 Conflict, and 401 Unauthorized errors. ```go func (n *Netlify) CreateSite(ctx context.Context, site *models.SiteSetup, configureDNS bool) (*models.Site, error) ``` ```go siteSetup := &models.SiteSetup{ Name: "my-new-website", } site, err := client.CreateSite(ctx, siteSetup, false) if err != nil { return err } fmt.Printf("Created site: %s\n", site.ID) fmt.Printf("Deploy URL: %s\n", site.DeployURL) ``` -------------------------------- ### Operation Parameters Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/plumbing-client.md Plumbing operations utilize automatically-generated parameter types for defining request parameters. Examples show how to instantiate and use these parameter types. ```APIDOC ## Operation Parameters Plumbing operations use automatically-generated parameter types: ```go // Example operation parameters params := &operations.ListSitesParams{ Name: stringPtr("my-site"), Filter: stringPtr("owner"), Page: int64Ptr(1), PerPage: int64Ptr(50), } resp, err := client.Operations.ListSites(params, authWriter) ``` All parameter types are in `operations` package: - `ListSitesParams` - `GetSiteParams` - `CreateSiteParams` - `GetDeployParams` - etc. ``` -------------------------------- ### OAuth Authentication Flow (Go) Source: https://github.com/netlify/open-api/blob/master/_autodocs/README.md Demonstrates the steps for OAuth authentication, including creating a ticket, waiting for user authorization, and exchanging the ticket for an access token. ```go // 1. Create ticket ticket, _ := client.CreateTicket(ctx, "client-id") // 2. User visits auth URL and authorizes // (URL construction is client-side) // 3. Wait for authorization ticket, _ := client.WaitUntilTicketAuthorized(ctx, ticket) // 4. Exchange for access token token, _ := client.ExchangeTicket(ctx, ticket.ID) // Use token.AccessToken for future requests ``` -------------------------------- ### Using the Plumbing Client Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/plumbing-client.md Demonstrates how to make a direct API call using the plumbing client, contrasting it with the porcelain client. ```APIDOC ## ListSites Operation ### Description Retrieves a list of sites associated with the authenticated user. ### Method GET ### Endpoint /sites ### Parameters #### Query Parameters - **filter** (string) - Optional - Filter criteria for the list of sites. - **page** (integer) - Optional - Page number for pagination. - **per_page** (integer) - Optional - Number of items per page. ### Request Example ```go // Assuming 'params' is a struct with appropriate fields for filtering, pagination, etc. // Assuming 'authWriter' is a configured runtime.ClientAuthInfoWriterFunc resp, err := client.Operations.ListSites(params, authWriter) if err != nil { // Handle error } // Access the list of sites via resp.Payload sites := resp.Payload ``` ### Response #### Success Response (200) - **Payload** (array of Site) - A list of site objects. #### Response Example ```json { "id": "site-id-123", "name": "my-site", "url": "https://my-site.netlify.app" } ``` ``` -------------------------------- ### Get Form Submissions (Go) Source: https://github.com/netlify/open-api/blob/master/_autodocs/README.md Retrieves form submissions for a given site. It first lists all forms associated with the site and then fetches submissions for each form. ```go forms, _ := client.ListFormsBySiteId(ctx, siteID) for _, form := range forms { submissions, _ := client.ListFormSubmissions(ctx, form.ID) for _, sub := range submissions { fmt.Printf("%s: %s\n", sub.Email, sub.Summary) } } ``` -------------------------------- ### Get Site Information Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/site.md Retrieve detailed information for a specific site using its unique identifier. Handles 404 Not Found and 401 Unauthorized errors. ```go func (n *Netlify) GetSite(ctx context.Context, siteID string) (*models.Site, error) ``` ```go site, err := client.GetSite(ctx, "5f1c2d8e9f3b2a1c5d8e9f3b") if err != nil { return err } fmt.Printf("Site Name: %s\n", site.Name) fmt.Printf("Deploy URL: %s\n", site.DeployURL) fmt.Printf("Custom Domain: %s\n", site.CustomDomain) fmt.Printf("Git Provider: %s\n", site.GitProvider) fmt.Printf("Functions Region: %s\n", site.FunctionsRegion) ``` -------------------------------- ### Create Plumbing HTTP Client with Custom Configuration Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/plumbing-client.md Create a Netlify HTTP client with custom transport settings like host, base path, and schemes. Pass nil for the default format registry. ```go cfg := &plumbing.TransportConfig{ Host: "api.example.com", BasePath: "/api/v1", Schemes: []string{"https"}, } client := plumbing.NewHTTPClientWithConfig(nil, cfg) ``` -------------------------------- ### Get All Submissions for a Site (Go) Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/forms.md Retrieves all forms associated with a site and then iterates through each form to fetch its submissions. Handles potential errors during API calls. ```go // 1. Get all forms forms, err := client.ListFormsBySiteId(ctx, siteID) if err != nil { return err } // 2. Iterate and get submissions for each for _, form := range forms { submissions, err := client.ListFormSubmissions(ctx, form.ID) if err != nil { fmt.Printf("Error getting submissions for form %s: %v\n", form.Name, err) continue } fmt.Printf("Form: %s\n", form.Name) for _, sub := range submissions { fmt.Printf(" - %s <%s> on %s\n", sub.Name, sub.Email, sub.CreatedAt) } } ``` -------------------------------- ### Create Default Netlify HTTP Client Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/porcelain-client.md Use NewHTTPClient to create a Netlify client with default settings. Pass nil for the formats registry to use default marshaling. ```go client := porcelain.NewHTTPClient(nil) ``` -------------------------------- ### Operations Service Usage Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/plumbing-client.md The Operations service provides access to all API endpoints. Examples demonstrate how to call methods like ListSites, GetSite, CreateSite, and DeleteSite. ```APIDOC ## Operations Service The `Operations` field provides access to all API endpoints: ```go client.Operations.ListSites(params, authWriter) client.Operations.GetSite(params, authWriter) client.Operations.CreateSite(params, authWriter) client.Operations.DeleteSite(params, authWriter) // ... and many more ``` All operations are in the `operations` subpackage: ```go import "github.com/netlify/open-api/v2/go/plumbing/operations" ``` ``` -------------------------------- ### List All Site Assets and Their Sizes Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/assets.md Retrieves a list of all site assets and calculates their total size. This is useful for monitoring storage usage. ```Go params := &operations.ListSiteAssetsParams{ SiteID: siteID, } assets, err := client.ListSiteAssets(ctx, params) if err != nil { return err } var totalSize int64 for _, asset := range assets { fmt.Printf("%s: %d bytes\n", asset.Name, asset.Size) totalSize += asset.Size } fmt.Printf("Total: %d bytes (%.2f MB)\n", totalSize, float64(totalSize)/1024/1024) ``` -------------------------------- ### List Site Forms with Go SDK Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md This Go code snippet demonstrates how to use the Netlify SDK to list forms for a given site ID. Ensure you have the client initialized and error handling in place. ```go forms, err := client.ListFormsBySiteId(ctx, "site-id-123") if err != nil { return err } for _, form := range forms { fmt.Printf("Form: %s (submissions: %d)\n", form.Name, form.SubmissionCount) } ``` -------------------------------- ### Get Specific Site using Netlify API Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Retrieves details for a specific site using its unique identifier. Allows for internal feature flag queries. ```go site, err := client.GetSite(ctx, "site-id-123") if err != nil { return err } fmt.Printf("Site: %s\nDeploy URL: %s\n", site.Name, site.DeployURL) ``` -------------------------------- ### Generate Multiple Deploy Keys Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/deploy-keys.md Create separate deploy keys for different environments like production and staging. Ensure each key is stored securely with appropriate permissions. ```go // Production key prodKey, _ := client.CreateDeployKey(ctx) // Staging key stagingKey, _ := client.CreateDeployKey(ctx) // Store each securely with appropriate permissions ``` -------------------------------- ### SiteSetup Object Definition Source: https://github.com/netlify/open-api/blob/master/_autodocs/types.md Defines the configuration for creating or updating a Netlify site. It includes settings for custom domains, build configurations, and deployment preferences. ```go type SiteSetup struct { Name string CustomDomain string Domain string BuildSettings *RepoInfo BuildImage string Repo *SiteSetupRepo ForceSsl bool PreventNonGitProdDeploys *bool NotificationEmail string } ``` -------------------------------- ### New Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/plumbing-client.md Creates a plumbing client using a completely custom HTTP transport implementation and a format registry. ```APIDOC ## New ### Description Create a client with a completely custom HTTP transport. ### Method Signature ```go func New(transport runtime.ClientTransport, formats strfmt.Registry) *Netlify ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **transport** (runtime.ClientTransport) - Custom HTTP transport implementation - **formats** (strfmt.Registry) - Format registry ### Returns - `*Netlify` - Client instance ### Usage Note Used by the Porcelain client internally. ``` -------------------------------- ### List All Sites (Go) Source: https://github.com/netlify/open-api/blob/master/_autodocs/README.md Use this to retrieve a list of all sites associated with your Netlify account. Requires the `operations` package. ```go import ( "github.com/netlify/open-api/v2/go/plumbing/operations" ) sites, err := client.ListSites(ctx, &operations.ListSitesParams{}) ``` -------------------------------- ### Create Netlify Client with Custom Transport Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/porcelain-client.md Use New to create a Netlify client with a custom HTTP transport. Pass the transport and formats registry. ```go client := porcelain.New(transport, nil) ``` -------------------------------- ### Get Site Asset Public Signature Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/assets.md Generates a temporary signed URL for a private asset. Use this when you need to provide time-limited access to an asset that is not publicly available. The URL is valid for approximately one hour. ```go func (n *Netlify) GetSiteAssetPublicSignature(ctx context.Context, params *operations.GetSiteAssetPublicSignatureParams) (*models.AssetPublicSignature, error) ``` ```go params := &operations.GetSiteAssetPublicSignatureParams{ SiteID: "site-id-123", AssetID: "asset-id-456", } sig, err := client.GetSiteAssetPublicSignature(ctx, params) if err != nil { return err } fmt.Printf("Signed URL: %s\n", sig.URL) // Share URL with others - valid for ~1 hour ``` -------------------------------- ### Create Site Deploy Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Initiate the creation of a new deploy for a site. Can be created as a draft. ```http POST /sites/{site_id}/deploys ``` -------------------------------- ### Default Netlify Client Instance Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/porcelain-client.md Provides a pre-configured default client instance for simple use cases. Use this when custom configuration is not needed. ```go var Default = NewHTTPClient(nil) ``` ```go sites, err := porcelain.Default.ListSites(ctx, params) ``` -------------------------------- ### Provision Site TLS Certificate (Go) Source: https://github.com/netlify/open-api/blob/master/_autodocs/endpoints.md Provision a new TLS certificate for a site or upload a custom certificate. Initiates Let's Encrypt provisioning if certificate details are omitted. ```Go cert, err := client.ConfigureSiteTLSCertificate(ctx, "site-id-123", nil) if err != nil { return err } fmt.Printf("Certificate state: %s\n", cert.State) ``` -------------------------------- ### List All Sites Source: https://github.com/netlify/open-api/blob/master/_autodocs/api-reference/site.md Retrieves all sites accessible to the authenticated user. Use this for a general overview of your sites. ```go func (n *Netlify) ListSites(ctx context.Context, params *operations.ListSitesParams) ([]*models.Site, error) ``` ```go ctx := context.Background() // List all sites sites, err := client.ListSites(ctx, &operations.ListSitesParams{}) if err != nil { return err } for _, site := range sites { fmt.Printf("Site: %s (ID: %s, URL: %s)\n", site.Name, site.ID, site.DeployURL) } ``` -------------------------------- ### SiteSetup Object Source: https://github.com/netlify/open-api/blob/master/_autodocs/types.md Represents the configuration for creating or updating a Netlify site. It's a subset of the full Site object. ```APIDOC ## SiteSetup Object ### Description Used for creating or updating sites. Subset of `Site` fields. ### Fields - **name** (string) - No - Site name - **custom_domain** (string) - No - Primary custom domain - **domain** (string) - No - Site domain (alternative to custom_domain) - **build_settings** (RepoInfo) - No - Build configuration - **build_image** (string) - No - Build image to use - **repo** (SiteSetupRepo) - No - Repository settings - **force_ssl** (boolean) - No - Force HTTPS - **prevent_non_git_prod_deploys** (boolean) - No - Block manual deployments to production - **notification_email** (string) - No - Notification email address ``` -------------------------------- ### TransportConfig Methods Source: https://github.com/netlify/open-api/blob/master/_autodocs/configuration.md Provides methods to configure the transport settings: WithHost, WithBasePath, and WithSchemes. ```go func (cfg *TransportConfig) WithHost(host string) *TransportConfig func (cfg *TransportConfig) WithBasePath(path string) *TransportConfig func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig ```