Categorygithub.com/launchdarkly/api-client-go

# README

This repository contains a client library for LaunchDarkly's REST API. This client was automatically generated from our OpenAPI specification using a code generation library. View our sample code for example usage.

This REST API is for custom integrations, data export, or automating your feature flag workflows. DO NOT use this client library to include feature flags in your web or mobile application. To integrate feature flags with your application, read the SDK documentation.

Go API client for ldapi

Overview

Authentication

All REST API resources are authenticated with either personal or service access tokens, or session cookies. Other authentication mechanisms are not supported. You can manage personal access tokens on your Account settings page.

LaunchDarkly also has SDK keys, mobile keys, and client-side IDs that are used by our server-side SDKs, mobile SDKs, and client-side SDKs, respectively. These keys cannot be used to access our REST API. These keys are environment-specific, and can only perform read-only operations (fetching feature flag settings).

Auth mechanismAllowed resourcesUse cases
Personal access tokensCan be customized on a per-token basisBuilding scripts, custom integrations, data export
SDK keysCan only access read-only SDK-specific resources and the firehose, restricted to a single environmentServer-side SDKs, Firehose API
Mobile keysCan only access read-only mobile SDK-specific resources, restricted to a single environmentMobile SDKs
Client-side IDSingle environment, only flags marked available to client-sideClient-side JavaScript

Keep your access tokens and SDK keys private

Access tokens should never be exposed in untrusted contexts. Never put an access token in client-side JavaScript, or embed it in a mobile application. LaunchDarkly has special mobile keys that you can embed in mobile apps. If you accidentally expose an access token or SDK key, you can reset it from your Account Settings page.

The client-side ID is safe to embed in untrusted contexts. It's designed for use in client-side JavaScript.

Via request header

The preferred way to authenticate with the API is by adding an Authorization header containing your access token to your requests. The value of the Authorization header must be your access token.

Manage personal access tokens from the Account Settings page.

Via session cookie

For testing purposes, you can make API calls directly from your web browser. If you're logged in to the application, the API will use your existing session to authenticate calls.

If you have a role other than Admin, or have a custom role defined, you may not have permission to perform some API calls. You will receive a 401 response code in that case.

Modifying the Origin header causes an error

LaunchDarkly validates that the Origin header for any API request authenticated by a session cookie matches the expected Origin header. The expected Origin header is https://app.launchdarkly.com.

If the Origin header does not match what's expected, LaunchDarkly returns an error. This error can prevent the LaunchDarkly app from working correctly.

Any browser extension that intentionally changes the Origin header can cause this problem. For example, the Allow-Control-Allow-Origin: * Chrome extension changes the Origin header to http://evil.com and causes the app to fail.

To prevent this error, do not modify your Origin header.

LaunchDarkly does not require origin matching when authenticating with an access token, so this issue does not affect normal API usage.

Representations

All resources expect and return JSON response bodies. Error responses will also send a JSON body. Read Errors for a more detailed description of the error format used by the API.

In practice this means that you always get a response with a Content-Type header set to application/json.

In addition, request bodies for PUT, POST, REPORT and PATCH requests must be encoded as JSON with a Content-Type header set to application/json.

Summary and detailed representations

When you fetch a list of resources, the response includes only the most important attributes of each resource. This is a summary representation of the resource. When you fetch an individual resource (for example, a single feature flag), you receive a detailed representation containing all of the attributes of the resource.

The best way to find a detailed representation is to follow links. Every summary representation includes a link to its detailed representation.

Links and addressability

The best way to navigate the API is by following links. These are attributes in representations that link to other resources. The API always uses the same format for links:

  • Links to other resources within the API are encapsulated in a _links object.
  • If the resource has a corresponding link to HTML content on the site, it is stored in a special _site link.

Each link has two attributes: an href (the URL) and a type (the content type). For example, a feature resource might return the following:

{
  \"_links\": {
    \"parent\": {
      \"href\": \"/api/features\",
      \"type\": \"application/json\"
    },
    \"self\": {
      \"href\": \"/api/features/sort.order\",
      \"type\": \"application/json\"
    }
  },
  \"_site\": {
    \"href\": \"/features/sort.order\",
    \"type\": \"text/html\"
  }
}

From this, you can navigate to the parent collection of features by following the parent link, or navigate to the site page for the feature by following the _site link.

Collections are always represented as a JSON object with an items attribute containing an array of representations. Like all other representations, collections have _links defined at the top level.

Paginated collections include first, last, next, and prev links containing a URL with the respective set of elements in the collection.

Updates

Resources that accept partial updates use the PATCH verb, and support the JSON Patch format. Some resources also support the JSON Merge Patch format. In addition, some resources support optional comments that can be submitted with updates. Comments appear in outgoing webhooks, the audit log, and other integrations.

Updates via JSON Patch

JSON Patch is a way to specify the modifications to perform on a resource. For example, in this feature flag representation:

{
    \"name\": \"New recommendations engine\",
    \"key\": \"engine.enable\",
    \"description\": \"This is the description\",
    ...
}

You can change the feature flag's description with the following patch document:

