Docs
Generating OpenAPI from Code
Go Gin

OpenAPI and Go with Optic

To begin using Optic with your API you first need an OpenAPI file describing your API. This YAML or JSON file can be written by hand or generated from your code. This document describes the recommended process for generating a new OpenAPI file for a Go project written with any framework or HTTP package.

For APIs written in Go, we recommend using Optic's capture proxy via the optic capture command.

To demonstrate, we've set up a simple example available here (opens in a new tab). Our example uses gin-gonic/gin (opens in a new tab) for the http framework but the content here is equally applicable to the standard library's net/http package or other frameworks. The steps below are written for our example repo but should be easy to adapt to your own.

From the openapi-generators/go-gin directory of the opticdev/examples repo, you can run a capture session which will generate an OpenAPI specification:

  1. go mod tidy to install the app's deps
  2. optic capture openapi.yml --update automatic to run a capture session

Take a look at ./openapi.yml that has been generated. You'll see we've documented a few requests!

From here you can edit your openapi.yml file (maybe to set the title field), run more capture sessions, etc. Optic will update the OpenAPI file as new requests are captured, adding or modifying endpoints as necessary.

💡

Don't forget to check your openapi.yml file into source control. Optic can use it to verify your code matches your OpenAPI spec and prevent breaking changes!

What's next

Automate your OpenAPI generation and test your API specifications by setting up Optic in CI.