SlideShare a Scribd company logo
1 of 30
Page 1
Grails : REST and Web Service
@somkiat
Page 2
REST
• Not really a Technology
• More an Architecture
• Simple
• Communication via plain text, xml, json
• Combine with HTTP method
• Resource-Oriented
Page 3
Mapping HTTP Method
HTTP Method Action
GET Read ( R )
PUT Update ( U )
POST Create ( C )
DELETE Delete ( D )
Page 4
Mapping REST in Grails
• Example
static mappings = {
"/product/$id?"( resource:"product" )
}
HTTP Method Action
GET show
PUT update
POST save
DELETE delete
Page 5
Mapping REST in Grails
• Example
static mappings = {
"/product/$id"(controller:"product",
parseRequest:true ){
action = [
GET:"show",
PUT:"update",
DELETE:"delete",
POST:"save“
]
}
}
Automatic XML
or JSON
Marshaling
Page 6
Create REST Controller
• grails create-controller product
class ProductController {
def show = {
render “show from rest”
}
def save = {
render “save from rest”
}
def update = {
render “update from rest”
}
def delete = {
render “delete from rest”
}
}
Page 7
REST Client
• Groovy HTTPBuilder
import groovyx.net.http.*
import static groovyx.net.http.ContentType.HTML
def url = "http://localhost:8080/example1/product/1"
def http = new HTTPBuilder( url )
http.request(Method.GET, HTML) {
response.success = {resp, html ->
println html
}
}
Page 8
REST Client
• GSP Form
<g:form controller="product" method="PUT">
<g:submitButton name="Test" />
</g:form>
Page 9
REST Controller :: Switch on HTTP method
• grails create-controller product
class ProductController {
def index = {
switch(request.method){
case "POST": render "Create"
break
case "GET": render "Retrieve"
break
case "PUT": render "Update"
break
case "DELETE": render "Delete"
break
}
}
}
Page 10
Communication via XML
• grails create-controller product
import grails.converters.*
class ProductController {
def list = {
render Product.list() as XML
}
def show = {
render Product.get( params.id ) as XML
}
}
Page 11
Domain class :: Product
• grails create-domain-class product
class Product {
String name
Double price
String toString() {
return "id=${id}|name=${name}|price=${price}"
}
}
Page 12
Insert data for Test
• File /conf/BootStap.groovy
class BootStrap {
def init = { servletContext ->
if( !Product.count() ) {
new Product(
name:"Product 1",
price:12.9 ).save( failOnError:true )
new Product(
name:"Product 2",
price:20.5 ).save( failOnError:true )
}
}
def destroy = { }
}
Page 13
XML Result
<list>
<product id="1">
<name>Product 1</name>
<price>12.9</price>
</product>
<product id="2">
<name>Product 2</name>
<price>20.5</price>
</product>
</list>
Page 14
Custom XML
<products>
<product id="1">
<product-name>product 1</name>
<product-price>12.9</price>
</product>
<product id="2">
<product-name>product 2</name>
<product-price>20.5</price>
</product>
</products>
Page 15
Communication via XML
def listXmlCustom = {
def productList = Product.list()
render( contentType:"text/xml" ) {
products{
for( temp in productList ) {
product( id:temp.id ){
"product-name"(temp.name)
"product-price"(temp.price)
}
}
}
}
}
Using Groovy
Markup Builder
http://groovy.codehaus.org/Creating+XML+using+Groovy's+MarkupBuilder
Page 16
Communication via JSON
• grails create-controller product
import grails.converters.*
class ProductController {
def list = {
render Product.list() as JSON
}
def show = {
render Product.get( params.id ) as JSON
}
}
Page 17
JSON Result
[
{ "class":"example1.Product",
"id":1,
"name":"Product 1",
"price":12.9
},
{
"class":"example1.Product",
"id":2,
"name":"Product 2",
"price":20.5
}
]
Page 18
Content Negotiation
• Allow to return different format based on the request.
• All format in file /conf/Config.groovy
grails.mime.types =
[
html: ['text/html','application/xhtml+xml'],
xml: ['text/xml', 'application/xml'],
text: 'text/plain',
js: 'text/javascript',
rss: 'application/rss+xml',
atom: 'application/atom+xml',
css: 'text/css',
csv: 'text/csv',
all: '*/*',
json: ['application/json','text/json'],
form: 'application/x-www-form-urlencoded',
multipartForm: 'multipart/form-data'
]
Page 19
Using withFormat
def list = {
if(!params.max) params.max = 10
def productList = Product.list( params )
withFormat {
html { render productList }
xml { render productList as XML }
json { render productList as JSON }
}
}
Default format
html
Page 20
How to call ?
• Default
• http://localhost:8080/example/product/list
• URL Extension
• http://localhost:8080/example/product/list.html
• Format request parameter
• http://localhost:8080/example/product/list?format=html
Page 21
URL Extension
• Disable/Enable in file /conf/Config.groovy
grails.mime.file.extensions = true // Enable ( Default )
grails.mime.file.extensions = false // Disable
Page 22
Define Format parameter in URL Mapping
• Set default format = xml
"/product2/list2" (controller:"product2", action:"list2") {
format = "xml"
}
Page 23
How to call ?
• http://localhost:8080/example/product/list.xml
• http://localhost:8080/example/product/list?format=xml
Page 24
RSS and Atom
• Using Feed plug-in
•http://docs.codehaus.org/display/GRAILS/Feeds+Plugin
• ROME Library
•https://rome.dev.java.net/
Page 25
RSS
• Install plug-in > grails install-plugin feeds
withFormat {
rss {
render(feedType:"rss", feedVersion:"2.0") {
title = "My test feed"
link = "http://www.grails66.com/feed"
description = “Grails 66 feed"
productList.each() { product ->
entry(product.name) {
link ="http://grails66.com//${product.id}"
product.name
}
}
}
}
}
Page 26
Result
• http://localhost:8080/example/product/list.rss
• http://localhost:8080/example/product/list?format=rss
Page 27
Demo :: REST with DOJO
grails create-app example2
cd example2
grails install-plugin dojo
grails install-dojo
grails create-domain-class product
grails create-controller product
Page 28
Web Service
• Web API
• Access via HTTP
• Executed on remote system
• SOA ( Service-Oriented Architecture )
Page 29
Grails Plug-in
• XFire
• http://xfire.codehaus.org/
• CFX
• http://grails.org/plugin/cxf/
• Axis2
• http://grails.org/plugin/axis2
• Metro
• https://jax-ws-commons.dev.java.net/grails/
Page 30
Thank you

