Building a REST API with Grails
Site Admin
· 11 Sep 2026
· 8 views
REST API Design
Grails excels at building RESTful APIs. With the rest-api profile and built-in URL mappings, you can create a complete REST API in minutes.
Domain Class Setup
class Book {
String title
String author
int pages
static constraints = {
title blank: false
author blank: false
pages min: 1
}
static mapping = {
table 'books'
}
}
REST Controller
class BookController extends RestfulController<Book> {
static responseFormats = ['json', 'xml']
BookController() {
super(Book)
}
@Override
def index() {
respond Book.list(params)
}
@Override
def show() {
respond Book.get(params.id)
}
@Override
def save() {
def book = new Book(request.JSON)
if (!book.save()) {
respond book.errors, view: 'create'
return
}
respond book, status: 201
}
}
URL Mappings
class UrlMappings {
static mappings = {
"/api/books"(resources: "book")
"/"(view: "/index")
"500"(view: '/error')
}
}
Testing the API
# Create a book
curl -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"Groovy","author":"Smith","pages":300}'
# List all books
curl http://localhost:8080/api/books
Key Points
- Use the
rest-apiprofile for REST-only projects. RestfulControllerprovides CRUD operations automatically.respondhandles content negotiation (JSON/XML).resourcesin URL mappings creates RESTful routes.- Request JSON binding works automatically.