@@ -37,6 +37,7 @@ type ApiOptions struct {
3737 MagicFields []string
3838 RawFields []string
3939 RequestHeaders []string
40+ Previews []string
4041 ShowResponseHeaders bool
4142 Paginate bool
4243 Silent bool
@@ -106,7 +107,10 @@ func NewCmdApi(f *cmdutil.Factory, runF func(*ApiOptions) error) *cobra.Command
106107 $ gh api -X GET search/issues -f q='repo:cli/cli is:open remote'
107108
108109 # set a custom HTTP header
109- $ gh api -H 'Accept: application/vnd.github.XYZ-preview+json' ...
110+ $ gh api -H 'Accept: application/vnd.github.v3.raw+json' ...
111+
112+ # opt into GitHub API previews
113+ $ gh api --preview baptiste,nebula ...
110114
111115 # list releases with GraphQL
112116 $ gh api graphql -F owner=':owner' -F name=':repo' -f query='
@@ -175,6 +179,7 @@ func NewCmdApi(f *cmdutil.Factory, runF func(*ApiOptions) error) *cobra.Command
175179 cmd .Flags ().StringArrayVarP (& opts .MagicFields , "field" , "F" , nil , "Add a typed parameter in `key=value` format" )
176180 cmd .Flags ().StringArrayVarP (& opts .RawFields , "raw-field" , "f" , nil , "Add a string parameter in `key=value` format" )
177181 cmd .Flags ().StringArrayVarP (& opts .RequestHeaders , "header" , "H" , nil , "Add a HTTP request header in `key:value` format" )
182+ cmd .Flags ().StringSliceVarP (& opts .Previews , "preview" , "p" , nil , "Opt into GitHub API previews" )
178183 cmd .Flags ().BoolVarP (& opts .ShowResponseHeaders , "include" , "i" , false , "Include HTTP response headers in the output" )
179184 cmd .Flags ().BoolVar (& opts .Paginate , "paginate" , false , "Make additional HTTP requests to fetch all pages of results" )
180185 cmd .Flags ().StringVar (& opts .RequestInputFile , "input" , "" , "The `file` to use as body for the HTTP request" )
@@ -219,6 +224,10 @@ func apiRun(opts *ApiOptions) error {
219224 }
220225 }
221226
227+ if len (opts .Previews ) > 0 {
228+ requestHeaders = append (requestHeaders , "Accept: " + previewNamesToMIMETypes (opts .Previews ))
229+ }
230+
222231 httpClient , err := opts .HttpClient ()
223232 if err != nil {
224233 return err
@@ -513,3 +522,11 @@ func parseErrorResponse(r io.Reader, statusCode int) (io.Reader, string, error)
513522
514523 return bodyCopy , "" , nil
515524}
525+
526+ func previewNamesToMIMETypes (names []string ) string {
527+ types := []string {fmt .Sprintf ("application/vnd.github.%s-preview+json" , names [0 ])}
528+ for _ , p := range names [1 :] {
529+ types = append (types , fmt .Sprintf ("application/vnd.github.%s-preview" , p ))
530+ }
531+ return strings .Join (types , ", " )
532+ }
0 commit comments