More Related Content

What's hot

단일 페이지 인터페이스 웹/앱 개발
단일 페이지 인터페이스 웹/앱 개발단일 페이지 인터페이스 웹/앱 개발
단일 페이지 인터페이스 웹/앱 개발동수 장
 
Knockout.js Overview
Knockout.js OverviewKnockout.js Overview
Knockout.js Overview민태 김
 
MongoDB World 2016 : Advanced Aggregation
MongoDB World 2016 : Advanced AggregationMongoDB World 2016 : Advanced Aggregation
MongoDB World 2016 : Advanced AggregationJoe Drumgoole
 
Synapse india reviews sharing chapter 23 – asp.net-part2
Synapse india reviews sharing  chapter 23 – asp.net-part2Synapse india reviews sharing  chapter 23 – asp.net-part2
Synapse india reviews sharing chapter 23 – asp.net-part2Synapseindiappsdevelopment
 
JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerBruce McPherson
 
Aggregation Framework in MongoDB Overview Part-1
Aggregation Framework in MongoDB Overview Part-1Aggregation Framework in MongoDB Overview Part-1
Aggregation Framework in MongoDB Overview Part-1Anuj Jain
 
The Ring programming language version 1.2 book - Part 31 of 84
The Ring programming language version 1.2 book - Part 31 of 84The Ring programming language version 1.2 book - Part 31 of 84
The Ring programming language version 1.2 book - Part 31 of 84Mahmoud Samir Fayed
 
Data Management 2: Conquering Data Proliferation
Data Management 2: Conquering Data ProliferationData Management 2: Conquering Data Proliferation
Data Management 2: Conquering Data ProliferationMongoDB
 
MongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your Data
MongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your DataMongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your Data
MongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your DataMongoDB
 
Работа с документами в JavaScript
Работа с документами в JavaScriptРабота с документами в JavaScript
Работа с документами в JavaScriptДмитрий Радыно
 
How to separate frontend from a highload python project with no problems - Py...
How to separate frontend from a highload python project with no problems - Py...How to separate frontend from a highload python project with no problems - Py...
How to separate frontend from a highload python project with no problems - Py...Oleksandr Tarasenko
 
