Rapid Prototyping of Design-First APIs in Go
Tags: api, go, designfirst
Published: 2023-08-20 14:19:43

API engineering is constantly evolving and using the right tools is the key to building Design-First APIs faster.

This article will explore the following,

1. API design-first approach and benefits
2. Generate API Server code from OpenAPI Specs
3. Run API Server with Gin Web framework


### API design-first approach

The “API design-first” approach emphasizes the importance of planning and designing the API’s contract before delving into implementation details. This strategy provides several benefits:

1. Clear Contract: It establishes a clear contract between the API provider and the consumers. This contract defines how the API will behave, the endpoints it will expose, the data formats it will accept and return, and other necessary details.

2. Stakeholder Feedback: By designing the API first, we can gather feedback from various stakeholders (like front-end developers, other back-end developers, or even potential users) early in the process. This can lead to an API that’s more intuitive and user-friendly.
 
3. Consistency: A design-first approach often results in a more consistent API design.

4. Better Documentation: Tools like Swagger/Stoplight Studio can generate documentation from the design itself. This ensures that the documentation is in sync with the API’s contract and is always up-to-date.
 
5. Versioning and Future Expansion: When we plan API in advance, it’s easier to think about how it might need to evolve in the future. we can design it in such a way that it’s easier to introduce non-breaking changes or new versions down the line.

We use Stoplight Studio https://stoplight.io/ to design APIs, one of the advantages of Stoplight Studio is the Visual interface, it generates OpenAPI specs from the design and supports OpenAPI v3, allowing users to create, edit, and view API designs using the OpenAPI standard.

Example: API endpoints for Users

```
- POST /users
- GET /users/{userId}
- PATCH /users/{userId}
```

Please refer to the OpenAPI specs https://github.com/thirukkumaran/design-first-apis-with-go/blob/main/apis/users.yaml

### Generate API Server code

Once the OpenAPI specs are ready, we could generate an API Server boilerplate using the Go package “**github.com/deepmap/oapi-codegen**”.

oapi-codegen automates the process of generating server boilerplate code, ensuring consistency and saving developer time.

Generated server code will have the OpenAPI models converted to Go structs and endpoints are registered with handler functions in an interface object.

To generate Gin server code for users.yaml,

```
go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen — package=Users — generate types,gin -o users.gen.go users.yaml
```

Please refer generated server code https://github.com/thirukkumaran/design-first-apis-with-go/blob/main/users/users.gen.go

And we need to implement the required business logic in the handler functions.

Please refer https://github.com/thirukkumaran/design-first-apis-with-go/blob/main/users/users.go

### Run API Server

We are ready with the API endpoints and implementation, time to put them together with the HTTP router.

We use Gin web framework https://gin-gonic.com for the routing, Gin provides a balance between performance, ease of use and extensibility making it a preferred choice for building and running web applications in Go.

Some of the advantages of Gin,

1. Performance: One of Gin’s primary selling points is its speed. It’s among the fastest web frameworks for Go, largely due to its ability to run without reflection. This makes it highly efficient, especially for high-performance applications.

2. Robust Middleware Support: Gin has a vast ecosystem of middleware, and we can also create custom middleware to suit specific needs.

3. JSON Validation: Gin offers functionalities for JSON request validation using a structure and providing detailed error messages, which simplifies the handling of input validation.

4. Routing: Gin provides a high-performance, flexible routing mechanism. The router is optimized for speed, and developers can define routes using HTTP verbs, path parameters, wildcards, etc. 

5. Data Binding: Gin can bind incoming JSON, XML, form, or query data into Go structures, which aids in processing request data. 

6. Context: Gin offers a context object passed to every request, making it easier to share data between middleware and handlers, manage flow, or retrieve request and response information.

Create gin router, register the handlers and start the server,

```
// Create a gin router
router := gin.Default()

// Server implementation
server := Users.ServerImplementation{}

// Register the handlers
Users.RegisterHandlers(router, server)

// Start the server
log.Println(“Server started on port 8080”)
router.Run()
```

Please refer https://github.com/thirukkumaran/design-first-apis-with-go/blob/main/main.go

### Test API server

We are all set, time to test the API endpoints

Clone git repo and test API endpoint,


```
git clone https://github.com/thirukkumaran/design-first-apis-with-go

cd design-first-apis-with-go

go run main.go

curl -v http://localhost:8080/users/1
```