[{ \"op\": \"replace\", \"path\": \"/description\", \"value\": \"This is the new description\" }]

JSON Patch documents are always arrays. You can specify multiple modifications to perform in a single request. You can also test that certain preconditions are met before applying the patch:

[
  { \"op\": \"test\", \"path\": \"/version\", \"value\": 10 },
  { \"op\": \"replace\", \"path\": \"/description\", \"value\": \"The new description\" }
]

The above patch request tests whether the feature flag's version is 10, and if so, changes the feature flag's description.

Attributes that aren't editable, like a resource's _links, have names that start with an underscore.

Updates via JSON Merge Patch

The API also supports the JSON Merge Patch format, as well as the Update feature flag resource.

JSON Merge Patch is less expressive than JSON Patch but in many cases, it is simpler to construct a merge patch document. For example, you can change a feature flag's description with the following merge patch document:

{
  \"description\": \"New flag description\"
}

Updates with comments

You can submit optional comments with PATCH changes. The Update feature flag resource supports comments.

To submit a comment along with a JSON Patch document, use the following format:

{
  \"comment\": \"This is a comment string\",
  \"patch\": [{ \"op\": \"replace\", \"path\": \"/description\", \"value\": \"The new description\" }]
}

To submit a comment along with a JSON Merge Patch document, use the following format:

{
  \"comment\": \"This is a comment string\",
  \"merge\": { \"description\": \"New flag description\" }
}

Updates via semantic patches

The API also supports the Semantic patch format. A semantic PATCH is a way to specify the modifications to perform on a resource as a set of executable instructions.

JSON Patch uses paths and a limited set of operations to describe how to transform the current state of the resource into a new state. Semantic patch allows you to be explicit about intent using precise, custom instructions. In many cases, semantic patch instructions can also be defined independently of the current state of the resource. This can be useful when defining a change that may be applied at a future date.

For example, in this feature flag configuration in environment Production:

{
    \"name\": \"Alternate sort order\",
    \"kind\": \"boolean\",
    \"key\": \"sort.order\",
   ...
    \"environments\": {
        \"production\": {
            \"on\": true,
            \"archived\": false,
            \"salt\": \"c29ydC5vcmRlcg==\",
            \"sel\": \"8de1085cb7354b0ab41c0e778376dfd3\",
            \"lastModified\": 1469131558260,
            \"version\": 81,
            \"targets\": [
                {
                    \"values\": [
                        \"[email protected]\"
                    ],
                    \"variation\": 0
                },
                {
                    \"values\": [
                        \"1461797806429-33-861961230\",
                        \"438580d8-02ee-418d-9eec-0085cab2bdf0\"
                    ],
                    \"variation\": 1
                }
            ],
            \"rules\": [],
            \"fallthrough\": {
                \"variation\": 0
            },
            \"offVariation\": 1,
            \"prerequisites\": [],
            \"_site\": {
                \"href\": \"/default/production/features/sort.order\",
                \"type\": \"text/html\"
            }
       }
    }
}

You can add a date you want a user to be removed from the feature flag's user targets. For example, “remove user 1461797806429-33-861961230 from the user target for variation 0 on the Alternate sort order flag in the production environment on Wed Jul 08 2020 at 15:27:41 pm”. This is done using the following:

{
  \"comment\": \"update expiring user targets\",
  \"instructions\": [
    {
      \"kind\": \"removeExpireUserTargetDate\",
      \"userKey\": \"userKey\",
      \"variationId\": \"978d53f9-7fe3-4a63-992d-97bcb4535dc8\"
    },
    {
      \"kind\": \"updateExpireUserTargetDate\",
      \"userKey\": \"userKey2\",
      \"variationId\": \"978d53f9-7fe3-4a63-992d-97bcb4535dc8\",
      \"value\": 1587582000000
    },
    {
      \"kind\": \"addExpireUserTargetDate\",
      \"userKey\": \"userKey3\",
      \"variationId\": \"978d53f9-7fe3-4a63-992d-97bcb4535dc8\",
      \"value\": 1594247266386
    }
  ]
}

Here is another example. In this feature flag configuration:

{
  \"name\": \"New recommendations engine\",
  \"key\": \"engine.enable\",
  \"environments\": {
    \"test\": {
      \"on\": true
    }
  }
}

You can change the feature flag's description with the following patch document as a set of executable instructions. For example, “add user X to targets for variation Y and remove user A from targets for variation B for test flag”:

{
  \"comment\": \"\",
  \"instructions\": [
    {
      \"kind\": \"removeUserTargets\",
      \"values\": [\"438580d8-02ee-418d-9eec-0085cab2bdf0\"],
      \"variationId\": \"852cb784-54ff-46b9-8c35-5498d2e4f270\"
    },
    {
      \"kind\": \"addUserTargets\",
      \"values\": [\"438580d8-02ee-418d-9eec-0085cab2bdf0\"],
      \"variationId\": \"1bb18465-33b6-49aa-a3bd-eeb6650b33ad\"
    }
  ]
}

Supported semantic patch API endpoints

Errors

The API always returns errors in a common format. Here's an example:

{
  \"code\": \"invalid_request\",
  \"message\": \"A feature with that key already exists\",
  \"id\": \"30ce6058-87da-11e4-b116-123b93f75cba\"
}

The general class of error is indicated by the code. The message is a human-readable explanation of what went wrong. The id is a unique identifier. Use it when you're working with LaunchDarkly support to debug a problem with a specific API call.

HTTP Status - Error Response Codes

CodeDefinitionDesc.Possible Solution
400Bad RequestA request that fails may return this HTTP response code.Ensure JSON syntax in request body is correct.
401UnauthorizedUser doesn't have permission to an API call.Ensure your SDK key is good.
403ForbiddenUser does not have permission for operation.Ensure that the user or access token has proper permissions set.
409ConflictThe API request could not be completed because it conflicted with a concurrent API request.Retry your request.
429Too many requestsSee Rate limiting.Wait and try again later.