Introducing Asp.Net Ajax 4.0 Preview
Introducing Asp.Net Ajax 4.0 PreviewIntroducing Asp.Net Ajax 4.0 Preview
Introducing Asp.Net Ajax 4.0 PreviewCat Chen
 

What's hot (20)

Grails Views
Grails ViewsGrails Views
Grails Views
 
Synapse india dotnet development web approch
Synapse india dotnet development web approchSynapse india dotnet development web approch
Synapse india dotnet development web approch
 
Smoke testing with Go
Smoke testing with GoSmoke testing with Go
Smoke testing with Go
 
jQuery Beginner
jQuery BeginnerjQuery Beginner
jQuery Beginner
 
단일 페이지 인터페이스 웹/앱 개발
단일 페이지 인터페이스 웹/앱 개발단일 페이지 인터페이스 웹/앱 개발
단일 페이지 인터페이스 웹/앱 개발
 
Knockout.js Overview
Knockout.js OverviewKnockout.js Overview
Knockout.js Overview
 
MongoDB World 2016 : Advanced Aggregation
MongoDB World 2016 : Advanced AggregationMongoDB World 2016 : Advanced Aggregation
MongoDB World 2016 : Advanced Aggregation
 
Synapse india reviews sharing chapter 23 – asp.net-part2
Synapse india reviews sharing  chapter 23 – asp.net-part2Synapse india reviews sharing  chapter 23 – asp.net-part2
Synapse india reviews sharing chapter 23 – asp.net-part2
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Goa tutorial
Goa tutorialGoa tutorial
Goa tutorial
 
JavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primerJavaScript client API for Google Apps Script API primer
JavaScript client API for Google Apps Script API primer
 
Aggregation Framework in MongoDB Overview Part-1
Aggregation Framework in MongoDB Overview Part-1Aggregation Framework in MongoDB Overview Part-1
Aggregation Framework in MongoDB Overview Part-1
 
The Ring programming language version 1.2 book - Part 31 of 84
The Ring programming language version 1.2 book - Part 31 of 84The Ring programming language version 1.2 book - Part 31 of 84
The Ring programming language version 1.2 book - Part 31 of 84
 
Data Management 2: Conquering Data Proliferation
Data Management 2: Conquering Data ProliferationData Management 2: Conquering Data Proliferation
Data Management 2: Conquering Data Proliferation
 
Git as NoSQL
Git as NoSQLGit as NoSQL
Git as NoSQL
 
MongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your Data
MongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your DataMongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your Data
MongoDB .local Toronto 2019: Using Change Streams to Keep Up with Your Data
 
Работа с документами в JavaScript
Работа с документами в JavaScriptРабота с документами в JavaScript
Работа с документами в JavaScript
 
How to separate frontend from a highload python project with no problems - Py...
How to separate frontend from a highload python project with no problems - Py...How to separate frontend from a highload python project with no problems - Py...
How to separate frontend from a highload python project with no problems - Py...
 
Introducing Asp.Net Ajax 4.0 Preview
Introducing Asp.Net Ajax 4.0 PreviewIntroducing Asp.Net Ajax 4.0 Preview
Introducing Asp.Net Ajax 4.0 Preview
 
React 101
React 101React 101
React 101
 

Viewers also liked

EDUCAUSE Midwest - Presentation - Koch - Henshaw
EDUCAUSE Midwest - Presentation - Koch - HenshawEDUCAUSE Midwest - Presentation - Koch - Henshaw
EDUCAUSE Midwest - Presentation - Koch - HenshawBruce Gilbert
 
