logo Buffalo slack logo
API Applications
Guides

API Applications#

Applications that only serve API end-points, typically JSON, are very different from those that serve HTML, JavaScript, and CSS. In this guide, you’ll learn how to build an API-only app, using Buffalo.

Creating a New API Application#

When creating a new Buffalo application using the buffalo new command, the optional --api flag will generate an application that is better suited to serving APIs than a stock Buffalo application.

$ buffalo new coke --api

Slimmed Project Layout#

Applications generated with the --api flag don’t contain any front systems. This means there is no templating, stylesheets, etc…

API
Default
$ buffalo new coke --api
├── actions/
│	├── app.go
│	└── render.go
├── cmd/
│	└── app/
│		└── main.go
├── config/
├── fixtures/
├── grifts/
├── locales/
├── models/
├── .buffalo.dev.yml
├── .codeclimate.yml
├── .docketignore
├── .env
├── .gitignore
├── database.yml
├── Dockerfile
├── go.mod
├── go.sum
├── inflections.json
├── README.md

Tuned actions/app.go actions/render.go Files#

API applications have actions/app.go and actions/render.go files that are a good starting point for API applications.

API
Default
$ buffalo new coke --api
func App() *buffalo.App {
	if app == nil {
		app = buffalo.New(buffalo.Options{
			Env:          ENV,
			SessionStore: sessions.Null{},
			PreWares: []buffalo.PreWare{
				cors.Default().Handler,
			},
			SessionName: "_coke_session",
		})
		app.Use(forceSSL())
		app.Use(paramlogger.ParameterLogger)
		app.Use(contenttype.Set("application/json"))

		app.Use(popmw.Transaction(models.DB))
		app.GET("/", HomeHandler)
	}

	return app
}
func init() {
	r = render.New(render.Options{
		DefaultContentType: "application/json",
	})
}