CORS

The LaunchDarkly API supports Cross Origin Resource Sharing (CORS) for AJAX requests from any origin. If an Origin header is given in a request, it will be echoed as an explicitly allowed origin. Otherwise, a wildcard is returned: Access-Control-Allow-Origin: *. For more information on CORS, see the CORS W3C Recommendation. Example CORS headers might look like:

Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, Authorization
Access-Control-Allow-Methods: OPTIONS, GET, DELETE, PATCH
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 300

You can make authenticated CORS calls just as you would make same-origin calls, using either token or session-based authentication. If you’re using session auth, you should set the withCredentials property for your xhr request to true. You should never expose your access tokens to untrusted users.

Rate limiting

We use several rate limiting strategies to ensure the availability of our APIs. Rate-limited calls to our APIs will return a 429 status code. Calls to our APIs will include headers indicating the current rate limit status. The specific headers returned depend on the API route being called. The limits differ based on the route, authentication mechanism, and other factors. Routes that are not rate limited may not contain any of the headers described below.

Rate limiting and SDKs

LaunchDarkly SDKs are never rate limited and do not use the API endpoints defined here. LaunchDarkly uses a different set of approaches, including streaming/server-sent events and a global CDN, to ensure availability to the routes used by LaunchDarkly SDKs.

The client-side ID is safe to embed in untrusted contexts. It's designed for use in client-side JavaScript.

Global rate limits

Authenticated requests are subject to a global limit. This is the maximum number of calls that can be made to the API per ten seconds. All personal access tokens on the account share this limit, so exceeding the limit with one access token will impact other tokens. Calls that are subject to global rate limits will return the headers below:

Header nameDescription
X-Ratelimit-Global-RemainingThe maximum number of requests the account is permitted to make per ten seconds.
X-Ratelimit-ResetThe time at which the current rate limit window resets in epoch milliseconds.

We do not publicly document the specific number of calls that can be made globally. This limit may change, and we encourage clients to program against the specification, relying on the two headers defined above, rather than hardcoding to the current limit.

Route-level rate limits

Some authenticated routes have custom rate limits. These also reset every ten seconds. Any access tokens hitting the same route share this limit, so exceeding the limit with one access token may impact other tokens. Calls that are subject to route-level rate limits will return the headers below:

Header nameDescription
X-Ratelimit-Route-RemainingThe maximum number of requests to the current route the account is permitted to make per ten seconds.
X-Ratelimit-ResetThe time at which the current rate limit window resets in epoch milliseconds.

A route represents a specific URL pattern and verb. For example, the Delete environment endpoint is considered a single route, and each call to delete an environment counts against your route-level rate limit for that route.

We do not publicly document the specific number of calls that can be made to each endpoint per ten seconds. These limits may change, and we encourage clients to program against the specification, relying on the two headers defined above, rather than hardcoding to the current limits.

IP-based rate limiting

We also employ IP-based rate limiting on some API routes. If you hit an IP-based rate limit, your API response will include a Retry-After header indicating how long to wait before re-trying the call. Clients must wait at least Retry-After seconds before making additional calls to our API, and should employ jitter and backoff strategies to avoid triggering rate limits again.

OpenAPI (Swagger)

We have a complete OpenAPI (Swagger) specification for our API.

You can use this specification to generate client libraries to interact with our REST API in your language of choice.

This specification is supported by several API-based tools such as Postman and Insomnia. In many cases, you can directly import our specification to ease use in navigating the APIs in the tooling.

Client libraries

We auto-generate multiple client libraries based on our OpenAPI specification. To learn more, visit GitHub.

Method Overriding

Some firewalls and HTTP clients restrict the use of verbs other than GET and POST. In those environments, our API endpoints that use PUT, PATCH, and DELETE verbs will be inaccessible.

To avoid this issue, our API supports the X-HTTP-Method-Override header, allowing clients to "tunnel" PUT, PATCH, and DELETE requests via a POST request.

For example, if you wish to call one of our PATCH resources via a POST request, you can include X-HTTP-Method-Override:PATCH as a header.

Beta resources

We sometimes release new API resources in beta status before we release them with general availability.

Resources that are in beta are still undergoing testing and development. They may change without notice, including becoming backwards incompatible.

We try to promote resources into general availability as quickly as possible. This happens after sufficient testing and when we're satisfied that we no longer need to make backwards-incompatible changes.

We mark beta resources with a "Beta" callout in our documentation, pictured below:

This feature is in beta

To use this feature, pass in a header including the LD-API-Version key with value set to beta. Use this header with each call. To learn more, read Beta resources.

Using beta resources

To use a beta resource, you must include a header in the request. If you call a beta resource without this header, you'll receive a 403 response.

Use this header:

LD-API-Version: beta

Versioning

We try hard to keep our REST API backwards compatible, but we occasionally have to make backwards-incompatible changes in the process of shipping new features. These breaking changes can cause unexpected behavior if you don't prepare for them accordingly.

Updates to our REST API include support for the latest features in LaunchDarkly. We also release a new version of our REST API every time we make a breaking change. We provide simultaneous support for multiple API versions so you can migrate from your current API version to a new version at your own pace.

Setting the API version per request

You can set the API version on a specific request by sending an LD-API-Version header, as shown in the example below:

