Building API Endpoints
Create dynamic JSON API endpoints using Go logic inside the api/ directory.
API Routes
Barry supports building JSON-based API endpoints using a dedicated `api/` directory. These routes let you respond to HTTP requests with data instead of HTML. Each route can use Go code to access request data, handle parameters, and return structured JSON.What Are API Routes?
API routes let you expose server-side functionality via HTTP endpoints that return JSON responses. These are located inside the api/
directory and work just like your regular routes/
files — but instead of rendering HTML, they respond with data.
Each endpoint is backed by an index.go
or index.server.go
file that exports a HandleAPI
function.
Basic Example
// api/ping/index.go
package ping
import "net/http"
func HandleAPI(r *http.Request, params map[string]string) (interface{}, error) {
return map[string]interface{}{
"pong": true,
}, nil
}
Requesting /api/ping
will return:
{"pong": true}
File-Based Routing
Like normal routes, API endpoints use folders to define paths and parameters:
/api
├── ping/
│ └── index.go → /api/ping
├── user/
│ └── _id/
│ └── index.go → /api/user/123
└── hello/
└── _name/
└── index.server.go → /api/hello/barry
Use _param
folders to capture dynamic segments. These will be available in the params
map passed to HandleAPI
.