Trefmoment 'Vluchtelingen en migratie' (Vluchtelingenwerk Vlaanderen en Orbit...
Trefmoment 'Vluchtelingen en migratie' (Vluchtelingenwerk Vlaanderen en Orbit...Trefmoment 'Vluchtelingen en migratie' (Vluchtelingenwerk Vlaanderen en Orbit...
Trefmoment 'Vluchtelingen en migratie' (Vluchtelingenwerk Vlaanderen en Orbit...Socius - steunpunt sociaal-cultureel werk
 
Deans-textbook-alternatives
Deans-textbook-alternativesDeans-textbook-alternatives
Deans-textbook-alternativesBruce Gilbert
 
Introduction to Continuous Integration
Introduction to Continuous IntegrationIntroduction to Continuous Integration
Introduction to Continuous IntegrationSomkiat Puisungnoen
 
Новые стандарты по делопроизводству (международная практика).
Новые стандарты по делопроизводству (международная практика).Новые стандарты по делопроизводству (международная практика).
Новые стандарты по делопроизводству (международная практика).Natasha Khramtsovsky
 
Системы автоматического распознавания регистрационных номеров автомашин (анал...
Системы автоматического распознавания регистрационных номеров автомашин (анал...Системы автоматического распознавания регистрационных номеров автомашин (анал...
Системы автоматического распознавания регистрационных номеров автомашин (анал...Natasha Khramtsovsky
 
Pptproject flipbook nmm
Pptproject flipbook nmmPptproject flipbook nmm
Pptproject flipbook nmmjaspang
 
Tears Of A Woman
Tears Of A WomanTears Of A Woman
Tears Of A Womanlycuong
 
Asian Defense Spending 2000-2011
Asian Defense Spending 2000-2011Asian Defense Spending 2000-2011
Asian Defense Spending 2000-2011teknoport
 
Проблемы законодательного регулирования управления документацией и информацией
Проблемы законодательного регулирования управления документацией и информациейПроблемы законодательного регулирования управления документацией и информацией
Проблемы законодательного регулирования управления документацией и информациейNatasha Khramtsovsky
 

Viewers also liked (20)

EDUCAUSE Midwest - Presentation - Koch - Henshaw
EDUCAUSE Midwest - Presentation - Koch - HenshawEDUCAUSE Midwest - Presentation - Koch - Henshaw
EDUCAUSE Midwest - Presentation - Koch - Henshaw
 
Trefmoment 'Vluchtelingen en migratie' (Vluchtelingenwerk Vlaanderen en Orbit...
Trefmoment 'Vluchtelingen en migratie' (Vluchtelingenwerk Vlaanderen en Orbit...Trefmoment 'Vluchtelingen en migratie' (Vluchtelingenwerk Vlaanderen en Orbit...
Trefmoment 'Vluchtelingen en migratie' (Vluchtelingenwerk Vlaanderen en Orbit...
 
Deans-textbook-alternatives
Deans-textbook-alternativesDeans-textbook-alternatives
Deans-textbook-alternatives
 
Ashley
AshleyAshley
Ashley
 
You Tube Optimisation
You Tube OptimisationYou Tube Optimisation
You Tube Optimisation
 
Introduction to Continuous Integration
Introduction to Continuous IntegrationIntroduction to Continuous Integration
Introduction to Continuous Integration
 
Новые стандарты по делопроизводству (международная практика).
Новые стандарты по делопроизводству (международная практика).Новые стандарты по делопроизводству (международная практика).
Новые стандарты по делопроизводству (международная практика).
 
Системы автоматического распознавания регистрационных номеров автомашин (анал...
Системы автоматического распознавания регистрационных номеров автомашин (анал...Системы автоматического распознавания регистрационных номеров автомашин (анал...
Системы автоматического распознавания регистрационных номеров автомашин (анал...
 
Introduction to Git and Github
Introduction to Git and GithubIntroduction to Git and Github
Introduction to Git and Github
 
CiviCRM bij Cavaria
CiviCRM bij CavariaCiviCRM bij Cavaria
CiviCRM bij Cavaria
 
Pptproject flipbook nmm
Pptproject flipbook nmmPptproject flipbook nmm
Pptproject flipbook nmm
 
Gruppo Sicani: SportHello
Gruppo Sicani: SportHelloGruppo Sicani: SportHello
Gruppo Sicani: SportHello
 
Jack Johnson - The Boxer
Jack Johnson - The BoxerJack Johnson - The Boxer
Jack Johnson - The Boxer
 
Tears Of A Woman
Tears Of A WomanTears Of A Woman
Tears Of A Woman
 
Een e-leeromgeving opzetten in je organiatie
Een e-leeromgeving opzetten in je organiatieEen e-leeromgeving opzetten in je organiatie
Een e-leeromgeving opzetten in je organiatie
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Javier
JavierJavier
Javier
 
Asian Defense Spending 2000-2011
Asian Defense Spending 2000-2011Asian Defense Spending 2000-2011
Asian Defense Spending 2000-2011
 
Проблемы законодательного регулирования управления документацией и информацией
Проблемы законодательного регулирования управления документацией и информациейПроблемы законодательного регулирования управления документацией и информацией
Проблемы законодательного регулирования управления документацией и информацией
 
Camera
CameraCamera
Camera
 

Similar to Grails66 web service

The Ring programming language version 1.5.3 book - Part 53 of 184
The Ring programming language version 1.5.3 book - Part 53 of 184The Ring programming language version 1.5.3 book - Part 53 of 184
The Ring programming language version 1.5.3 book - Part 53 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 43 of 184
The Ring programming language version 1.5.3 book - Part 43 of 184The Ring programming language version 1.5.3 book - Part 43 of 184
The Ring programming language version 1.5.3 book - Part 43 of 184Mahmoud Samir Fayed
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
The Ring programming language version 1.10 book - Part 53 of 212
The Ring programming language version 1.10 book - Part 53 of 212The Ring programming language version 1.10 book - Part 53 of 212
The Ring programming language version 1.10 book - Part 53 of 212Mahmoud Samir Fayed
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
Agile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansAgile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansCarol McDonald
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3masahiroookubo
 
Grails EE
Grails EEGrails EE
Grails EEGR8Conf
 
MongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB
 
After max+phonegap
After max+phonegapAfter max+phonegap
After max+phonegapyangdj
 
混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaver混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaveryangdj
 
Google App Engine with Gaelyk
Google App Engine with GaelykGoogle App Engine with Gaelyk
Google App Engine with GaelykChoong Ping Teo
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Introduction to Grails Framework
Introduction to Grails FrameworkIntroduction to Grails Framework
Introduction to Grails FrameworkPT.JUG
 
Spicy javascript: Create your first Chrome extension for web analytics QA
Spicy javascript: Create your first Chrome extension for web analytics QASpicy javascript: Create your first Chrome extension for web analytics QA
Spicy javascript: Create your first Chrome extension for web analytics QAAlban Gérôme
 
A test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobileA test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobileGlobalLogic Ukraine
 
The Ring programming language version 1.5.2 book - Part 7 of 181
The Ring programming language version 1.5.2 book - Part 7 of 181The Ring programming language version 1.5.2 book - Part 7 of 181
The Ring programming language version 1.5.2 book - Part 7 of 181Mahmoud Samir Fayed
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJames Casey
 

Similar to Grails66 web service (20)

The Ring programming language version 1.5.3 book - Part 53 of 184
The Ring programming language version 1.5.3 book - Part 53 of 184The Ring programming language version 1.5.3 book - Part 53 of 184
The Ring programming language version 1.5.3 book - Part 53 of 184
 
The Ring programming language version 1.5.3 book - Part 43 of 184
The Ring programming language version 1.5.3 book - Part 43 of 184The Ring programming language version 1.5.3 book - Part 43 of 184
The Ring programming language version 1.5.3 book - Part 43 of 184
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
The Ring programming language version 1.10 book - Part 53 of 212
The Ring programming language version 1.10 book - Part 53 of 212The Ring programming language version 1.10 book - Part 53 of 212
The Ring programming language version 1.10 book - Part 53 of 212
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
Agile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansAgile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with Netbeans
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3
 
Grails EE
Grails EEGrails EE
Grails EE
 
MongoDB World 2018: Keynote
MongoDB World 2018: KeynoteMongoDB World 2018: Keynote
MongoDB World 2018: Keynote
 
After max+phonegap
After max+phonegapAfter max+phonegap
After max+phonegap
 
混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaver混搭移动开发:PhoneGap+JQurey+Dreamweaver
混搭移动开发:PhoneGap+JQurey+Dreamweaver
 
Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
 
Google App Engine with Gaelyk
Google App Engine with GaelykGoogle App Engine with Gaelyk
Google App Engine with Gaelyk
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Introduction to Grails Framework
Introduction to Grails FrameworkIntroduction to Grails Framework
Introduction to Grails Framework
 
Spicy javascript: Create your first Chrome extension for web analytics QA
Spicy javascript: Create your first Chrome extension for web analytics QASpicy javascript: Create your first Chrome extension for web analytics QA
Spicy javascript: Create your first Chrome extension for web analytics QA
 
A test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobileA test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobile
 
Serverless
ServerlessServerless
Serverless
 
The Ring programming language version 1.5.2 book - Part 7 of 181
The Ring programming language version 1.5.2 book - Part 7 of 181The Ring programming language version 1.5.2 book - Part 7 of 181
The Ring programming language version 1.5.2 book - Part 7 of 181
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 

More from Somkiat Puisungnoen (20)

Next of Java 2022
Next of Java 2022Next of Java 2022
Next of Java 2022
 
Sck spring-reactive
Sck spring-reactiveSck spring-reactive
Sck spring-reactive
 
Part 2 :: Spring Boot testing
Part 2 :: Spring Boot testingPart 2 :: Spring Boot testing
Part 2 :: Spring Boot testing
 
vTalk#1 Microservices with Spring Boot
vTalk#1 Microservices with Spring BootvTalk#1 Microservices with Spring Boot
vTalk#1 Microservices with Spring Boot
 
Lesson learned from React native and Flutter
Lesson learned from React native and FlutterLesson learned from React native and Flutter
Lesson learned from React native and Flutter
 
devops
devops devops
devops
 
Angular :: basic tuning performance
Angular :: basic tuning performanceAngular :: basic tuning performance
Angular :: basic tuning performance
 
Shared code between projects
Shared code between projectsShared code between projects
Shared code between projects
 
Distributed Tracing
Distributed Tracing Distributed Tracing
Distributed Tracing
 
Manage data of service
Manage data of serviceManage data of service
Manage data of service
 
RobotFramework Meetup at Thailand #2
RobotFramework Meetup at Thailand #2RobotFramework Meetup at Thailand #2
RobotFramework Meetup at Thailand #2
 
Visual testing
Visual testingVisual testing
Visual testing
 
Cloud Native App
Cloud Native AppCloud Native App
Cloud Native App
 
Wordpress for Newbie
Wordpress for NewbieWordpress for Newbie
Wordpress for Newbie
 
Sck Agile in Real World
Sck Agile in Real WorldSck Agile in Real World
Sck Agile in Real World
 
Clean you code
Clean you codeClean you code
Clean you code
 
SCK Firestore at CNX
SCK Firestore at CNXSCK Firestore at CNX
SCK Firestore at CNX
 
Unhappiness Developer
Unhappiness DeveloperUnhappiness Developer
Unhappiness Developer
 
The Beauty of BAD code
The Beauty of  BAD codeThe Beauty of  BAD code
The Beauty of BAD code
 
React in the right way
React in the right wayReact in the right way
React in the right way
 

Recently uploaded

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Recently uploaded (20)

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

Grails66 web service

  • 1. Page 1 Grails : REST and Web Service @somkiat
  • 2. Page 2 REST • Not really a Technology • More an Architecture • Simple • Communication via plain text, xml, json • Combine with HTTP method • Resource-Oriented
  • 3. Page 3 Mapping HTTP Method HTTP Method Action GET Read ( R ) PUT Update ( U ) POST Create ( C ) DELETE Delete ( D )
  • 4. Page 4 Mapping REST in Grails • Example static mappings = { "/product/$id?"( resource:"product" ) } HTTP Method Action GET show PUT update POST save DELETE delete
  • 5. Page 5 Mapping REST in Grails • Example static mappings = { "/product/$id"(controller:"product", parseRequest:true ){ action = [ GET:"show", PUT:"update", DELETE:"delete", POST:"save“ ] } } Automatic XML or JSON Marshaling
  • 6. Page 6 Create REST Controller • grails create-controller product class ProductController { def show = { render “show from rest” } def save = { render “save from rest” } def update = { render “update from rest” } def delete = { render “delete from rest” } }
  • 7. Page 7 REST Client • Groovy HTTPBuilder import groovyx.net.http.* import static groovyx.net.http.ContentType.HTML def url = "http://localhost:8080/example1/product/1" def http = new HTTPBuilder( url ) http.request(Method.GET, HTML) { response.success = {resp, html -> println html } }
  • 8. Page 8 REST Client • GSP Form <g:form controller="product" method="PUT"> <g:submitButton name="Test" /> </g:form>
  • 9. Page 9 REST Controller :: Switch on HTTP method • grails create-controller product class ProductController { def index = { switch(request.method){ case "POST": render "Create" break case "GET": render "Retrieve" break case "PUT": render "Update" break case "DELETE": render "Delete" break } } }
  • 10. Page 10 Communication via XML • grails create-controller product import grails.converters.* class ProductController { def list = { render Product.list() as XML } def show = { render Product.get( params.id ) as XML } }
  • 11. Page 11 Domain class :: Product • grails create-domain-class product class Product { String name Double price String toString() { return "id=${id}|name=${name}|price=${price}" } }
  • 12. Page 12 Insert data for Test • File /conf/BootStap.groovy class BootStrap { def init = { servletContext -> if( !Product.count() ) { new Product( name:"Product 1", price:12.9 ).save( failOnError:true ) new Product( name:"Product 2", price:20.5 ).save( failOnError:true ) } } def destroy = { } }
  • 13. Page 13 XML Result <list> <product id="1"> <name>Product 1</name> <price>12.9</price> </product> <product id="2"> <name>Product 2</name> <price>20.5</price> </product> </list>
  • 14. Page 14 Custom XML <products> <product id="1"> <product-name>product 1</name> <product-price>12.9</price> </product> <product id="2"> <product-name>product 2</name> <product-price>20.5</price> </product> </products>
  • 15. Page 15 Communication via XML def listXmlCustom = { def productList = Product.list() render( contentType:"text/xml" ) { products{ for( temp in productList ) { product( id:temp.id ){ "product-name"(temp.name) "product-price"(temp.price) } } } } } Using Groovy Markup Builder http://groovy.codehaus.org/Creating+XML+using+Groovy's+MarkupBuilder
  • 16. Page 16 Communication via JSON • grails create-controller product import grails.converters.* class ProductController { def list = { render Product.list() as JSON } def show = { render Product.get( params.id ) as JSON } }
  • 17. Page 17 JSON Result [ { "class":"example1.Product", "id":1, "name":"Product 1", "price":12.9 }, { "class":"example1.Product", "id":2, "name":"Product 2", "price":20.5 } ]
  • 18. Page 18 Content Negotiation • Allow to return different format based on the request. • All format in file /conf/Config.groovy grails.mime.types = [ html: ['text/html','application/xhtml+xml'], xml: ['text/xml', 'application/xml'], text: 'text/plain', js: 'text/javascript', rss: 'application/rss+xml', atom: 'application/atom+xml', css: 'text/css', csv: 'text/csv', all: '*/*', json: ['application/json','text/json'], form: 'application/x-www-form-urlencoded', multipartForm: 'multipart/form-data' ]
  • 19. Page 19 Using withFormat def list = { if(!params.max) params.max = 10 def productList = Product.list( params ) withFormat { html { render productList } xml { render productList as XML } json { render productList as JSON } } } Default format html
  • 20. Page 20 How to call ? • Default • http://localhost:8080/example/product/list • URL Extension • http://localhost:8080/example/product/list.html • Format request parameter • http://localhost:8080/example/product/list?format=html
  • 21. Page 21 URL Extension • Disable/Enable in file /conf/Config.groovy grails.mime.file.extensions = true // Enable ( Default ) grails.mime.file.extensions = false // Disable
  • 22. Page 22 Define Format parameter in URL Mapping • Set default format = xml "/product2/list2" (controller:"product2", action:"list2") { format = "xml" }
  • 23. Page 23 How to call ? • http://localhost:8080/example/product/list.xml • http://localhost:8080/example/product/list?format=xml
  • 24. Page 24 RSS and Atom • Using Feed plug-in •http://docs.codehaus.org/display/GRAILS/Feeds+Plugin • ROME Library •https://rome.dev.java.net/
  • 25. Page 25 RSS • Install plug-in > grails install-plugin feeds withFormat { rss { render(feedType:"rss", feedVersion:"2.0") { title = "My test feed" link = "http://www.grails66.com/feed" description = “Grails 66 feed" productList.each() { product -> entry(product.name) { link ="http://grails66.com//${product.id}" product.name } } } } }
  • 26. Page 26 Result • http://localhost:8080/example/product/list.rss • http://localhost:8080/example/product/list?format=rss
  • 27. Page 27 Demo :: REST with DOJO grails create-app example2 cd example2 grails install-plugin dojo grails install-dojo grails create-domain-class product grails create-controller product
  • 28. Page 28 Web Service • Web API • Access via HTTP • Executed on remote system • SOA ( Service-Oriented Architecture )
  • 29. Page 29 Grails Plug-in • XFire • http://xfire.codehaus.org/ • CFX • http://grails.org/plugin/cxf/ • Axis2 • http://grails.org/plugin/axis2 • Metro • https://jax-ws-commons.dev.java.net/grails/