LD-API-Version: 20210729

The header value is the version number of the API version you'd like to request. The number for each version corresponds to the date the version was released in yyyymmdd format. In the example above the version 20210729 corresponds to July 29, 2021.

Setting the API version per access token

When creating an access token, you must specify a specific version of the API to use. This ensures that integrations using this token cannot be broken by version changes.

Tokens created before versioning was released have their version set to 20160426 (the version of the API that existed before versioning) so that they continue working the same way they did before versioning.

If you would like to upgrade your integration to use a new API version, you can explicitly set the header described above.

Best practice: Set the header for every client or integration

We recommend that you set the API version header explicitly in any client or integration you build.

Only rely on the access token API version during manual testing.

API version changelog

VersionChanges
20210729
  • Changed the create approval request return value. It now returns HTTP Status Code 201 instead of 200.
  • Changed the get users return value. It now returns a user record, not a user.
  • Added additional optional fields to environment, segments, flags, members, and segments, including the ability to create Big Segments.
  • Added default values for flag variations when new environments are created.
  • Added filtering and pagination for getting flags and members, including limit, number, filter, and sort query parameters.
  • Added endpoints for expiring user targets for flags and segments, scheduled changes, access tokens, Relay Proxy configuration, integrations and subscriptions, and approvals.
20191212
  • List feature flags now defaults to sending summaries of feature flag configurations, equivalent to setting the query parameter summary=true. Summaries omit flag targeting rules and individual user targets from the payload.
  • Added endpoints for flags, flag status, projects, environments, users, audit logs, members, users, custom roles, segments, usage, streams, events, and data export.
20160426
  • Initial versioning of API. Tokens created before versioning have their version set to this.

Overview

This API client was generated by the OpenAPI Generator project. By using the OpenAPI-spec from a remote server, you can easily generate an API client.

  • API version: 2.0
  • Package version: 8
  • Build package: org.openapitools.codegen.languages.GoClientCodegen For more information, please visit https://support.launchdarkly.com

Installation

Install the following dependencies:

go get github.com/stretchr/testify/assert
go get golang.org/x/oauth2
go get golang.org/x/net/context

Put the package under your project folder and add the following in import:

import sw "./ldapi"

To use a proxy, set the environment variable HTTP_PROXY:

os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port")

Configuration of Server URL

Default configuration comes with Servers field that contains server objects as defined in the OpenAPI specification.

Select Server Configuration

For using other server than the one defined on index 0 set context value sw.ContextServerIndex of type int.

ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1)

Templated Server URL

Templated server URL is formatted using default variables from configuration or from context value sw.ContextServerVariables of type map[string]string.

ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{
	"basePath": "v2",
})

Note, enum values are always validated and all unused variables are silently ignored.

URLs Configuration per Operation

Each operation can use different server URL defined using OperationServers map in the Configuration. An operation is uniquely identified by "{classname}Service.{nickname}" string. Similar rules for overriding default operation server index and variables applies by using sw.ContextOperationServerIndices and sw.ContextOperationServerVariables context maps.

ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{
	"{classname}Service.{nickname}": 2,
})
ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{
	"{classname}Service.{nickname}": {
		"port": "8443",
	},
})

Documentation for API Endpoints

All URIs are relative to https://app.launchdarkly.com

