Skip to content
Open
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
44 changes: 6 additions & 38 deletions internal/cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,12 @@ package api

import (
"fmt"
"strings"

"github.com/langchain-ai/langsmith-cli/internal/cmdutil"
"github.com/spf13/cobra"
)

// NewCmd creates the top-level `langsmith api` command.
func NewCmd() *cobra.Command {
var (
body string
headers []string
include bool
)

cmd := &cobra.Command{
Use: "api",
Short: "Browse API endpoints and make authenticated requests",
Expand All @@ -32,45 +24,21 @@ Make requests:
langsmith api POST runs/query --body '{"session_id":"abc"}'
langsmith api DELETE sessions/abc-123
langsmith api POST datasets --body @body.json
echo '{"name":"x"}' | langsmith api POST sessions --body @-
langsmith api GET sessions --include`,
echo '{"name":"x"}' | langsmith api POST sessions --body @-`,
Args: cobra.ArbitraryArgs,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 2 {
if len(args) == 0 {
return cmd.Help()
}

method := strings.ToUpper(args[0])
if !isHTTPMethod(method) {
return fmt.Errorf("unknown subcommand or HTTP method: %q\nRun 'langsmith api --help' for usage", args[0])
}

path := args[1]

c, err := cmdutil.GetClient(cmd)
if err != nil {
return err
}

w := cmd.OutOrStdout()
statusCode, err := runRequest(c, method, path, body, headers, include, w)
if err != nil {
return err
}
if statusCode >= 400 {
return fmt.Errorf("HTTP %d", statusCode)
}
return nil
return fmt.Errorf("unknown subcommand or HTTP method: %q\nRun 'langsmith api --help' for usage", args[0])
},
}

// Flags for request mode
cmd.Flags().StringVar(&body, "body", "", `Request body (JSON string, @file, or @- for stdin)`)
cmd.Flags().StringArrayVarP(&headers, "header", "H", nil, "Additional headers (Key:Value, repeatable)")
cmd.Flags().BoolVarP(&include, "include", "i", false, "Include HTTP response headers in output")

cmd.AddCommand(newLsCmd())
cmd.AddCommand(newInfoCmd())
for _, method := range []string{"GET", "POST", "PUT", "PATCH", "DELETE"} {
cmd.AddCommand(requestCommand(method).Cobra())
}

return cmd
}
56 changes: 53 additions & 3 deletions internal/cmd/api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"net/http/httptest"
"strings"
"testing"

"github.com/stretchr/testify/require"
)

func TestNewCmd_HasSubcommands(t *testing.T) {
Expand All @@ -21,6 +23,12 @@ func TestNewCmd_HasSubcommands(t *testing.T) {
if !names["info"] {
t.Error("missing subcommand 'info'")
}
if !names["GET"] {
t.Error("missing subcommand 'GET'")
}
if !names["POST"] {
t.Error("missing subcommand 'POST'")
}
}

func TestNewCmd_UseField(t *testing.T) {
Expand All @@ -32,10 +40,14 @@ func TestNewCmd_UseField(t *testing.T) {

func TestNewCmd_RequestFlags(t *testing.T) {
cmd := NewCmd()
for _, name := range []string{"body", "header", "include"} {
f := cmd.Flags().Lookup(name)
getCmd, _, err := cmd.Find([]string{"GET"})
if err != nil {
t.Fatalf("finding GET command: %v", err)
}
for _, name := range []string{"body", "header"} {
f := getCmd.Flags().Lookup(name)
if f == nil {
t.Errorf("flag --%s not found on api command", name)
t.Errorf("flag --%s not found on GET command", name)
}
}
}
Expand Down Expand Up @@ -71,6 +83,44 @@ func TestNewCmd_GETRequest(t *testing.T) {
}
}

func TestNewCmd_GETRequestJQ(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Errorf("expected GET, got %s", r.Method)
}
w.WriteHeader(200)
_, _ = w.Write([]byte(`{"ok":true,"name":"alpha"}`))
}))
defer ts.Close()

root := newTestRoot()
var out bytes.Buffer
root.SetOut(&out)
root.SetErr(&out)
root.SetArgs([]string{"api", "--api-key", "test-key", "--api-url", ts.URL, "GET", "sessions", "--jq", ".name"})

require.NoError(t, root.Execute())
require.Equal(t, "alpha", strings.TrimSpace(out.String()))
}

func TestNewCmd_GETRequestJQNonJSON(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
_, _ = w.Write([]byte(`plain text`))
}))
defer ts.Close()

