CreateAPIKey creates a new API key with the given ACL for the specified application.
( accessToken, appID string, acl []string, description string, )
| 541 | |
| 542 | // CreateAPIKey creates a new API key with the given ACL for the specified application. |
| 543 | func (c *Client) CreateAPIKey( |
| 544 | accessToken, appID string, |
| 545 | acl []string, |
| 546 | description string, |
| 547 | ) (string, error) { |
| 548 | payload := CreateAPIKeyRequest{ACL: acl, Description: description} |
| 549 | body, err := json.Marshal(payload) |
| 550 | if err != nil { |
| 551 | return "", err |
| 552 | } |
| 553 | |
| 554 | endpoint := fmt.Sprintf("%s/1/applications/%s/api-keys", c.APIURL, url.PathEscape(appID)) |
| 555 | req, err := http.NewRequest(http.MethodPost, endpoint, bytes.NewReader(body)) |
| 556 | if err != nil { |
| 557 | return "", err |
| 558 | } |
| 559 | c.setAPIHeaders(req, accessToken) |
| 560 | req.Header.Set("Content-Type", "application/json") |
| 561 | |
| 562 | resp, err := c.client.Do(req) |
| 563 | if err != nil { |
| 564 | return "", fmt.Errorf("create API key request failed: %w", err) |
| 565 | } |
| 566 | defer resp.Body.Close() |
| 567 | |
| 568 | respBody, err := io.ReadAll(resp.Body) |
| 569 | if err != nil { |
| 570 | return "", fmt.Errorf("failed to read API key response: %w", err) |
| 571 | } |
| 572 | |
| 573 | if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { |
| 574 | return "", fmt.Errorf( |
| 575 | "create API key failed with status %d: %s", |
| 576 | resp.StatusCode, |
| 577 | string(respBody), |
| 578 | ) |
| 579 | } |
| 580 | |
| 581 | var keyResp CreateAPIKeyResponse |
| 582 | if err := json.Unmarshal(respBody, &keyResp); err != nil { |
| 583 | return "", fmt.Errorf( |
| 584 | "failed to parse API key response: %w (body: %s)", |
| 585 | err, |
| 586 | string(respBody), |
| 587 | ) |
| 588 | } |
| 589 | |
| 590 | key := keyResp.Data.Attributes.Value |
| 591 | if key == "" { |
| 592 | return "", fmt.Errorf( |
| 593 | "API key creation succeeded but no key was returned in the response: %s", |
| 594 | string(respBody), |
| 595 | ) |
| 596 | } |
| 597 | |
| 598 | return key, nil |
| 599 | } |
| 600 |
no test coverage detected