ClassMethodHTTP requestDescription
AccessTokensApiDeleteTokenDelete /api/v2/tokens/{id}Delete access token
AccessTokensApiGetTokenGet /api/v2/tokens/{id}Get access token
AccessTokensApiGetTokensGet /api/v2/tokensList access tokens
AccessTokensApiPatchTokenPatch /api/v2/tokens/{id}Patch access token
AccessTokensApiPostTokenPost /api/v2/tokensCreate access token
AccessTokensApiResetTokenPost /api/v2/tokens/{id}/resetReset access token
AccountMembersApiDeleteMemberDelete /api/v2/members/{id}Delete account member
AccountMembersApiGetMemberGet /api/v2/members/{id}Get account member
AccountMembersApiGetMembersGet /api/v2/membersList account members
AccountMembersApiPatchMemberPatch /api/v2/members/{id}Modify an account member
AccountMembersApiPostMemberTeamsPost /api/v2/members/{id}/teamsAdd member to teams
AccountMembersApiPostMembersPost /api/v2/membersInvite new members
AccountUsageBetaApiGetEvaluationsUsageGet /api/v2/usage/evaluations/{projectKey}/{environmentKey}/{featureFlagKey}Get evaluations usage
AccountUsageBetaApiGetEventsUsageGet /api/v2/usage/events/{type}Get events usage
AccountUsageBetaApiGetMauSdksByTypeGet /api/v2/usage/mau/sdksGet MAU SDKs by type
AccountUsageBetaApiGetMauUsageGet /api/v2/usage/mauGet MAU usage
AccountUsageBetaApiGetMauUsageByCategoryGet /api/v2/usage/mau/bycategoryGet MAU usage by category
AccountUsageBetaApiGetStreamUsageGet /api/v2/usage/streams/{source}Get stream usage
AccountUsageBetaApiGetStreamUsageBySdkVersionGet /api/v2/usage/streams/{source}/bysdkversionGet stream usage by SDK version
AccountUsageBetaApiGetStreamUsageSdkversionGet /api/v2/usage/streams/{source}/sdkversionsGet stream usage SDK versions
ApprovalsApiDeleteApprovalRequestDelete /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/approval-requests/{id}Delete approval request
ApprovalsApiGetApprovalGet /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/approval-requests/{id}Get approval request
ApprovalsApiGetApprovalsGet /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/approval-requestsList all approval requests
ApprovalsApiPostApprovalRequestPost /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/approval-requestsCreate approval request
ApprovalsApiPostApprovalRequestApplyRequestPost /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/approval-requests/{id}/applyApply approval request
ApprovalsApiPostApprovalRequestReviewPost /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/approval-requests/{id}/reviewsReview approval request
ApprovalsApiPostFlagCopyConfigApprovalRequestPost /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/approval-requests-flag-copyCreate approval request to copy flag configurations across environments
AuditLogApiGetAuditLogEntriesGet /api/v2/auditlogList audit log feature flag entries
AuditLogApiGetAuditLogEntryGet /api/v2/auditlog/{id}Get audit log entry
CodeReferencesApiDeleteBranchesPost /api/v2/code-refs/repositories/{repo}/branch-delete-tasksDelete branches
CodeReferencesApiDeleteRepositoryDelete /api/v2/code-refs/repositories/{repo}Delete repository
CodeReferencesApiGetBranchGet /api/v2/code-refs/repositories/{repo}/branches/{branch}Get branch
CodeReferencesApiGetBranchesGet /api/v2/code-refs/repositories/{repo}/branchesList branches
CodeReferencesApiGetExtinctionsGet /api/v2/code-refs/extinctionsList extinctions
CodeReferencesApiGetRepositoriesGet /api/v2/code-refs/repositoriesList repositories
CodeReferencesApiGetRepositoryGet /api/v2/code-refs/repositories/{repo}Get repository
CodeReferencesApiGetRootStatisticGet /api/v2/code-refs/statisticsGet links to code reference repositories for each project
CodeReferencesApiGetStatisticsGet /api/v2/code-refs/statistics/{projectKey}Get number of code references for flags
CodeReferencesApiPatchRepositoryPatch /api/v2/code-refs/repositories/{repo}Update repository
CodeReferencesApiPostExtinctionPost /api/v2/code-refs/repositories/{repo}/branches/{branch}/extinction-eventsCreate extinction
CodeReferencesApiPostRepositoryPost /api/v2/code-refs/repositoriesCreate repository
CodeReferencesApiPutBranchPut /api/v2/code-refs/repositories/{repo}/branches/{branch}Upsert branch
CustomRolesApiDeleteCustomRoleDelete /api/v2/roles/{customRoleKey}Delete custom role
CustomRolesApiGetCustomRoleGet /api/v2/roles/{customRoleKey}Get custom role
CustomRolesApiGetCustomRolesGet /api/v2/rolesList custom roles
CustomRolesApiPatchCustomRolePatch /api/v2/roles/{customRoleKey}Update custom role
CustomRolesApiPostCustomRolePost /api/v2/rolesCreate custom role
DataExportDestinationsApiDeleteDestinationDelete /api/v2/destinations/{projectKey}/{environmentKey}/{id}Delete Data Export destination
DataExportDestinationsApiGetDestinationGet /api/v2/destinations/{projectKey}/{environmentKey}/{id}Get destination
DataExportDestinationsApiGetDestinationsGet /api/v2/destinationsList destinations
DataExportDestinationsApiPatchDestinationPatch /api/v2/destinations/{projectKey}/{environmentKey}/{id}Update Data Export destination
DataExportDestinationsApiPostDestinationPost /api/v2/destinations/{projectKey}/{environmentKey}Create data export destination
EnvironmentsApiDeleteEnvironmentDelete /api/v2/projects/{projectKey}/environments/{environmentKey}Delete environment
EnvironmentsApiGetEnvironmentGet /api/v2/projects/{projectKey}/environments/{environmentKey}Get environment
EnvironmentsApiPatchEnvironmentPatch /api/v2/projects/{projectKey}/environments/{environmentKey}Update environment
EnvironmentsApiPostEnvironmentPost /api/v2/projects/{projectKey}/environmentsCreate environment
EnvironmentsApiResetEnvironmentMobileKeyPost /api/v2/projects/{projectKey}/environments/{environmentKey}/mobileKeyReset environment mobile SDK key
EnvironmentsApiResetEnvironmentSDKKeyPost /api/v2/projects/{projectKey}/environments/{environmentKey}/apiKeyReset environment SDK key
ExperimentsBetaApiGetExperimentGet /api/v2/flags/{projectKey}/{featureFlagKey}/experiments/{environmentKey}/{metricKey}Get experiment results
ExperimentsBetaApiResetExperimentDelete /api/v2/flags/{projectKey}/{featureFlagKey}/experiments/{environmentKey}/{metricKey}/resultsReset experiment results
FeatureFlagsApiCopyFeatureFlagPost /api/v2/flags/{projectKey}/{featureFlagKey}/copyCopy feature flag
FeatureFlagsApiDeleteFeatureFlagDelete /api/v2/flags/{projectKey}/{featureFlagKey}Delete feature flag
FeatureFlagsApiGetExpiringUserTargetsGet /api/v2/flags/{projectKey}/{featureFlagKey}/expiring-user-targets/{environmentKey}Get expiring user targets for feature flag
FeatureFlagsApiGetFeatureFlagGet /api/v2/flags/{projectKey}/{featureFlagKey}Get feature flag
FeatureFlagsApiGetFeatureFlagStatusGet /api/v2/flag-statuses/{projectKey}/{environmentKey}/{featureFlagKey}Get feature flag status
FeatureFlagsApiGetFeatureFlagStatusAcrossEnvironmentsGet /api/v2/flag-status/{projectKey}/{featureFlagKey}Get flag status across environments
FeatureFlagsApiGetFeatureFlagStatusesGet /api/v2/flag-statuses/{projectKey}/{environmentKey}List feature flag statuses
FeatureFlagsApiGetFeatureFlagsGet /api/v2/flags/{projectKey}List feature flags
FeatureFlagsApiPatchExpiringUserTargetsPatch /api/v2/flags/{projectKey}/{featureFlagKey}/expiring-user-targets/{environmentKey}Update expiring user targets on feature flag
FeatureFlagsApiPatchFeatureFlagPatch /api/v2/flags/{projectKey}/{featureFlagKey}Update feature flag
FeatureFlagsApiPostFeatureFlagPost /api/v2/flags/{projectKey}Create a feature flag
FeatureFlagsBetaApiGetDependentFlagsGet /api/v2/flags/{projectKey}/{featureFlagKey}/dependent-flagsList dependent feature flags
FeatureFlagsBetaApiGetDependentFlagsByEnvGet /api/v2/flags/{projectKey}/{environmentKey}/{featureFlagKey}/dependent-flagsList dependent feature flags by environment
FlagLinksBetaApiCreateFlagLinkPost /api/v2/flag-links/projects/{projectKey}/flags/{featureFlagKey}Create flag link
FlagLinksBetaApiDeleteFlagLinkDelete /api/v2/flag-links/projects/{projectKey}/flags/{featureFlagKey}/{id}Delete flag link
FlagLinksBetaApiGetFlagLinksGet /api/v2/flag-links/projects/{projectKey}/flags/{featureFlagKey}List flag links
FlagLinksBetaApiUpdateFlagLinkPatch /api/v2/flag-links/projects/{projectKey}/flags/{featureFlagKey}/{id}Update flag link
FlagTriggersApiCreateTriggerWorkflowPost /api/v2/flags/{projectKey}/{featureFlagKey}/triggers/{environmentKey}Create flag trigger
FlagTriggersApiDeleteTriggerWorkflowDelete /api/v2/flags/{projectKey}/{featureFlagKey}/triggers/{environmentKey}/{id}Delete flag trigger
FlagTriggersApiGetTriggerWorkflowByIdGet /api/v2/flags/{projectKey}/{featureFlagKey}/triggers/{environmentKey}/{id}Get flag trigger by ID
FlagTriggersApiGetTriggerWorkflowsGet /api/v2/flags/{projectKey}/{featureFlagKey}/triggers/{environmentKey}List flag triggers
FlagTriggersApiPatchTriggerWorkflowPatch /api/v2/flags/{projectKey}/{featureFlagKey}/triggers/{environmentKey}/{id}Update flag trigger
IntegrationAuditLogSubscriptionsApiCreateSubscriptionPost /api/v2/integrations/{integrationKey}Create audit log subscription
IntegrationAuditLogSubscriptionsApiDeleteSubscriptionDelete /api/v2/integrations/{integrationKey}/{id}Delete audit log subscription
IntegrationAuditLogSubscriptionsApiGetSubscriptionByIDGet /api/v2/integrations/{integrationKey}/{id}Get audit log subscription by ID
IntegrationAuditLogSubscriptionsApiGetSubscriptionsGet /api/v2/integrations/{integrationKey}Get audit log subscriptions by integration
IntegrationAuditLogSubscriptionsApiUpdateSubscriptionPatch /api/v2/integrations/{integrationKey}/{id}Update audit log subscription
IntegrationDeliveryConfigurationsBetaApiCreateIntegrationDeliveryConfigurationPost /api/v2/integration-capabilities/featureStore/{projectKey}/{environmentKey}/{integrationKey}Create delivery configuration
IntegrationDeliveryConfigurationsBetaApiDeleteIntegrationDeliveryConfigurationDelete /api/v2/integration-capabilities/featureStore/{projectKey}/{environmentKey}/{integrationKey}/{id}Delete delivery configuration
IntegrationDeliveryConfigurationsBetaApiGetIntegrationDeliveryConfigurationByEnvironmentGet /api/v2/integration-capabilities/featureStore/{projectKey}/{environmentKey}Get delivery configurations by environment
IntegrationDeliveryConfigurationsBetaApiGetIntegrationDeliveryConfigurationByIdGet /api/v2/integration-capabilities/featureStore/{projectKey}/{environmentKey}/{integrationKey}/{id}Get delivery configuration by ID
IntegrationDeliveryConfigurationsBetaApiGetIntegrationDeliveryConfigurationsGet /api/v2/integration-capabilities/featureStoreList all delivery configurations
IntegrationDeliveryConfigurationsBetaApiPatchIntegrationDeliveryConfigurationPatch /api/v2/integration-capabilities/featureStore/{projectKey}/{environmentKey}/{integrationKey}/{id}Update delivery configuration
IntegrationDeliveryConfigurationsBetaApiValidateIntegrationDeliveryConfigurationPost /api/v2/integration-capabilities/featureStore/{projectKey}/{environmentKey}/{integrationKey}/{id}/validateValidate delivery configuration
MetricsApiDeleteMetricDelete /api/v2/metrics/{projectKey}/{metricKey}Delete metric
MetricsApiGetMetricGet /api/v2/metrics/{projectKey}/{metricKey}Get metric
MetricsApiGetMetricsGet /api/v2/metrics/{projectKey}List metrics
MetricsApiPatchMetricPatch /api/v2/metrics/{projectKey}/{metricKey}Update metric
MetricsApiPostMetricPost /api/v2/metrics/{projectKey}Create metric
OtherApiGetIpsGet /api/v2/public-ip-listGets the public IP list
OtherApiGetOpenapiSpecGet /api/v2/openapi.jsonGets the OpenAPI spec in json
OtherApiGetRootGet /api/v2Root resource
OtherApiGetVersionsGet /api/v2/versionsGet version information
ProjectsApiDeleteProjectDelete /api/v2/projects/{projectKey}Delete project
ProjectsApiGetProjectGet /api/v2/projects/{projectKey}Get project
ProjectsApiGetProjectsGet /api/v2/projectsList projects
ProjectsApiPatchProjectPatch /api/v2/projects/{projectKey}Update project
ProjectsApiPostProjectPost /api/v2/projectsCreate project
RelayProxyConfigurationsApiDeleteRelayAutoConfigDelete /api/v2/account/relay-auto-configs/{id}Delete Relay Proxy config by ID
RelayProxyConfigurationsApiGetRelayProxyConfigGet /api/v2/account/relay-auto-configs/{id}Get Relay Proxy config
RelayProxyConfigurationsApiGetRelayProxyConfigsGet /api/v2/account/relay-auto-configsList Relay Proxy configs
RelayProxyConfigurationsApiPatchRelayAutoConfigPatch /api/v2/account/relay-auto-configs/{id}Update a Relay Proxy config
RelayProxyConfigurationsApiPostRelayAutoConfigPost /api/v2/account/relay-auto-configsCreate a new Relay Proxy config
RelayProxyConfigurationsApiResetRelayAutoConfigPost /api/v2/account/relay-auto-configs/{id}/resetReset Relay Proxy configuration key
ScheduledChangesApiDeleteFlagConfigScheduledChangesDelete /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/scheduled-changes/{id}Delete scheduled changes workflow
ScheduledChangesApiGetFeatureFlagScheduledChangeGet /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/scheduled-changes/{id}Get a scheduled change
ScheduledChangesApiGetFlagConfigScheduledChangesGet /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/scheduled-changesList scheduled changes
ScheduledChangesApiPatchFlagConfigScheduledChangePatch /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/scheduled-changes/{id}Update scheduled changes workflow
ScheduledChangesApiPostFlagConfigScheduledChangesPost /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/scheduled-changesCreate scheduled changes workflow
SegmentsApiDeleteSegmentDelete /api/v2/segments/{projectKey}/{environmentKey}/{segmentKey}Delete segment
SegmentsApiGetExpiringUserTargetsForSegmentGet /api/v2/segments/{projectKey}/{segmentKey}/expiring-user-targets/{environmentKey}Get expiring user targets for segment
SegmentsApiGetSegmentGet /api/v2/segments/{projectKey}/{environmentKey}/{segmentKey}Get segment
SegmentsApiGetSegmentMembershipForUserGet /api/v2/segments/{projectKey}/{environmentKey}/{segmentKey}/users/{userKey}Get Big Segment membership for user
SegmentsApiGetSegmentsGet /api/v2/segments/{projectKey}/{environmentKey}List segments
SegmentsApiPatchExpiringUserTargetsForSegmentPatch /api/v2/segments/{projectKey}/{segmentKey}/expiring-user-targets/{environmentKey}Update expiring user targets for segment
SegmentsApiPatchSegmentPatch /api/v2/segments/{projectKey}/{environmentKey}/{segmentKey}Patch segment
SegmentsApiPostSegmentPost /api/v2/segments/{projectKey}/{environmentKey}Create segment
SegmentsApiUpdateBigSegmentTargetsPost /api/v2/segments/{projectKey}/{environmentKey}/{segmentKey}/usersUpdate targets on a Big Segment
SegmentsBetaApiCreateBigSegmentExportPost /api/v2/segments/{projectKey}/{environmentKey}/{segmentKey}/exportsCreate Big Segment export
SegmentsBetaApiCreateBigSegmentImportPost /api/v2/segments/{projectKey}/{environmentKey}/{segmentKey}/importsCreate Big Segment import
SegmentsBetaApiGetBigSegmentExportGet /api/v2/segments/{projectKey}/{environmentKey}/{segmentKey}/exports/{exportID}Get Big Segment export
SegmentsBetaApiGetBigSegmentImportGet /api/v2/segments/{projectKey}/{environmentKey}/{segmentKey}/imports/{importID}Get Big Segment import
TagsApiGetTagsGet /api/v2/tagsList tags
TeamsBetaApiDeleteTeamDelete /api/v2/teams/{teamKey}Delete team
TeamsBetaApiGetTeamGet /api/v2/teams/{teamKey}Get team
TeamsBetaApiGetTeamMaintainersGet /api/v2/teams/{teamKey}/maintainersGet team maintainers
TeamsBetaApiGetTeamRolesGet /api/v2/teams/{teamKey}/rolesGet team custom roles
TeamsBetaApiGetTeamsGet /api/v2/teamsList teams
TeamsBetaApiPatchTeamPatch /api/v2/teams/{teamKey}Update team
TeamsBetaApiPostTeamPost /api/v2/teamsCreate team
TeamsBetaApiPostTeamMembersPost /api/v2/teams/{teamKey}/membersAdd members to team
UserSettingsApiGetExpiringFlagsForUserGet /api/v2/users/{projectKey}/{userKey}/expiring-user-targets/{environmentKey}Get expiring dates on flags for user
UserSettingsApiGetUserFlagSettingGet /api/v2/users/{projectKey}/{environmentKey}/{userKey}/flags/{featureFlagKey}Get flag setting for user
UserSettingsApiGetUserFlagSettingsGet /api/v2/users/{projectKey}/{environmentKey}/{userKey}/flagsList flag settings for user
UserSettingsApiPatchExpiringFlagsForUserPatch /api/v2/users/{projectKey}/{userKey}/expiring-user-targets/{environmentKey}Update expiring user target for flags
UserSettingsApiPutFlagSettingPut /api/v2/users/{projectKey}/{environmentKey}/{userKey}/flags/{featureFlagKey}Update flag settings for user
UsersApiDeleteUserDelete /api/v2/users/{projectKey}/{environmentKey}/{userKey}Delete user
UsersApiGetSearchUsersGet /api/v2/user-search/{projectKey}/{environmentKey}Find users
UsersApiGetUserGet /api/v2/users/{projectKey}/{environmentKey}/{userKey}Get user
UsersApiGetUsersGet /api/v2/users/{projectKey}/{environmentKey}List users
UsersBetaApiGetUserAttributeNamesGet /api/v2/user-attributes/{projectKey}/{environmentKey}Get user attribute names
WebhooksApiDeleteWebhookDelete /api/v2/webhooks/{id}Delete webhook
WebhooksApiGetAllWebhooksGet /api/v2/webhooksList webhooks
WebhooksApiGetWebhookGet /api/v2/webhooks/{id}Get webhook
WebhooksApiPatchWebhookPatch /api/v2/webhooks/{id}Update webhook
WebhooksApiPostWebhookPost /api/v2/webhooksCreates a webhook
WorkflowsBetaApiDeleteWorkflowDelete /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/workflows/{workflowId}Delete workflow
WorkflowsBetaApiGetCustomWorkflowGet /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/workflows/{workflowId}Get custom workflow
WorkflowsBetaApiGetWorkflowsGet /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/workflowsGet workflows
WorkflowsBetaApiPostWorkflowPost /api/v2/projects/{projectKey}/flags/{featureFlagKey}/environments/{environmentKey}/workflowsCreate workflow

