-
Notifications
You must be signed in to change notification settings - Fork 12
/
api_segments.go
3500 lines (2906 loc) · 150 KB
/
api_segments.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
LaunchDarkly REST API
# Overview ## Authentication LaunchDarkly's REST API uses the HTTPS protocol with a minimum TLS version of 1.2. All REST API resources are authenticated with either [personal or service access tokens](https://docs.launchdarkly.com/home/account/api), or session cookies. Other authentication mechanisms are not supported. You can manage personal access tokens on your [**Authorization**](https://app.launchdarkly.com/settings/authorization) page in the LaunchDarkly UI. LaunchDarkly also has SDK keys, mobile keys, and client-side IDs that are used by our server-side SDKs, mobile SDKs, and JavaScript-based SDKs, respectively. **These keys cannot be used to access our REST API**. These keys are environment-specific, and can only perform read-only operations such as fetching feature flag settings. | Auth mechanism | Allowed resources | Use cases | | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------- | | [Personal or service access tokens](https://docs.launchdarkly.com/home/account/api) | Can be customized on a per-token basis | Building scripts, custom integrations, data export. | | SDK keys | Can only access read-only resources specific to server-side SDKs. Restricted to a single environment. | Server-side SDKs | | Mobile keys | Can only access read-only resources specific to mobile SDKs, and only for flags marked available to mobile keys. Restricted to a single environment. | Mobile SDKs | | Client-side ID | Can only access read-only resources specific to JavaScript-based client-side SDKs, and only for flags marked available to client-side. Restricted to a single environment. | Client-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 [**Authorization**](https://app.launchdarkly.com/settings/authorization) page. > > The client-side ID is safe to embed in untrusted contexts. It's designed for use in client-side JavaScript. ### Authentication using 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 [**Authorization**](https://app.launchdarkly.com/settings/authorization) page. ### Authentication using session cookie For testing purposes, you can make API calls directly from your web browser. If you are logged in to the LaunchDarkly application, the API will use your existing session to authenticate calls. If you have a [role](https://docs.launchdarkly.com/home/account/built-in-roles) other than Admin, or have a [custom role](https://docs.launchdarkly.com/home/account/custom-roles) 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 also send a JSON body. To learn more about the error format of the API, read [Errors](/#section/Overview/Errors). In practice this means that you always get a response with a `Content-Type` header set to `application/json`. In addition, request bodies for `PATCH`, `POST`, and `PUT` 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, such as a single feature flag, you receive a _detailed representation_ 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. ### Expanding responses Sometimes the detailed representation of a resource does not include all of the attributes of the resource by default. If this is the case, the request method will clearly document this and describe which attributes you can include in an expanded response. To include the additional attributes, append the `expand` request parameter to your request and add a comma-separated list of the attributes to include. For example, when you append `?expand=members,maintainers` to the [Get team](/tag/Teams#operation/getTeam) endpoint, the expanded response includes both of these attributes. ### 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`, which contains the URL - A `type`, which describes the content type For example, a feature resource might return the following: ```json { \"_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. Most resources support the [JSON patch](/reference#updates-using-json-patch) format. Some resources also support the [JSON merge patch](/reference#updates-using-json-merge-patch) format, and some resources support the [semantic patch](/reference#updates-using-semantic-patch) format, which is a way to specify the modifications to perform as a set of executable instructions. Each resource supports optional [comments](/reference#updates-with-comments) that you can submit with updates. Comments appear in outgoing webhooks, the audit log, and other integrations. When a resource supports both JSON patch and semantic patch, we document both in the request method. However, the specific request body fields and descriptions included in our documentation only match one type of patch or the other. ### Updates using JSON patch [JSON patch](https://datatracker.ietf.org/doc/html/rfc6902) is a way to specify the modifications to perform on a resource. 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. JSON patch documents are always arrays, where each element contains an operation, a path to the field to update, and the new value. For example, in this feature flag representation: ```json { \"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: ```json [{ \"op\": \"replace\", \"path\": \"/description\", \"value\": \"This is the new description\" }] ``` You can specify multiple modifications to perform in a single request. You can also test that certain preconditions are met before applying the patch: ```json [ { \"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 are not editable, such as a resource's `_links`, have names that start with an underscore. ### Updates using JSON merge patch [JSON merge patch](https://datatracker.ietf.org/doc/html/rfc7386) is another format for specifying the modifications to perform on a resource. JSON merge patch is less expressive than JSON patch. However, 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: ```json { \"description\": \"New flag description\" } ``` ### Updates using semantic patch Some resources support 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. Semantic patch allows you to be explicit about intent using precise, custom instructions. In many cases, you can define semantic patch instructions independently of the current state of the resource. This can be useful when defining a change that may be applied at a future date. To make a semantic patch request, you must append `domain-model=launchdarkly.semanticpatch` to your `Content-Type` header. Here's how: ``` Content-Type: application/json; domain-model=launchdarkly.semanticpatch ``` If you call a semantic patch resource without this header, you will receive a `400` response because your semantic patch will be interpreted as a JSON patch. The body of a semantic patch request takes the following properties: * `comment` (string): (Optional) A description of the update. * `environmentKey` (string): (Required for some resources only) The environment key. * `instructions` (array): (Required) A list of actions the update should perform. Each action in the list must be an object with a `kind` property that indicates the instruction. If the instruction requires parameters, you must include those parameters as additional fields in the object. The documentation for each resource that supports semantic patch includes the available instructions and any additional parameters. For example: ```json { \"comment\": \"optional comment\", \"instructions\": [ {\"kind\": \"turnFlagOn\"} ] } ``` If any instruction in the patch encounters an error, the endpoint returns an error and will not change the resource. In general, each instruction silently does nothing if the resource is already in the state you request. ### Updates with comments You can submit optional comments with `PATCH` changes. To submit a comment along with a JSON patch document, use the following format: ```json { \"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: ```json { \"comment\": \"This is a comment string\", \"merge\": { \"description\": \"New flag description\" } } ``` To submit a comment along with a semantic patch, use the following format: ```json { \"comment\": \"This is a comment string\", \"instructions\": [ {\"kind\": \"turnFlagOn\"} ] } ``` ## Errors The API always returns errors in a common format. Here's an example: ```json { \"code\": \"invalid_request\", \"message\": \"A feature with that key already exists\", \"id\": \"30ce6058-87da-11e4-b116-123b93f75cba\" } ``` The `code` indicates the general class of error. 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 | Code | Definition | Description | Possible Solution | | ---- | ----------------- | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | 400 | Invalid request | The request cannot be understood. | Ensure JSON syntax in request body is correct. | | 401 | Invalid access token | Requestor is unauthorized or does not have permission for this API call. | Ensure your API access token is valid and has the appropriate permissions. | | 403 | Forbidden | Requestor does not have access to this resource. | Ensure that the account member or access token has proper permissions set. | | 404 | Invalid resource identifier | The requested resource is not valid. | Ensure that the resource is correctly identified by ID or key. | | 405 | Method not allowed | The request method is not allowed on this resource. | Ensure that the HTTP verb is correct. | | 409 | Conflict | The API request can not be completed because it conflicts with a concurrent API request. | Retry your request. | | 422 | Unprocessable entity | The API request can not be completed because the update description can not be understood. | Ensure that the request body is correct for the type of patch you are using, either JSON patch or semantic patch. | 429 | Too many requests | Read [Rate limiting](/#section/Overview/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 the request returns a wildcard, `Access-Control-Allow-Origin: *`. For more information on CORS, read the [CORS W3C Recommendation](http://www.w3.org/TR/cors). Example CORS headers might look like: ```http 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](/#section/Overview/Authentication). If you are using session authentication, you should set the `withCredentials` property for your `xhr` request to `true`. You should never expose your access tokens to untrusted entities. ## Rate limiting We use several rate limiting strategies to ensure the availability of our APIs. Rate-limited calls to our APIs return a `429` status code. Calls to our APIs 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. ### Global rate limits Authenticated requests are subject to a global limit. This is the maximum number of calls that your account can make to the API per ten seconds. All service and 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 may return the headers below: | Header name | Description | | ------------------------------ | -------------------------------------------------------------------------------- | | `X-Ratelimit-Global-Remaining` | The maximum number of requests the account is permitted to make per ten seconds. | | `X-Ratelimit-Reset` | The 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 service or personal 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 return the headers below: | Header name | Description | | ----------------------------- | ----------------------------------------------------------------------------------------------------- | | `X-Ratelimit-Route-Remaining` | The maximum number of requests to the current route the account is permitted to make per ten seconds. | | `X-Ratelimit-Reset` | The 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](/tag/Environments#operation/deleteEnvironment) 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 an account can make 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) and client libraries We have a [complete OpenAPI (Swagger) specification](https://app.launchdarkly.com/api/v2/openapi.json) for our API. We auto-generate multiple client libraries based on our OpenAPI specification. To learn more, visit the [collection of client libraries on GitHub](https://github.com/search?q=topic%3Alaunchdarkly-api+org%3Alaunchdarkly&type=Repositories). You can also use this specification to generate client libraries to interact with our REST API in your language of choice. Our OpenAPI specification is supported by several API-based tools such as Postman and Insomnia. In many cases, you can directly import our specification to explore our APIs. ## 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 `DELETE`, `PATCH`, and `PUT` verbs are inaccessible. To avoid this issue, our API supports the `X-HTTP-Method-Override` header, allowing clients to \"tunnel\" `DELETE`, `PATCH`, and `PUT` requests using a `POST` request. For example, to call a `PATCH` endpoint using 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](/#section/Overview/Beta-resources). > > Resources that are in beta are still undergoing testing and development. They may change without notice, including becoming backwards incompatible. ### 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 receive a `403` response. Use this header: ``` LD-API-Version: beta ``` ## Federal environments The version of LaunchDarkly that is available on domains controlled by the United States government is different from the version of LaunchDarkly available to the general public. If you are an employee or contractor for a United States federal agency and use LaunchDarkly in your work, you likely use the federal instance of LaunchDarkly. If you are working in the federal instance of LaunchDarkly, the base URI for each request is `https://app.launchdarkly.us`. In the \"Try it\" sandbox for each request, click the request path to view the complete resource path for the federal environment. To learn more, read [LaunchDarkly in federal environments](https://docs.launchdarkly.com/home/infrastructure/federal). ## 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: 20240415 ``` The header value is the version number of the API version you would 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 `20240415` corresponds to April 15, 2024. ### Setting the API version per access token When you create 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`, which is the version of the API that existed before the current versioning scheme, 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 |<div style=\"width:75px\">Version</div> | Changes | End of life (EOL) |---|---|---| | `20240415` | <ul><li>Changed several endpoints from unpaginated to paginated. Use the `limit` and `offset` query parameters to page through the results.</li> <li>Changed the [list access tokens](/tag/Access-tokens#operation/getTokens) endpoint: <ul><li>Response is now paginated with a default limit of `25`</li></ul></li> <li>Changed the [list account members](/tag/Account-members#operation/getMembers) endpoint: <ul><li>The `accessCheck` filter is no longer available</li></ul></li> <li>Changed the [list custom roles](/tag/Custom-roles#operation/getCustomRoles) endpoint: <ul><li>Response is now paginated with a default limit of `20`</li></ul></li> <li>Changed the [list feature flags](/tag/Feature-flags#operation/getFeatureFlags) endpoint: <ul><li>Response is now paginated with a default limit of `20`</li><li>The `environments` field is now only returned if the request is filtered by environment, using the `filterEnv` query parameter</li><li>The `filterEnv` query parameter supports a maximum of three environments</li><li>The `followerId`, `hasDataExport`, `status`, `contextKindTargeted`, and `segmentTargeted` filters are no longer available</li></ul></li> <li>Changed the [list segments](/tag/Segments#operation/getSegments) endpoint: <ul><li>Response is now paginated with a default limit of `20`</li></ul></li> <li>Changed the [list teams](/tag/Teams#operation/getTeams) endpoint: <ul><li>The `expand` parameter no longer supports including `projects` or `roles`</li><li>In paginated results, the maximum page size is now 100</li></ul></li> <li>Changed the [get workflows](/tag/Workflows#operation/getWorkflows) endpoint: <ul><li>Response is now paginated with a default limit of `20`</li><li>The `_conflicts` field in the response is no longer available</li></ul></li> </ul> | Current | | `20220603` | <ul><li>Changed the [list projects](/tag/Projects#operation/getProjects) return value:<ul><li>Response is now paginated with a default limit of `20`.</li><li>Added support for filter and sort.</li><li>The project `environments` field is now expandable. This field is omitted by default.</li></ul></li><li>Changed the [get project](/tag/Projects#operation/getProject) return value:<ul><li>The `environments` field is now expandable. This field is omitted by default.</li></ul></li></ul> | 2025-04-15 | | `20210729` | <ul><li>Changed the [create approval request](/tag/Approvals#operation/postApprovalRequest) return value. It now returns HTTP Status Code `201` instead of `200`.</li><li> Changed the [get users](/tag/Users#operation/getUser) return value. It now returns a user record, not a user. </li><li>Added additional optional fields to environment, segments, flags, members, and segments, including the ability to create big segments. </li><li> Added default values for flag variations when new environments are created. </li><li>Added filtering and pagination for getting flags and members, including `limit`, `number`, `filter`, and `sort` query parameters. </li><li>Added endpoints for expiring user targets for flags and segments, scheduled changes, access tokens, Relay Proxy configuration, integrations and subscriptions, and approvals. </li></ul> | 2023-06-03 | | `20191212` | <ul><li>[List feature flags](/tag/Feature-flags#operation/getFeatureFlags) 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. </li><li> Added endpoints for flags, flag status, projects, environments, audit logs, members, users, custom roles, segments, usage, streams, events, and data export. </li></ul> | 2022-07-29 | | `20160426` | <ul><li>Initial versioning of API. Tokens created before versioning have their version set to this.</li></ul> | 2020-12-12 | To learn more about how EOL is determined, read LaunchDarkly's [End of Life (EOL) Policy](https://launchdarkly.com/policies/end-of-life-policy/).
API version: 2.0
Contact: support@launchdarkly.com
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package ldapi
import (
"bytes"
"context"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
type SegmentsApi interface {
/*
DeleteSegment Delete segment
Delete a segment.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@param segmentKey The segment key
@return ApiDeleteSegmentRequest
*/
DeleteSegment(ctx context.Context, projectKey string, environmentKey string, segmentKey string) ApiDeleteSegmentRequest
// DeleteSegmentExecute executes the request
DeleteSegmentExecute(r ApiDeleteSegmentRequest) (*http.Response, error)
/*
GetContextInstanceSegmentsMembershipByEnv List segment memberships for context instance
For a given context instance with attributes, get membership details for all segments. In the request body, pass in the context instance.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@return ApiGetContextInstanceSegmentsMembershipByEnvRequest
*/
GetContextInstanceSegmentsMembershipByEnv(ctx context.Context, projectKey string, environmentKey string) ApiGetContextInstanceSegmentsMembershipByEnvRequest
// GetContextInstanceSegmentsMembershipByEnvExecute executes the request
// @return ContextInstanceSegmentMemberships
GetContextInstanceSegmentsMembershipByEnvExecute(r ApiGetContextInstanceSegmentsMembershipByEnvRequest) (*ContextInstanceSegmentMemberships, *http.Response, error)
/*
GetExpiringTargetsForSegment Get expiring targets for segment
Get a list of a segment's context targets that are scheduled for removal.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@param segmentKey The segment key
@return ApiGetExpiringTargetsForSegmentRequest
*/
GetExpiringTargetsForSegment(ctx context.Context, projectKey string, environmentKey string, segmentKey string) ApiGetExpiringTargetsForSegmentRequest
// GetExpiringTargetsForSegmentExecute executes the request
// @return ExpiringTargetGetResponse
GetExpiringTargetsForSegmentExecute(r ApiGetExpiringTargetsForSegmentRequest) (*ExpiringTargetGetResponse, *http.Response, error)
/*
GetExpiringUserTargetsForSegment Get expiring user targets for segment
> ### Contexts are now available
>
> After you have upgraded your LaunchDarkly SDK to use contexts instead of users, you should use [Get expiring targets for segment](/tag/Segments#operation/getExpiringTargetsForSegment) instead of this endpoint. To learn more, read [Contexts](https://docs.launchdarkly.com/home/observability/contexts).
Get a list of a segment's user targets that are scheduled for removal.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@param segmentKey The segment key
@return ApiGetExpiringUserTargetsForSegmentRequest
*/
GetExpiringUserTargetsForSegment(ctx context.Context, projectKey string, environmentKey string, segmentKey string) ApiGetExpiringUserTargetsForSegmentRequest
// GetExpiringUserTargetsForSegmentExecute executes the request
// @return ExpiringUserTargetGetResponse
GetExpiringUserTargetsForSegmentExecute(r ApiGetExpiringUserTargetsForSegmentRequest) (*ExpiringUserTargetGetResponse, *http.Response, error)
/*
GetSegment Get segment
Get a single segment by key.<br/><br/>Segments can be rule-based, list-based, or synced. Big segments include larger list-based segments and synced segments. Some fields in the response only apply to big segments.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@param segmentKey The segment key
@return ApiGetSegmentRequest
*/
GetSegment(ctx context.Context, projectKey string, environmentKey string, segmentKey string) ApiGetSegmentRequest
// GetSegmentExecute executes the request
// @return UserSegment
GetSegmentExecute(r ApiGetSegmentRequest) (*UserSegment, *http.Response, error)
/*
GetSegmentMembershipForContext Get big segment membership for context
Get the membership status (included/excluded) for a given context in this big segment. Big segments include larger list-based segments and synced segments. This operation does not support standard segments.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@param segmentKey The segment key
@param contextKey The context key
@return ApiGetSegmentMembershipForContextRequest
*/
GetSegmentMembershipForContext(ctx context.Context, projectKey string, environmentKey string, segmentKey string, contextKey string) ApiGetSegmentMembershipForContextRequest
// GetSegmentMembershipForContextExecute executes the request
// @return BigSegmentTarget
GetSegmentMembershipForContextExecute(r ApiGetSegmentMembershipForContextRequest) (*BigSegmentTarget, *http.Response, error)
/*
GetSegmentMembershipForUser Get big segment membership for user
> ### Contexts are now available
>
> After you have upgraded your LaunchDarkly SDK to use contexts instead of users, you should use [Get expiring targets for segment](/tag/Segments#operation/getExpiringTargetsForSegment) instead of this endpoint. To learn more, read [Contexts](https://docs.launchdarkly.com/home/observability/contexts).
Get the membership status (included/excluded) for a given user in this big segment. This operation does not support standard segments.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@param segmentKey The segment key
@param userKey The user key
@return ApiGetSegmentMembershipForUserRequest
*/
GetSegmentMembershipForUser(ctx context.Context, projectKey string, environmentKey string, segmentKey string, userKey string) ApiGetSegmentMembershipForUserRequest
// GetSegmentMembershipForUserExecute executes the request
// @return BigSegmentTarget
GetSegmentMembershipForUserExecute(r ApiGetSegmentMembershipForUserRequest) (*BigSegmentTarget, *http.Response, error)
/*
GetSegments List segments
Get a list of all segments in the given project.
Segments can be rule-based, list-based, or synced. Big segments include larger list-based segments and synced segments. Some fields in the response only apply to big segments.
### Filtering segments
The `filter` parameter supports the following operators: `equals`, `anyOf`, and `exists`.
You can also combine filters in the following ways:
- Use a comma (`,`) as an AND operator
- Use a vertical bar (`|`) as an OR operator
- Use parentheses (`()`) to group filters
#### Supported fields and operators
You can only filter certain fields in segments when using the `filter` parameter. Additionally, you can only filter some fields with certain operators.
When you search for segments, the `filter` parameter supports the following fields and operators:
|<div style="width:120px">Field</div> |Description |Supported operators |
|---|---|---|
| `excludedKeys` | The segment keys of segments to exclude from the results. | `anyOf` |
| `external` | Whether the segment is a synced segment. | `exists` |
| `includedKeys` | The segment keys of segments to include in the results. | `anyOf` |
| `query` | A "fuzzy" search across segment key, name, and description. Supply a string or list of strings to the operator. | `equals` |
| `tags` | The segment tags. | `anyOf` |
| `unbounded` | Whether the segment is a standard segment (`false`) or a big segment (`true`). Standard segments include rule-based segments and smaller list-based segments. Big segments include larger list-based segments and synced segments. | `equals` |
Here are a few examples:
* The filter `?filter=tags anyOf ["enterprise", "beta"],query equals "toggle"` matches segments with "toggle" in their key, name, or description that also have "enterprise" or "beta" as a tag.
* The filter `?filter=excludedKeys anyOf ["segmentKey1", "segmentKey2"]` excludes the segments with those keys from the results.
* The filter `?filter=unbounded equals true` matches larger list-based segments and synced segments.
The documented values for `filter` query parameters are prior to URL encoding. For example, the `[` in `?filter=tags anyOf ["enterprise", "beta"]` must be encoded to `%5B`.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@return ApiGetSegmentsRequest
*/
GetSegments(ctx context.Context, projectKey string, environmentKey string) ApiGetSegmentsRequest
// GetSegmentsExecute executes the request
// @return UserSegments
GetSegmentsExecute(r ApiGetSegmentsRequest) (*UserSegments, *http.Response, error)
/*
PatchExpiringTargetsForSegment Update expiring targets for segment
Update expiring context targets for a segment. Updating a context target expiration uses the semantic patch format.
To make a semantic patch request, you must append `domain-model=launchdarkly.semanticpatch` to your `Content-Type` header. To learn more, read [Updates using semantic patch](/reference#updates-using-semantic-patch).
If the request is well-formed but any of its instructions failed to process, this operation returns status code `200`. In this case, the response `errors` array will be non-empty.
### Instructions
Semantic patch requests support the following `kind` instructions for updating expiring context targets.
<details>
<summary>Click to expand instructions for <strong>updating expiring context targets</strong></summary>
#### addExpiringTarget
Schedules a date and time when LaunchDarkly will remove a context from segment targeting. The segment must already have the context as an individual target.
##### Parameters
- `targetType`: The type of individual target for this context. Must be either `included` or `excluded`.
- `contextKey`: The context key.
- `contextKind`: The kind of context being targeted.
- `value`: The date when the context should expire from the segment targeting, in Unix milliseconds.
Here's an example:
```json
{
"instructions": [{
"kind": "addExpiringTarget",
"targetType": "included",
"contextKey": "user-key-123abc",
"contextKind": "user",
"value": 1754092860000
}]
}
```
#### updateExpiringTarget
Updates the date and time when LaunchDarkly will remove a context from segment targeting.
##### Parameters
- `targetType`: The type of individual target for this context. Must be either `included` or `excluded`.
- `contextKey`: The context key.
- `contextKind`: The kind of context being targeted.
- `value`: The new date when the context should expire from the segment targeting, in Unix milliseconds.
- `version`: (Optional) The version of the expiring target to update. If included, update will fail if version doesn't match current version of the expiring target.
Here's an example:
```json
{
"instructions": [{
"kind": "updateExpiringTarget",
"targetType": "included",
"contextKey": "user-key-123abc",
"contextKind": "user",
"value": 1754179260000
}]
}
```
#### removeExpiringTarget
Removes the scheduled expiration for the context in the segment.
##### Parameters
- `targetType`: The type of individual target for this context. Must be either `included` or `excluded`.
- `contextKey`: The context key.
- `contextKind`: The kind of context being targeted.
Here's an example:
```json
{
"instructions": [{
"kind": "removeExpiringTarget",
"targetType": "included",
"contextKey": "user-key-123abc",
"contextKind": "user",
}]
}
```
</details>
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@param segmentKey The segment key
@return ApiPatchExpiringTargetsForSegmentRequest
*/
PatchExpiringTargetsForSegment(ctx context.Context, projectKey string, environmentKey string, segmentKey string) ApiPatchExpiringTargetsForSegmentRequest
// PatchExpiringTargetsForSegmentExecute executes the request
// @return ExpiringTargetPatchResponse
PatchExpiringTargetsForSegmentExecute(r ApiPatchExpiringTargetsForSegmentRequest) (*ExpiringTargetPatchResponse, *http.Response, error)
/*
PatchExpiringUserTargetsForSegment Update expiring user targets for segment
> ### Contexts are now available
>
> After you have upgraded your LaunchDarkly SDK to use contexts instead of users, you should use [Update expiring targets for segment](/tag/Segments#operation/patchExpiringTargetsForSegment) instead of this endpoint. To learn more, read [Contexts](https://docs.launchdarkly.com/home/observability/contexts).
Update expiring user targets for a segment. Updating a user target expiration uses the semantic patch format.
To make a semantic patch request, you must append `domain-model=launchdarkly.semanticpatch` to your `Content-Type` header. To learn more, read [Updates using semantic patch](/reference#updates-using-semantic-patch).
If the request is well-formed but any of its instructions failed to process, this operation returns status code `200`. In this case, the response `errors` array will be non-empty.
### Instructions
Semantic patch requests support the following `kind` instructions for updating expiring user targets.
<details>
<summary>Click to expand instructions for <strong>updating expiring user targets</strong></summary>
#### addExpireUserTargetDate
Schedules a date and time when LaunchDarkly will remove a user from segment targeting.
##### Parameters
- `targetType`: A segment's target type, must be either `included` or `excluded`.
- `userKey`: The user key.
- `value`: The date when the user should expire from the segment targeting, in Unix milliseconds.
#### updateExpireUserTargetDate
Updates the date and time when LaunchDarkly will remove a user from segment targeting.
##### Parameters
- `targetType`: A segment's target type, must be either `included` or `excluded`.
- `userKey`: The user key.
- `value`: The new date when the user should expire from the segment targeting, in Unix milliseconds.
- `version`: The segment version.
#### removeExpireUserTargetDate
Removes the scheduled expiration for the user in the segment.
##### Parameters
- `targetType`: A segment's target type, must be either `included` or `excluded`.
- `userKey`: The user key.
</details>
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@param segmentKey The segment key
@return ApiPatchExpiringUserTargetsForSegmentRequest
*/
PatchExpiringUserTargetsForSegment(ctx context.Context, projectKey string, environmentKey string, segmentKey string) ApiPatchExpiringUserTargetsForSegmentRequest
// PatchExpiringUserTargetsForSegmentExecute executes the request
// @return ExpiringUserTargetPatchResponse
PatchExpiringUserTargetsForSegmentExecute(r ApiPatchExpiringUserTargetsForSegmentRequest) (*ExpiringUserTargetPatchResponse, *http.Response, error)
/*
PatchSegment Patch segment
Update a segment. The request body must be a valid semantic patch, JSON patch, or JSON merge patch. To learn more the different formats, read [Updates](/#section/Overview/Updates).
### Using semantic patches on a segment
To make a semantic patch request, you must append `domain-model=launchdarkly.semanticpatch` to your `Content-Type` header. To learn more, read [Updates using semantic patch](/reference#updates-using-semantic-patch).
The body of a semantic patch request for updating segments requires an `environmentKey` in addition to `instructions` and an optional `comment`. The body of the request takes the following properties:
* `comment` (string): (Optional) A description of the update.
* `environmentKey` (string): (Required) The key of the LaunchDarkly environment.
* `instructions` (array): (Required) A list of actions the update should perform. Each action in the list must be an object with a `kind` property that indicates the instruction. If the action requires parameters, you must include those parameters as additional fields in the object.
### Instructions
Semantic patch requests support the following `kind` instructions for updating segments.
<details>
<summary>Click to expand instructions for <strong>updating segments</strong></summary>
#### addIncludedTargets
Adds context keys to the individual context targets included in the segment for the specified `contextKind`. Returns an error if this causes the same context key to be both included and excluded.
##### Parameters
- `contextKind`: The context kind the targets should be added to.
- `values`: List of keys.
Here's an example:
```json
{
"instructions": [{
"kind": "addIncludedTargets",
"contextKind": "org",
"values": [ "org-key-123abc", "org-key-456def" ]
}]
}
```
#### addIncludedUsers
Adds user keys to the individual user targets included in the segment. Returns an error if this causes the same user key to be both included and excluded. If you are working with contexts, use `addIncludedTargets` instead of this instruction.
##### Parameters
- `values`: List of user keys.
Here's an example:
```json
{
"instructions": [{
"kind": "addIncludedUsers",
"values": [ "user-key-123abc", "user-key-456def" ]
}]
}
```
#### addExcludedTargets
Adds context keys to the individual context targets excluded in the segment for the specified `contextKind`. Returns an error if this causes the same context key to be both included and excluded.
##### Parameters
- `contextKind`: The context kind the targets should be added to.
- `values`: List of keys.
Here's an example:
```json
{
"instructions": [{
"kind": "addExcludedTargets",
"contextKind": "org",
"values": [ "org-key-123abc", "org-key-456def" ]
}]
}
```
#### addExcludedUsers
Adds user keys to the individual user targets excluded from the segment. Returns an error if this causes the same user key to be both included and excluded. If you are working with contexts, use `addExcludedTargets` instead of this instruction.
##### Parameters
- `values`: List of user keys.
Here's an example:
```json
{
"instructions": [{
"kind": "addExcludedUsers",
"values": [ "user-key-123abc", "user-key-456def" ]
}]
}
```
#### removeIncludedTargets
Removes context keys from the individual context targets included in the segment for the specified `contextKind`.
##### Parameters
- `contextKind`: The context kind the targets should be removed from.
- `values`: List of keys.
Here's an example:
```json
{
"instructions": [{
"kind": "removeIncludedTargets",
"contextKind": "org",
"values": [ "org-key-123abc", "org-key-456def" ]
}]
}
```
#### removeIncludedUsers
Removes user keys from the individual user targets included in the segment. If you are working with contexts, use `removeIncludedTargets` instead of this instruction.
##### Parameters
- `values`: List of user keys.
Here's an example:
```json
{
"instructions": [{
"kind": "removeIncludedUsers",
"values": [ "user-key-123abc", "user-key-456def" ]
}]
}
```
#### removeExcludedTargets
Removes context keys from the individual context targets excluded from the segment for the specified `contextKind`.
##### Parameters
- `contextKind`: The context kind the targets should be removed from.
- `values`: List of keys.
Here's an example:
```json
{
"instructions": [{
"kind": "removeExcludedTargets",
"contextKind": "org",
"values": [ "org-key-123abc", "org-key-456def" ]
}]
}
```
#### removeExcludedUsers
Removes user keys from the individual user targets excluded from the segment. If you are working with contexts, use `removeExcludedTargets` instead of this instruction.
##### Parameters
- `values`: List of user keys.
Here's an example:
```json
{
"instructions": [{
"kind": "removeExcludedUsers",
"values": [ "user-key-123abc", "user-key-456def" ]
}]
}
```
#### updateName
Updates the name of the segment.
##### Parameters
- `value`: Name of the segment.
Here's an example:
```json
{
"instructions": [{
"kind": "updateName",
"value": "Updated segment name"
}]
}
```
</details>
## Using JSON patches on a segment
If you do not include the header described above, you can use a [JSON patch](/reference#updates-using-json-patch) or [JSON merge patch](https://datatracker.ietf.org/doc/html/rfc7386) representation of the desired changes.
For example, to update the description for a segment with a JSON patch, use the following request body:
```json
{
"patch": [
{
"op": "replace",
"path": "/description",
"value": "new description"
}
]
}
```
To update fields in the segment that are arrays, set the `path` to the name of the field and then append `/<array index>`. Use `/0` to add the new entry to the beginning of the array. Use `/-` to add the new entry to the end of the array.
For example, to add a rule to a segment, use the following request body:
```json
{
"patch":[
{
"op": "add",
"path": "/rules/0",
"value": {
"clauses": [{ "contextKind": "user", "attribute": "email", "op": "endsWith", "values": [".edu"], "negate": false }]
}
}
]
}
```
To add or remove targets from segments, we recommend using semantic patch. Semantic patch for segments includes specific instructions for adding and removing both included and excluded targets.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@param segmentKey The segment key
@return ApiPatchSegmentRequest
*/
PatchSegment(ctx context.Context, projectKey string, environmentKey string, segmentKey string) ApiPatchSegmentRequest
// PatchSegmentExecute executes the request
// @return UserSegment
PatchSegmentExecute(r ApiPatchSegmentRequest) (*UserSegment, *http.Response, error)
/*
PostSegment Create segment
Create a new segment.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@return ApiPostSegmentRequest
*/
PostSegment(ctx context.Context, projectKey string, environmentKey string) ApiPostSegmentRequest
// PostSegmentExecute executes the request
// @return UserSegment
PostSegmentExecute(r ApiPostSegmentRequest) (*UserSegment, *http.Response, error)
/*
UpdateBigSegmentContextTargets Update context targets on a big segment
Update context targets included or excluded in a big segment. Big segments include larger list-based segments and synced segments. This operation does not support standard segments.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@param segmentKey The segment key
@return ApiUpdateBigSegmentContextTargetsRequest
*/
UpdateBigSegmentContextTargets(ctx context.Context, projectKey string, environmentKey string, segmentKey string) ApiUpdateBigSegmentContextTargetsRequest
// UpdateBigSegmentContextTargetsExecute executes the request
UpdateBigSegmentContextTargetsExecute(r ApiUpdateBigSegmentContextTargetsRequest) (*http.Response, error)
/*
UpdateBigSegmentTargets Update user context targets on a big segment
Update user context targets included or excluded in a big segment. Big segments include larger list-based segments and synced segments. This operation does not support standard segments.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@param segmentKey The segment key
@return ApiUpdateBigSegmentTargetsRequest
*/
UpdateBigSegmentTargets(ctx context.Context, projectKey string, environmentKey string, segmentKey string) ApiUpdateBigSegmentTargetsRequest
// UpdateBigSegmentTargetsExecute executes the request
UpdateBigSegmentTargetsExecute(r ApiUpdateBigSegmentTargetsRequest) (*http.Response, error)
}
// SegmentsApiService SegmentsApi service
type SegmentsApiService service
type ApiDeleteSegmentRequest struct {
ctx context.Context
ApiService SegmentsApi
projectKey string
environmentKey string
segmentKey string
}
func (r ApiDeleteSegmentRequest) Execute() (*http.Response, error) {
return r.ApiService.DeleteSegmentExecute(r)
}
/*
DeleteSegment Delete segment
Delete a segment.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@param segmentKey The segment key
@return ApiDeleteSegmentRequest
*/
func (a *SegmentsApiService) DeleteSegment(ctx context.Context, projectKey string, environmentKey string, segmentKey string) ApiDeleteSegmentRequest {
return ApiDeleteSegmentRequest{
ApiService: a,
ctx: ctx,
projectKey: projectKey,
environmentKey: environmentKey,
segmentKey: segmentKey,
}
}
// Execute executes the request
func (a *SegmentsApiService) DeleteSegmentExecute(r ApiDeleteSegmentRequest) (*http.Response, error) {
var (
localVarHTTPMethod = http.MethodDelete
localVarPostBody interface{}
formFiles []formFile
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "SegmentsApiService.DeleteSegment")
if err != nil {
return nil, &GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/api/v2/segments/{projectKey}/{environmentKey}/{segmentKey}"
localVarPath = strings.Replace(localVarPath, "{"+"projectKey"+"}", url.PathEscape(parameterToString(r.projectKey, "")), -1)
localVarPath = strings.Replace(localVarPath, "{"+"environmentKey"+"}", url.PathEscape(parameterToString(r.environmentKey, "")), -1)
localVarPath = strings.Replace(localVarPath, "{"+"segmentKey"+"}", url.PathEscape(parameterToString(r.segmentKey, "")), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
if r.ctx != nil {
// API Key Authentication
if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {
if apiKey, ok := auth["ApiKey"]; ok {
var key string
if apiKey.Prefix != "" {
key = apiKey.Prefix + " " + apiKey.Key
} else {
key = apiKey.Key
}
localVarHeaderParams["Authorization"] = key
}
}
}
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)
if err != nil {
return nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarHTTPResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))
if err != nil {
return localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := &GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 401 {
var v UnauthorizedErrorRep
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarHTTPResponse, newErr
}
newErr.model = v
return localVarHTTPResponse, newErr
}
if localVarHTTPResponse.StatusCode == 403 {
var v ForbiddenErrorRep
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarHTTPResponse, newErr
}
newErr.model = v
return localVarHTTPResponse, newErr
}
if localVarHTTPResponse.StatusCode == 404 {
var v NotFoundErrorRep
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarHTTPResponse, newErr
}
newErr.model = v
return localVarHTTPResponse, newErr
}
if localVarHTTPResponse.StatusCode == 409 {
var v StatusConflictErrorRep
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarHTTPResponse, newErr
}
newErr.model = v
return localVarHTTPResponse, newErr
}
if localVarHTTPResponse.StatusCode == 429 {
var v RateLimitedErrorRep
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarHTTPResponse, newErr
}
return localVarHTTPResponse, nil
}
type ApiGetContextInstanceSegmentsMembershipByEnvRequest struct {
ctx context.Context
ApiService SegmentsApi
projectKey string
environmentKey string
requestBody *map[string]interface{}
}
func (r ApiGetContextInstanceSegmentsMembershipByEnvRequest) RequestBody(requestBody map[string]interface{}) ApiGetContextInstanceSegmentsMembershipByEnvRequest {
r.requestBody = &requestBody
return r
}
func (r ApiGetContextInstanceSegmentsMembershipByEnvRequest) Execute() (*ContextInstanceSegmentMemberships, *http.Response, error) {
return r.ApiService.GetContextInstanceSegmentsMembershipByEnvExecute(r)
}
/*
GetContextInstanceSegmentsMembershipByEnv List segment memberships for context instance
For a given context instance with attributes, get membership details for all segments. In the request body, pass in the context instance.
@param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
@param projectKey The project key
@param environmentKey The environment key
@return ApiGetContextInstanceSegmentsMembershipByEnvRequest
*/
func (a *SegmentsApiService) GetContextInstanceSegmentsMembershipByEnv(ctx context.Context, projectKey string, environmentKey string) ApiGetContextInstanceSegmentsMembershipByEnvRequest {
return ApiGetContextInstanceSegmentsMembershipByEnvRequest{
ApiService: a,
ctx: ctx,
projectKey: projectKey,
environmentKey: environmentKey,
}
}
// Execute executes the request
// @return ContextInstanceSegmentMemberships
func (a *SegmentsApiService) GetContextInstanceSegmentsMembershipByEnvExecute(r ApiGetContextInstanceSegmentsMembershipByEnvRequest) (*ContextInstanceSegmentMemberships, *http.Response, error) {
var (
localVarHTTPMethod = http.MethodPost
localVarPostBody interface{}
formFiles []formFile
localVarReturnValue *ContextInstanceSegmentMemberships
)
localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "SegmentsApiService.GetContextInstanceSegmentsMembershipByEnv")
if err != nil {
return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}
}
localVarPath := localBasePath + "/api/v2/projects/{projectKey}/environments/{environmentKey}/segments/evaluate"
localVarPath = strings.Replace(localVarPath, "{"+"projectKey"+"}", url.PathEscape(parameterToString(r.projectKey, "")), -1)
localVarPath = strings.Replace(localVarPath, "{"+"environmentKey"+"}", url.PathEscape(parameterToString(r.environmentKey, "")), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
if r.requestBody == nil {
return localVarReturnValue, nil, reportError("requestBody is required and must be specified")
}
// to determine the Content-Type header
localVarHTTPContentTypes := []string{"application/json"}
// set Content-Type header
localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)
if localVarHTTPContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHTTPContentType
}
// to determine the Accept header
localVarHTTPHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)
if localVarHTTPHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept
}
// body params
localVarPostBody = r.requestBody
if r.ctx != nil {
// API Key Authentication
if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {
if apiKey, ok := auth["ApiKey"]; ok {
var key string
if apiKey.Prefix != "" {
key = apiKey.Prefix + " " + apiKey.Key
} else {
key = apiKey.Key
}
localVarHeaderParams["Authorization"] = key
}
}
}
req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHTTPResponse, err := a.client.callAPI(req)
if err != nil || localVarHTTPResponse == nil {
return localVarReturnValue, localVarHTTPResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)
localVarHTTPResponse.Body.Close()
localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))
if err != nil {
return localVarReturnValue, localVarHTTPResponse, err
}
if localVarHTTPResponse.StatusCode >= 300 {
newErr := &GenericOpenAPIError{
body: localVarBody,
error: localVarHTTPResponse.Status,
}
if localVarHTTPResponse.StatusCode == 400 {
var v InvalidRequestErrorRep
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHTTPResponse, newErr
}
if localVarHTTPResponse.StatusCode == 401 {
var v UnauthorizedErrorRep
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHTTPResponse, newErr
}
if localVarHTTPResponse.StatusCode == 404 {
var v NotFoundErrorRep
err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHTTPResponse, newErr
}
newErr.model = v
}
return localVarReturnValue, localVarHTTPResponse, newErr
}
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type"))
if err != nil {
newErr := &GenericOpenAPIError{
body: localVarBody,