Build a RESTful API With Go and Gin: A Practical Guide
To build a RESTful API with Go and Gin, create a Go module, add github.com/gin-gonic/gin, define a struct for each resource, register handlers on a router from gin.Default(), and start the server. Gin gives you routing, JSON binding and middleware, so most of your real work goes into validation, error responses and data access.
This guide is for developers and technical leads who want a small, working service first and a clear list of what to change before anyone else depends on it.
Key takeaways
- Gin is a Go web framework with radix-tree routing, middleware chains, route groups and built-in JSON validation.
- The official Go tutorial builds a small albums API with Gin; it is a good starting template.
- Use ShouldBindJSON with binding tags so your handler, not the framework, decides the 400 response.
- Version routes, protect shared state, add auth middleware and use a real database before production.
- Keep status codes and error bodies consistent so integrations can rely on them.
Why choose Go and Gin for an API?
Go compiles to a single binary, starts fast and handles concurrent requests well, which is why it shows up so often in internal services and integration APIs. Gin sits on top of Go's net/http rather than replacing it. Its documentation highlights radix-tree routing, middleware that runs as a chain (logger, authorization, gzip, then your handler), panic recovery, route groups and JSON validation.
You do have alternatives. Since Go 1.22, the standard library router supports HTTP methods and wildcards in patterns, which covers many small services with zero dependencies. Echo, Chi and Fiber are other popular options. Gin's case is maturity, good documentation and a large middleware ecosystem.
How do you set up the project?
mkdir items-api && cd items-api
go mod init example.com/items-api
go get github.com/gin-gonic/gin
Create main.go with a resource type, an in-memory store and handlers. The slice keeps the example short; it is fine for a local demo but not for real traffic, which the production section covers.
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type Item struct {
ID string `json:"id" binding:"required"`
Name string `json:"name" binding:"required"`
Price float64 `json:"price" binding:"gte=0"`
}
var items = []Item{{ID: "1", Name: "Badge reader", Price: 49.5}}
func listItems(c *gin.Context) {
c.JSON(http.StatusOK, items)
}
func getItem(c *gin.Context) {
id := c.Param("id")
for _, it := range items {
if it.ID == id {
c.JSON(http.StatusOK, it)
return
}
}
c.JSON(http.StatusNotFound, gin.H{"error": "item not found", "code": "ITEM_NOT_FOUND"})
}
func createItem(c *gin.Context) {
var in Item
if err := c.ShouldBindJSON(&in); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "code": "INVALID_BODY"})
return
}
items = append(items, in)
c.JSON(http.StatusCreated, in)
}
func setupRouter() *gin.Engine {
r := gin.Default()
v1 := r.Group("/api/v1")
v1.GET("/items", listItems)
v1.GET("/items/:id", getItem)
v1.POST("/items", createItem)
return r
}
func main() {
setupRouter().Run(":8080")
}
Run it with go run . and test with curl http://localhost:8080/api/v1/items. Two deliberate differences from the official tutorial: it uses c.BindJSON and c.IndentedJSON, while this example uses ShouldBindJSON and c.JSON. The tutorial itself notes you can swap IndentedJSON for JSON to send more compact output, and that indentation mainly helps while debugging.
Which REST conventions matter in practice?
| Operation | Method and path | Success code | Common errors |
|---|---|---|---|
| List | GET /items | 200 | 401, 403 |
| Read one | GET /items/:id | 200 | 404 |
| Create | POST /items | 201 | 400, 409 |
| Replace | PUT /items/:id | 200 | 400, 404 |
| Partial update | PATCH /items/:id | 200 | 400, 404 |
| Delete | DELETE /items/:id | 204 | 404 |
- Use plural nouns for resources and keep the verb in the HTTP method.
- Version from day one (/api/v1) so you can change contracts without breaking callers.
- Return one error shape everywhere, such as {"error": "message", "code": "ITEM_NOT_FOUND"}.
- Paginate list endpoints with limit plus a cursor or offset.
- Reject duplicate IDs on create with 409 rather than silently overwriting.
These rules pay off most when other systems integrate with you. Enterprise platforms each take their own approach, as our comparisons of Workday EIB, connectors and Studio and Infor's API and ION options show. A consistent contract is what makes your service easy to plug into tools like these.
What should you change before production?
Persistence
Replace the slice with a database using database/sql or a library of your choice. The in-memory slice is not safe for concurrent writes (Gin serves requests concurrently), loses everything on restart and cannot be shared across more than one instance.
Authentication and authorization
Add middleware that validates tokens, for example OAuth 2.0 bearer tokens from your identity provider, and attach it to a group with v1.Use(authMiddleware). Check permissions per action, not only at login. A read-only reporting client should not be able to POST.
Security and reliability checklist
- Serve over TLS, usually behind a load balancer or reverse proxy.
- Set read and write timeouts by running Gin as the Handler of an http.Server instead of calling r.Run.
- Limit request body size and validate every input, including path and query parameters.
- Call SetTrustedProxies with your proxy addresses so client IPs cannot be spoofed through headers.
- Run in release mode with gin.SetMode(gin.ReleaseMode) and use structured logging.
- Keep secrets in environment variables or a secrets manager, never in code.
Our guide on achieving data security in the cloud covers the hosting side of these controls.
Testing
Go's net/http/httptest package lets you call the router without opening a port. Because setupRouter returns the engine, a test can create a request, pass it to router.ServeHTTP with an httptest.NewRecorder(), and assert on the status code and JSON body. Cover the unhappy paths too: missing fields, negative prices and unknown IDs are where clients will find your bugs first.
If this API is one piece of a larger internal system, it helps to decide early who owns it long term. Our overview of enterprise custom software development covers the build, maintain and staffing questions that come after the first release.
Frequently Asked Questions
What is the difference between BindJSON and ShouldBindJSON in Gin?
BindJSON is a shortcut for MustBindWith, which aborts the request with HTTP 400 if binding fails, so you have little control over the response body. ShouldBindJSON is a shortcut for ShouldBindWith, which returns the error to your handler and lets you write the response. Most production APIs use the Should variants to keep one consistent error format.
Is Gin still needed now that Go's standard router supports methods?
Not always. Since Go 1.22, net/http patterns can include an HTTP method and wildcards, which is enough for many simple services. Gin still adds JSON binding with validation tags, route groups, panic recovery and a mature middleware ecosystem. Pick the standard library when you want minimal dependencies and Gin when those conveniences save your team real time.
How do I validate request fields in Gin?
Add binding tags to struct fields, such as binding:"required" or binding:"gte=0", then bind with ShouldBindJSON. Gin uses the go-playground/validator/v10 library to check them. For rules that span several fields or need a database lookup, such as a unique name, add explicit checks in your handler after binding succeeds and return the same error shape.
What to do next
- Work through the official Go and Gin tutorial, then compare it with the example above.
- Swap the slice for a database and add an httptest test for every route, including failures.
- Add auth middleware, SetTrustedProxies and server timeouts before the first external client connects.
- Write an OpenAPI description of your endpoints so the contract is documented before others build on it.
Last reviewed: October 2026.
Sources
- Tutorial: Developing a RESTful API with Go and Gin, The Go Programming Language
- Routing Enhancements for Go 1.22, The Go Blog
- Gin Web Framework, Gin
- gin package documentation, Go Packages

Comments
Post a Comment