Documentation For Models

Documentation For Authorization

ApiKey

  • Type: API key
  • API key parameter name: Authorization
  • Location: HTTP header

Note, each API key must be added to a map of map[string]APIKey where the key is: Authorization and passed in as the auth context for each request.

Documentation for Utility Methods

Due to the fact that model structure members are all pointers, this package contains a number of utility functions to easily obtain pointers to values of basic types. Each of these functions takes a value of the given basic type and returns a pointer to it:

  • PtrBool
  • PtrInt
  • PtrInt32
  • PtrInt64
  • PtrFloat
  • PtrFloat32
  • PtrFloat64
  • PtrString
  • PtrTime

Author

[email protected]

Sample Code

package main

import (
	"context"
	"fmt"
	"os"

	ldapi "github.com/launchdarkly/api-client-go"
)

func main() {
	apiKey := os.Getenv("LD_API_KEY")
	if apiKey == "" {
		panic("LD_API_KEY env var was empty!")
	}
	client := ldapi.NewAPIClient(ldapi.NewConfiguration())

	auth := make(map[string]ldapi.APIKey)
	auth["ApiKey"] = ldapi.APIKey{
		Key: apiKey,
	}

	ctx := context.WithValue(context.Background(), ldapi.ContextAPIKeys, auth)

	flagName := "Test Flag Go"
	flagKey := "test-go"
	// Create a multi-variate feature flag
	valOneVal := []int{1, 2}
	valOne := map[string]interface{}{"one": valOneVal}
	valTwoVal := []int{4, 5}
	valTwo := map[string]interface{}{"two": valTwoVal}
	body := ldapi.FeatureFlagBody{
		Name: flagName,
		Key:  flagKey,
		Variations: &[]ldapi.Variation{
			{Value: &valOne},
			{Value: &valTwo},
		},
	}
	flag, resp, err := client.FeatureFlagsApi.PostFeatureFlag(ctx, "openapi").FeatureFlagBody(body).Execute()
	if err != nil {
		if resp.StatusCode != 409 {
			panic(fmt.Errorf("create failed: %s", err))
		} else {
			if _, err := client.FeatureFlagsApi.DeleteFeatureFlag(ctx, "openapi", body.Key).Execute(); err != nil {
				panic(fmt.Errorf("delete failed: %s", err))
			}
			flag, resp, err = client.FeatureFlagsApi.PostFeatureFlag(ctx, "openapi").FeatureFlagBody(body).Execute()
			if err != nil {
				panic(fmt.Errorf("create failed: %s", err))
			}
		}
	}
	fmt.Printf("Created flag: %+v\n", flag)
	// Clean up new flag
	defer func() {
		if _, err := client.FeatureFlagsApi.DeleteFeatureFlag(ctx, "openapi", body.Key).Execute(); err != nil {
			panic(fmt.Errorf("delete failed: %s", err))
		}
	}()
}

func intfPtr(i interface{}) *interface{} {
	return &i
}

# Packages

No description provided by the author