---
# System prepended metadata

title: CUE to OpenAPI

---

# CUE to OpenAPI

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"

	"cuelang.org/go/cue"
	"cuelang.org/go/encoding/openapi"
)

func genOpenAPI(inst *cue.Instance) ([]byte, error) {
	b, err := openapi.Gen(inst, nil)
	if err != nil {
		return nil, err
	}

	var out = &bytes.Buffer{}
	_ = json.Indent(out, b, "", "   ")
	return out.Bytes(), nil
}

func main() {
	r := &cue.Runtime{}
	inst, err := r.Compile("./app.cue", nil)
	if err != nil {
		panic(err)
	}
	b, err := genOpenAPI(inst)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(b))
}

```

CUE file:
```yaml
output: {
	apiVersion: "apps/v1"
	kind:       "Deployment"
	spec: {
		selector: matchLabels: {
			"app.oam.dev/component": context.name
		}

		template: {
			metadata: labels: {
				"app.oam.dev/component": context.name
			}

			spec: {
				containers: [{
					name:  context.name
					image: #parameter.image

					if #parameter["cmd"] != _|_ {
						command: #parameter.cmd
					}
				}]
			}
		}

		selector:
			matchLabels:
				"app.oam.dev/component": context.name
	}
}

context: {
  name: string
}

#parameter: {
	// +usage=Which image would you like to use for your service
	// +short=i
	image: string
	// +usage=Commands to run in the container
	cmd?: [...string]
}

```


Output:
```json
{
   "openapi": "3.0.0",
   "info": {
      "title": "Generated by cue.",
      "version": "no version"
   },
   "paths": {},
   "components": {
      "schemas": {
         "parameter": {
            "type": "object",
            "required": [
               "image"
            ],
            "properties": {
               "cmd": {
                  "description": "+usage=Commands to run in the container",
                  "type": "array",
                  "items": {
                     "type": "string"
                  }
               },
               "image": {
                  "description": "+usage=Which image would you like to use for your service\n+short=i",
                  "type": "string"
               }
            }
         }
      }
   }
}
```