When developing web applications in Go, especially when building RESTful APIs, documentation and strict adherence to a specification play a crucial role. For these purposes, the OpenAPI (Swagger) format is often used. However, manually maintaining both code and specification can lead to inconsistencies and errors.
The oapi-codegen tool helps automate the creation of part of the code based on an OpenAPI specification.
🔗 GitHub Repository: oapi-codegen
What is oapi-codegen?
oapi-codegen is a powerful open-source code generator designed for Go projects. It accepts an OpenAPI 3.0 specification in YAML or JSON format and generates ready-to-use Go code that implements server interfaces, client libraries, data models, routes, and other API components.
This significantly reduces the amount of boilerplate code required to build HTTP servers and clients, while ensuring consistency between the specification and the actual implementation.
Key Features
✅ Data Model Generation: Create Go structs based on schemas defined in the OpenAPI spec.
✅ Server Interface Creation: Automatically generate handler methods for request processing.
✅ Client SDK Support: Generate client packages for interacting with the API.
✅ Input Validation: Validate query parameters, headers, request bodies, etc., according to the spec.
✅ Framework Integration: Works with popular HTTP routers and frameworks like Chi, Echo, Gin, Fiber, Gorilla Mux, Iris, and even standard net/http
.
✅ Extensibility: Supports custom templates and imports for tailored generation.
Installation
You can install the tool using the standard Go command:
go install github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@latest
Example Usage
Suppose you have a file openapi.yaml
that describes a simple user management API:
openapi: 3.0.3
info:
title: User API
version: 1.0.0
paths:
/users/{id}:
get:
summary: Get user by ID
operationId: getV1GetUserByID
parameters:
- name: id
in: path
required: true
schema:
type: string
example: "123"
responses:
'200':
description: User response
content:
application/json:
schema:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
required:
- id
- name
properties:
id:
type: integer
name:
type: string
Create a configuration file config.yaml
:
package: api
generate:
chi-server: true
models: true
output: server_interface.gen.go
Run the generator:
oapi-codegen --config config.yaml openapi.yaml
The generated file will contain:
- Data structures (
User
) - A
ServerInterface
interface with methods for each endpoint - Route setup and middleware implementation for the selected framework (Chi in this case)
Now you can implement your handler logic without worrying about routing or parsing requests manually.
Framework Integration
oapi-codegen supports integration with many popular HTTP libraries:
Each framework has its own set of generated helpers and example implementations.
Why Use oapi-codegen?
✅ Specification-Code Consistency
Generating code from an OpenAPI spec ensures that your API always matches the documentation, reducing the risk of mismatches and bugs.
✅ Time Savings
You save time writing routes, validation logic, models, and other repetitive code elements.
✅ Scalable for Large APIs
Ideal for large-scale APIs where maintaining clean, structured code and making frequent changes is essential.
✅ Design-First API Development
oapi-codegen fits perfectly into a Design-First API workflow, where the specification is written before development begins. This makes the API design process consistent and aligned with the original plan.
Conclusion
oapi-codegen is a powerful tool for automating code generation from OpenAPI specifications in Go. It allows developers to focus on business logic rather than setting up routes and validations manually. If you're working on an API in a team or striving for clean, well-documented code, this utility is an excellent choice.
📣 Follow me and read my content on other platforms:
Check out this and other articles on my pages:
🔗 LinkedIn
📚 Medium
📘 Facebook
✈️ Telegram
🐦 X
Oh, almost forgot — my personal website.
🔔 Follow me not to miss new articles and guides on hot topics!