root := newTestRoot()
var out bytes.Buffer
root.SetOut(&out)
root.SetErr(&out)
root.SetArgs([]string{"api", "--api-key", "test-key", "--api-url", ts.URL, "GET", "sessions", "--jq", ".name"})

err := root.Execute()
require.Error(t, err)
require.Contains(t, err.Error(), "JSON model is not available")
}

func TestNewCmd_POSTWithBody(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/openapi.json" {
Expand Down
106 changes: 39 additions & 67 deletions internal/cmd/api/info.go
Original file line number Diff line number Diff line change
@@ -1,85 +1,57 @@
package api

import (
"encoding/json"
"fmt"
"context"

"github.com/langchain-ai/langsmith-cli/internal/cache"
"github.com/langchain-ai/langsmith-cli/internal/cmdutil"
"github.com/langchain-ai/langsmith-cli/internal/structured"
"github.com/spf13/cobra"
)

func newInfoCmd() *cobra.Command {
var refresh bool
type infoInput struct {
Refresh bool
}

cmd := &cobra.Command{
Use: "info METHOD PATH",
Short: "Show details for a specific API endpoint",
Long: `Show full details for a specific API endpoint including parameters,
var infoCommand = structured.Command[*infoInput]{
Use: "info METHOD PATH",
Short: "Show details for a specific API endpoint",
Long: `Show full details for a specific API endpoint including parameters,
request body schema, and response schema.

Examples:
langsmith api info GET /api/v1/sessions
langsmith api info GET sessions
langsmith api info POST runs/query`,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
method := args[0]
path := args[1]

apiURL := cmdutil.ResolveAPIURL(cmd)
cacheDir := cache.DefaultDir()
format := cmdutil.ResolveFormat(cmd)

spec, err := loadSpec(apiURL, cacheDir, refresh)
if err != nil {
return err
}

detail, err := spec.LookupEndpoint(method, path)
if err != nil {
return err
}

w := cmd.OutOrStdout()

if format == "pretty" {
fmt.Fprintf(w, "%s %s\n", detail.Method, detail.Path)
fmt.Fprintf(w, "Tag: %s\n", detail.Tag)
fmt.Fprintf(w, "Summary: %s\n", detail.Summary)
if detail.Description != "" {
fmt.Fprintf(w, "Description: %s\n", detail.Description)
}
if len(detail.Parameters) > 0 {
fmt.Fprintf(w, "\nParameters:\n")
for _, p := range detail.Parameters {
req := ""
if p.Required {
req = " (required)"
}
fmt.Fprintf(w, " %-20s %-10s %s%s\n", p.Name, p.Type, p.Description, req)
}
}
if detail.RequestBody != nil {
fmt.Fprintf(w, "\nRequest Body:\n")
b, _ := json.MarshalIndent(detail.RequestBody, " ", " ")
fmt.Fprintf(w, " %s\n", b)
}
if detail.Response != nil {
fmt.Fprintf(w, "\nResponse Schema:\n")
b, _ := json.MarshalIndent(detail.Response, " ", " ")
fmt.Fprintf(w, " %s\n", b)
}
} else {
data, _ := json.MarshalIndent(detail, "", " ")
fmt.Fprintln(w, string(data))
}

return nil
},
}

cmd.Flags().BoolVar(&refresh, "refresh", false, "Force re-fetch of the OpenAPI spec")
Args: cobra.ExactArgs(2),
Input: func(cmd *cobra.Command) *infoInput {
in := &infoInput{}
cmd.Flags().BoolVar(&in.Refresh, "refresh", false, "Force re-fetch of the OpenAPI spec")
return in
},
Action: func(_ context.Context, cmd *cobra.Command, in *infoInput, args []string) (any, error) {
spec, err := loadSpec(cmdutil.ResolveAPIURL(cmd), cache.DefaultDir(), in.Refresh)
if err != nil {
return nil, err
}
return spec.LookupEndpoint(args[0], args[1])
},
Render: structured.Template(`{{.Method}} {{.Path}}
Tag: {{.Tag}}
Summary: {{.Summary}}{{if .Description}}
Description: {{.Description}}{{end}}{{if .Parameters}}

Parameters:
{{range .Parameters}} {{printf "%-20s %-10s %s" .Name .Type .Description}}{{if .Required}} (required){{end}}
{{end}}{{end}}{{if .RequestBody}}
Request Body:
{{jsonIndent .RequestBody " " " "}}
{{end}}{{if .Response}}
Response Schema:
{{jsonIndent .Response " " " "}}
{{end}}`),
}

return cmd
func newInfoCmd() *cobra.Command {
return infoCommand.Cobra()
}
Loading
Loading