Skip to content

feat: autogenerate go SDK example in the codeSample #772

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 91 additions & 3 deletions tools/cli/internal/openapi/filter/code_sample.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,47 @@
package filter

import (
"bytes"
"fmt"
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The main changes were in this file. The files under tests were autogenerated.

goFormat "go/format"
"strings"
"text/template"
"time"

"github.com/getkin/kin-openapi/openapi3"
"github.com/mongodb/openapi/tools/cli/internal/apiversion"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)

const goSDKTemplate = `import (
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[follow up] conmsider creating a sdk.go.tmpl file and using embedded here, using a template file will give you some code highlighting

"os"
"context"
"log"
sdk "go.mongodb.org/atlas-sdk/v{{ .Version }}/admin"
)

func main() {
ctx := context.Background()
clientID := os.Getenv("MONGODB_ATLAS_CLIENT_ID")
clientSecret := os.Getenv("MONGODB_ATLAS_CLIENT_SECRET")

client, err := sdk.NewClient(
sdk.UseOAuthAuth(clientID, clientSecret),
sdk.UseBaseURL(url))

if err != nil {
log.Fatalf("Error: %v", err)
}

params = &sdk.{{ .OperationID }}ApiParams{}
{{ if eq .Method "DELETE" }} httpResp, err := client.{{ .Tag }}Api.
{{ .OperationID }}WithParams(ctx, params).
Execute(){{ else }} sdkResp, httpResp, err := client.{{ .Tag }}Api.
{{ .OperationID }}WithParams(ctx, params).
Execute(){{ end}}
}`

const codeSampleExtensionName = "x-codeSamples"

// https://redocly.com/docs-legacy/api-reference-docs/specification-extensions/x-code-samples#x-codesamples
Expand Down Expand Up @@ -121,6 +156,47 @@ func newAtlasCliCodeSamplesForOperation(op *openapi3.Operation) codeSample {
}
}

func (f *CodeSampleFilter) newGoSdkCodeSamplesForOperation(op *openapi3.Operation, opMethod string) (*codeSample, error) {
version := strings.ReplaceAll(apiVersion(f.metadata.targetVersion), "-", "") + "001"
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This field represents the SDK version. The value is formatted as YYYY-MM-DD-001, where 001 indicates the first SDK release for that API version. The last three digits are incremented for subsequent releases, but 001 will always be available as the initial version for each API version.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A bit curious on how this version stays in sync with the latest SDK version:

  1. Is this reference to the SDK version always being published before SDK?
  2. Or there is a mechanism for reading the latest SDK version?

Copy link
Collaborator Author

@andreaangiolillo andreaangiolillo Jun 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, neither of those options apply. I generate the SDK version by combining the API version in the format YYYY-DD.MM with 001 as the suffix, which represents the first release for any new API version and is always present. Subsequent releases for the same API version will follow the format YYYY-DD.MM-002, YYYY-DD.MM-003, and so on, but the example will always use the initial 001 release.
If I merge this, I will then create a ticket to improve this to check for the release in the sdk repo but I don't think is critical for the initial example since the 001 is always present.

operationID := cases.Title(language.English, cases.NoLower).String(op.OperationID)
tag := strings.ReplaceAll(op.Tags[0], " ", "")
tag = strings.ReplaceAll(tag, ".", "")

t, err := template.New("goSDK").Parse(goSDKTemplate)
if err != nil {
return nil, err
}

var buffer bytes.Buffer
err = t.Execute(&buffer, struct {
Tag string
OperationID string
Version string
Method string
}{
Tag: tag,
OperationID: operationID,
Version: version,
Method: opMethod,
})

if err != nil {
return nil, err
}

formattedResult, err := goFormat.Source(buffer.Bytes())
if err != nil {
return nil, fmt.Errorf("tag: %q, operationId: %q code: %q: error: %w",
op.Tags[0], operationID, buffer.String(), err)
}

return &codeSample{
Lang: "go",
Label: "Go",
Source: string(formattedResult),
}, nil
}

func (f *CodeSampleFilter) includeCodeSamplesForOperation(pathName, opMethod string, op *openapi3.Operation) error {
if op == nil || opMethod == "" || pathName == "" {
return nil
Expand All @@ -130,10 +206,22 @@ func (f *CodeSampleFilter) includeCodeSamplesForOperation(pathName, opMethod str
op.Extensions = map[string]any{}
}

op.Extensions[codeSampleExtensionName] = []codeSample{
codeSamples := []codeSample{
newAtlasCliCodeSamplesForOperation(op),
f.newServiceAccountCurlCodeSamplesForOperation(pathName, opMethod),
f.newDigestCurlCodeSamplesForOperation(pathName, opMethod),
}

if f.metadata.targetVersion.IsStable() {
sdkSample, err := f.newGoSdkCodeSamplesForOperation(op, opMethod)
if err != nil {
return err
}
codeSamples = append(codeSamples, *sdkSample)
}

codeSamples = append(
codeSamples,
f.newServiceAccountCurlCodeSamplesForOperation(pathName, opMethod),
f.newDigestCurlCodeSamplesForOperation(pathName, opMethod))
op.Extensions[codeSampleExtensionName] = codeSamples
return nil
}
21 changes: 21 additions & 0 deletions tools/cli/internal/openapi/filter/code_sample_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ func TestCodeSampleFilter(t *testing.T) {
},
},
})),
Tags: []string{"TestTag"},
Extensions: map[string]any{
"x-sunset": "9999-12-31",
},
Expand All @@ -73,6 +74,7 @@ func TestCodeSampleFilter(t *testing.T) {
},
},
})),
Tags: []string{"TestTag"},
Extensions: map[string]any{
"x-sunset": "9999-12-31",
"x-codeSamples": []codeSample{
Expand All @@ -81,6 +83,25 @@ func TestCodeSampleFilter(t *testing.T) {
Label: "Atlas CLI",
Source: "atlas api testOperationID --help",
},
{
Lang: "go",
Label: "Go",
Source: "import (\n" +
"\t\"os\"\n \"context\"\n" + "\t\"log\"\n" +
"\tsdk \"go.mongodb.org/atlas-sdk/v20250101001/admin\"\n)\n\n" +
"func main() {\n" +
"\tctx := context.Background()\n" +
"\tclientID := os.Getenv(\"MONGODB_ATLAS_CLIENT_ID\")\n" +
"\tclientSecret := os.Getenv(\"MONGODB_ATLAS_CLIENT_SECRET\")\n\n" +
"\tclient, err := sdk.NewClient(\n" +
"\t\tsdk.UseOAuthAuth(clientID, clientSecret),\n" +
"\t\tsdk.UseBaseURL(url))\n\n" +
"\tif err != nil {\n" + "\t\tlog.Fatalf(\"Error: %v\", err)\n\t}\n\n" +
"\tparams = &sdk.TestOperationIDApiParams{}\n" +
"\tsdkResp, httpResp, err := client.TestTagApi.\n" +
"\t\tTestOperationIDWithParams(ctx, params).\n" +
"\t\tExecute()" + "\n}",
},
{
Lang: "cURL",
Label: "curl (Service Accounts)",
Expand Down
1,685 changes: 1,685 additions & 0 deletions tools/cli/test/data/split/dev/openapi-v2-2023-01-01.json

Large diffs are not rendered by default.

Loading
Loading