SlideShare a Scribd company logo
1 of 30
•REST Api using Grails
Agenda
✔ What is REST service
✔ Guidelines to create REST Api
✔ Domain class as REST resource
✔ Implementing REST Controller
✔ Customizing Response Rendering
✔ Versioning REST Resources
What is REST service
✔ Service:- App that is hosted in backend and ready to
serve data
✔ REST is stand for (Representational State Transfer)
Guidelines to create REST Api
✔ Use HTTP methods (Client will request data with
http)
✔ Expose directory structure like URIs
✔ Transfer XML or JSON (Javascript Object Notation)
or both
✔ Be stateless. (server does not store any state about
the client session on the server side.)
REST is very simple and involves
• XML, JSON as a communication medium
• Combined with URL parameters
• Use HTTP methods GET, POST, PUT, DELETE
Each HTTP method maps to an action type
• GET:- retrieving data
• POST:- creating data
• PUT:- updating data
• DELETE:- Delete data
Domain classes as REST resources
• Expose a domain class as a REST resource. It can be done by adding grails.rest.Resource @Resource
• Specify a URI@Resource(uri = '/persons')
• Now domain is available as a REST resource either JSON or XML formats. Default type is XML.
• Ex:-
• package com
• import grails.rest.Resource
• @Resource(uri = '/persons')
• class Person {
• static constraints = {
• }
• }
Header Information
● Content Type
● Accept
• package com
• import
grails.rest.Resource
• @Resource(uri =
'/persons')
• class Person {
• String firstName
• String lastName
• Long age
• static constraints = {
• }
• <person id="1">
• <age>25</age>
• <firstName>Vijay</firstNa
me>
• <lastName>Shukla</lastN
ame>
• </person>
• <list>
• <person id="1">
• <age>25</age>
• <firstName>Vijay</firstNa
me>
• <lastName>Shukla</last
Name>
• </person>
• <person id="2">
• <age>30</age>
• [{"class":"com.Person"
,"id":1,"age":25,"firstN
ame":"Vijay","lastNam
e":"Shukla"},{"class":"c
om.Person","id":2,"ag
e":30,"firstName":"Kar
an","lastName":"Aah
•If you want to change the defult representation from
XML to JSON then
•add formats option like:-
•@Resource(uri = '/persons', formats = ['json', 'xml'])
• [{"class":"com.Person","i
d":1,"age":25,"firstName
":"Vijay","lastName":"Sh
ukla"},{"class":"com.Per
son","id":2,"age":30,"first
Name":"Karan","lastNa
me":"Aahuja"}]
• Instead of using the file
extension in the URI,
you can also obtain a
JSON response using
the ACCEPT header.
• curl -i -H "Accept:
application/json"
You can create a new resource by issuing
a POST request:
• curl -i -X POST -H "Content-Type: application/json" -d
'{"firstName":"Testing", "lastName":"REST",
"age":"85"}'
• HTTP/1.1 201 Created
• Server: Apache-Coyote/1.1
• X-Application-Context:
application:development
• Location:
http://localhost:8080/persons/3
When any Error Occured then
• curl -i -X POST -H "Content-Type: application/json" -d
'{"firstName":"Testing"}' http://localhost:8080/persons
• HTTP/1.1 422 Unprocessable Entity
• Server: Apache-Coyote/1.1
• X-Application-Context: application:development
• Content-Type: application/json;charset=UTF-8
• Transfer-Encoding: chunked
• Date: Sun, 10 Jan 2016 03:32:48 GMT
• {"errors":[{"object":"com.Person","field":"age","r
Updating can be done with a PUT request:
• curl -i -X PUT -H "Content-Type: application/json" -d
'{"firstName":"Testing", "lastName":"Renaming", "age":"05"}'
• Response:-
• HTTP/1.1 200 OK
• Server: Apache-Coyote/1.1
• X-Application-Context: application:development
• Location: http://localhost:8080/persons/1
• Content-Type: application/json;charset=UTF-8
• Transfer-Encoding: chunked
• Date: Sat, 09 Jan 2016 14:06:10 GMT
• {"class":"com.Person","id":1,"age":5,"firstName":"Testing","lastName":"Rena
ming"}
• Now by hitting
If you not provide any ID to be update by PUT
• curl -i -X PUT -H "Content-Type: application/json" -d
'{"firstName":"Testing", "lastName":"Renaming", "age":"05"}'
http://localhost:8080/persons
• HTTP/1.1 405 Method Not Allowed
• Server: Apache-Coyote/1.1
• X-Application-Context: application:development
• Allow: GET, HEAD
• Content-Type: application/json;charset=UTF-8
• Transfer-Encoding: chunked
• Date: Sun, 10 Jan 2016 03:35:27 GMT
• {"timestamp":1452396927350,"status":405,"error":"Method Not
Allowed","exception":"org.springframework.web.HttpRequestM
ethodNotSupportedException","message":"Request method
a resource can be deleted with DELETE request:
• curl -i -X DELETE -H "Content-Type: application/json"
• Response:- HTTP/1.1 204 No Content
• Server: Apache-Coyote/1.1
• X-Application-Context: application:development
• Date: Sat, 09 Jan 2016 14:08:35 GMT
• Now, by hitting
• [{"class":"com.Person","id":2,"age":30,"firstName":"Karan","lastName
":"Aahuja"},{"class":"com.Person","id":3,"age":85,"firstName":"Testing
","lastName":"REST"}]
If the data you want to delete is not available
• curl: (6) Could not resolve host: Content-Type
• HTTP/1.1 404 Not Found
• Server: Apache-Coyote/1.1
• X-Application-Context: application:development
• Content-Length: 0
• Date: Sat, 09 Jan 2016 14:10:07 GMT
Update only one field:-
• curl -X PATCH -H "Content-Type: application/json" -d
'{"firstName":"REST API TESTING"}'
http://localhost:8080/persons/2• {"class":"com.Person","id":2,"age":30,"firstName":"REST API
TESTING","lastName":"Aahuja"}
• Now hitting
• [{"class":"com.Person","id":1,"age":25,"firstName":"Vijay","lastN
ame":"Shukla"},{"class":"com.Person","id":2,"age":30,"firstNam
e":"REST API TESTING","lastName":"Aahuja"}]
•We can enable read-only capabilities ny setting reaadOnly attribute to
true:-
•@Resource(uri='/books', readOnly=true)
•In this case POST, PUT and DELETE requests will be forbidden.
•package com
•import grails.rest.Resource
•@Resource(uri = '/persons', formats = ['json', 'xml'], readOnly = true)
•class Person {
• String firstName
• String lastName
• Long age
• static constraints = {
• }
•}
• curl -i -H "Accept:
application/json"
http://localhost:8080/persons
• HTTP/1.1 200 OK
• Server: Apache-Coyote/1.1
• X-Application-Context:
application:development
• Content-Type:
application/json;charset=UTF
-8
• Transfer-Encoding: chunked
• Date: Sat, 09 Jan 2016
14:15:05 GMT
• [{"class":"com.Person","id":1,"
• curl -i -X POST -H
"Content-Type:
application/json" -d
'{"firstName":"DO NOT",
"lastName":"ENTER",
"age":"85"}'
http://localhost:8080/per
sons
• HTTP/1.1 405 Method
Not Allowed
• Server: Apache-
Coyote/1.1
• X-Application-Context:
application:development
• Content-Length: 0
• Date: Sat, 09 Jan 2016
• If you have done any changes then refresh your application
else you may get this error
• curl -i -H "Accept: application/json"
http://localhost:8080/persons
• curl: (7) Failed to connect to localhost port 8080: Connection
•If you prefer to keep all url part in UrlMapping then simply
remove uri part from domain and below line in UrlMapping.groovy
•"/persons"(resources:"person")
•Ex:-
•import grails.rest.Resource
•@Resource(formats = ['json', 'xml'], readOnly = true)
•class Person {
• String firstName
• String lastName
• Long age
• static constraints = {
• }
•}
Works Done by Resource Annotation
✔ Automatic Mappings
✔ No Controllers created
✔ UrlMappiings.groovy not updated
✔ HTTP status codes
✔ HTTP methods
REST-ful Controller
• Create domain
• Create controller/ Generate Controller
• Add this line to URLMppings.groovy
• "/companies"(controller: "company", action: "index",
method: "GET")
• "/companies"(controller: "company", action: "save",
method: "POST")
• "/companies/$id"(controller: "company", action:
"update", method: "PUT")
• "/companies/$id"(controller: "company", action:
"patch", method: "PATCH")
✔ Controller Class must extends RestfulController
✔ Add static response formats
✔ class CompanyController extends RestfulController {
✔ static responseFormats = ["json", "xml"]
✔ CompanyController() {
✔ super(Company)
✔ }
✔ }
URL MAPPING REPORTS
✔ HTTP Methods
✔via mappings
✔“/custom”(controller=”custom”, action=”index”,
method=”GET”)
✔via controllers
✔static allowedMethods = [sav:”POST”,
update:”PUT”]
✔ Either use allowedMethod way or mapping ways
Default Media Types
✔ xml if nothing specified
✔ on mappings and controllers
✔formats = [“json”,”xml”]
✔ Extension
✔/countries.xml
✔/countries.json
✔ Requesting a format not included returns 406 Not Acceptable
Custom Response Renderer
• Register custom JSON or XML renderers bean in
resources.groovy
• beans = {
• countryJsonRenderer(JsonCollectionRenderer,
Country) {
• excludes = ['abreviation']
• }
• personJsonRenderer(XmlCollectionRenderer,
Person){
• excludes = ["age"]
• }
Custom Response Renderer
• Registeriing Custome Renderer in Bootstrap.grroovy
• JSON.registerObjectMarshaller(Country) {
• return [
• id : it.id,
• countryName : it.countryName,
• abbreviation: it.abbreviation,
• continent : it.continent
• ]
• }
References

More Related Content

What's hot

Cool bonsai cool - an introduction to ElasticSearch
Cool bonsai cool - an introduction to ElasticSearchCool bonsai cool - an introduction to ElasticSearch
Cool bonsai cool - an introduction to ElasticSearchclintongormley
 
Experiences on a Design Approach for Interactive Web Applications
Experiences on a Design Approach for Interactive Web ApplicationsExperiences on a Design Approach for Interactive Web Applications
Experiences on a Design Approach for Interactive Web ApplicationsJanne Kuuskeri
 
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...Codemotion
 
Webinar: Modern Techniques for Better Search Relevance with Fusion
Webinar: Modern Techniques for Better Search Relevance with FusionWebinar: Modern Techniques for Better Search Relevance with Fusion
Webinar: Modern Techniques for Better Search Relevance with FusionLucidworks
 
Hadoop User Group EU 2014
Hadoop User Group EU 2014Hadoop User Group EU 2014
Hadoop User Group EU 2014cwensel
 
Agile Testing Days 2018 - API Fundamentals - postman collection
Agile Testing Days 2018 - API Fundamentals - postman collectionAgile Testing Days 2018 - API Fundamentals - postman collection
Agile Testing Days 2018 - API Fundamentals - postman collectionJoEllen Carter
 
elasticsearch - advanced features in practice
elasticsearch - advanced features in practiceelasticsearch - advanced features in practice
elasticsearch - advanced features in practiceJano Suchal
 
NoSQL & MongoDB
NoSQL & MongoDBNoSQL & MongoDB
NoSQL & MongoDBShuai Liu
 
Native Code, Off-Heap Data & JSON Facet API for Solr (Heliosearch)
Native Code, Off-Heap Data & JSON Facet API for Solr (Heliosearch)Native Code, Off-Heap Data & JSON Facet API for Solr (Heliosearch)
Native Code, Off-Heap Data & JSON Facet API for Solr (Heliosearch)Yonik Seeley
 
CouchDB at JAOO Århus 2009
CouchDB at JAOO Århus 2009CouchDB at JAOO Århus 2009
CouchDB at JAOO Århus 2009Jason Davies
 
ElasticSearch for .NET Developers
ElasticSearch for .NET DevelopersElasticSearch for .NET Developers
ElasticSearch for .NET DevelopersBen van Mol
 
Getting Buzzed on Buzzwords: Using Cloud & Big Data to Pentest at Scale
Getting Buzzed on Buzzwords: Using Cloud & Big Data to Pentest at ScaleGetting Buzzed on Buzzwords: Using Cloud & Big Data to Pentest at Scale
Getting Buzzed on Buzzwords: Using Cloud & Big Data to Pentest at ScaleBishop Fox
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responsesdarrelmiller71
 
Elasticsearch: You know, for search! and more!
Elasticsearch: You know, for search! and more!Elasticsearch: You know, for search! and more!
Elasticsearch: You know, for search! and more!Philips Kokoh Prasetyo
 
Solr and Elasticsearch, a performance study
Solr and Elasticsearch, a performance studySolr and Elasticsearch, a performance study
Solr and Elasticsearch, a performance studyCharlie Hull
 
Webinar: What's New in Solr 6
Webinar: What's New in Solr 6Webinar: What's New in Solr 6
Webinar: What's New in Solr 6Lucidworks
 
Simple search with elastic search
Simple search with elastic searchSimple search with elastic search
Simple search with elastic searchmarkstory
 
Elasticsearch in 15 Minutes
Elasticsearch in 15 MinutesElasticsearch in 15 Minutes
Elasticsearch in 15 MinutesKarel Minarik
 
Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Karel Minarik
 

What's hot (20)

Cool bonsai cool - an introduction to ElasticSearch
Cool bonsai cool - an introduction to ElasticSearchCool bonsai cool - an introduction to ElasticSearch
Cool bonsai cool - an introduction to ElasticSearch
 
Experiences on a Design Approach for Interactive Web Applications
Experiences on a Design Approach for Interactive Web ApplicationsExperiences on a Design Approach for Interactive Web Applications
Experiences on a Design Approach for Interactive Web Applications
 
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK -  Nicola Iarocci - Co...
RESTFUL SERVICES MADE EASY: THE EVE REST API FRAMEWORK - Nicola Iarocci - Co...
 
Webinar: Modern Techniques for Better Search Relevance with Fusion
Webinar: Modern Techniques for Better Search Relevance with FusionWebinar: Modern Techniques for Better Search Relevance with Fusion
Webinar: Modern Techniques for Better Search Relevance with Fusion
 
Hadoop User Group EU 2014
Hadoop User Group EU 2014Hadoop User Group EU 2014
Hadoop User Group EU 2014
 
Agile Testing Days 2018 - API Fundamentals - postman collection
Agile Testing Days 2018 - API Fundamentals - postman collectionAgile Testing Days 2018 - API Fundamentals - postman collection
Agile Testing Days 2018 - API Fundamentals - postman collection
 
elasticsearch - advanced features in practice
elasticsearch - advanced features in practiceelasticsearch - advanced features in practice
elasticsearch - advanced features in practice
 
NoSQL & MongoDB
NoSQL & MongoDBNoSQL & MongoDB
NoSQL & MongoDB
 
Native Code, Off-Heap Data & JSON Facet API for Solr (Heliosearch)
Native Code, Off-Heap Data & JSON Facet API for Solr (Heliosearch)Native Code, Off-Heap Data & JSON Facet API for Solr (Heliosearch)
Native Code, Off-Heap Data & JSON Facet API for Solr (Heliosearch)
 
CouchDB at JAOO Århus 2009
CouchDB at JAOO Århus 2009CouchDB at JAOO Århus 2009
CouchDB at JAOO Århus 2009
 
ElasticSearch for .NET Developers
ElasticSearch for .NET DevelopersElasticSearch for .NET Developers
ElasticSearch for .NET Developers
 
Getting Buzzed on Buzzwords: Using Cloud & Big Data to Pentest at Scale
Getting Buzzed on Buzzwords: Using Cloud & Big Data to Pentest at ScaleGetting Buzzed on Buzzwords: Using Cloud & Big Data to Pentest at Scale
Getting Buzzed on Buzzwords: Using Cloud & Big Data to Pentest at Scale
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responses
 
Elasticsearch: You know, for search! and more!
Elasticsearch: You know, for search! and more!Elasticsearch: You know, for search! and more!
Elasticsearch: You know, for search! and more!
 
Solr and Elasticsearch, a performance study
Solr and Elasticsearch, a performance studySolr and Elasticsearch, a performance study
Solr and Elasticsearch, a performance study
 
Webinar: What's New in Solr 6
Webinar: What's New in Solr 6Webinar: What's New in Solr 6
Webinar: What's New in Solr 6
 
JSON-LD and MongoDB
JSON-LD and MongoDBJSON-LD and MongoDB
JSON-LD and MongoDB
 
Simple search with elastic search
Simple search with elastic searchSimple search with elastic search
Simple search with elastic search
 
Elasticsearch in 15 Minutes
Elasticsearch in 15 MinutesElasticsearch in 15 Minutes
Elasticsearch in 15 Minutes
 
Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]
 

Similar to REST

How ElasticSearch lives in my DevOps life
How ElasticSearch lives in my DevOps lifeHow ElasticSearch lives in my DevOps life
How ElasticSearch lives in my DevOps life琛琳 饶
 
Node.js 與 google cloud storage
Node.js 與 google cloud storageNode.js 與 google cloud storage
Node.js 與 google cloud storageonlinemad
 
Mastering Access Control Policies
Mastering Access Control PoliciesMastering Access Control Policies
Mastering Access Control PoliciesAmazon Web Services
 
Mastering Access Control Policies (SEC302) | AWS re:Invent 2013
Mastering Access Control Policies (SEC302) | AWS re:Invent 2013Mastering Access Control Policies (SEC302) | AWS re:Invent 2013
Mastering Access Control Policies (SEC302) | AWS re:Invent 2013Amazon Web Services
 
Behavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberBehavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberKMS Technology
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with SolrErik Hatcher
 
Restful webservices
Restful webservicesRestful webservices
Restful webservicesKong King
 
(SEC303) Mastering Access Control Policies | AWS re:Invent 2014
(SEC303) Mastering Access Control Policies | AWS re:Invent 2014(SEC303) Mastering Access Control Policies | AWS re:Invent 2014
(SEC303) Mastering Access Control Policies | AWS re:Invent 2014Amazon Web Services
 
A Serverless Approach to Operational Log Visualisation and Analytics
A Serverless Approach to Operational Log Visualisation and AnalyticsA Serverless Approach to Operational Log Visualisation and Analytics
A Serverless Approach to Operational Log Visualisation and AnalyticsAmazon Web Services
 
2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...
2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...
2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...Andrey Devyatkin
 
Elegant Rest Design Webinar
Elegant Rest Design WebinarElegant Rest Design Webinar
Elegant Rest Design WebinarStormpath
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with SolrErik Hatcher
 
Applied Machine learning using H2O, python and R Workshop
Applied Machine learning using H2O, python and R WorkshopApplied Machine learning using H2O, python and R Workshop
Applied Machine learning using H2O, python and R WorkshopAvkash Chauhan
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.Andrey Oleynik
 
SharePoint REST vs CSOM
SharePoint REST vs CSOMSharePoint REST vs CSOM
SharePoint REST vs CSOMMark Rackley
 

Similar to REST (20)

How ElasticSearch lives in my DevOps life
How ElasticSearch lives in my DevOps lifeHow ElasticSearch lives in my DevOps life
How ElasticSearch lives in my DevOps life
 
Android and REST
Android and RESTAndroid and REST
Android and REST
 
Masting Access Control Policies
Masting Access Control PoliciesMasting Access Control Policies
Masting Access Control Policies
 
Node.js 與 google cloud storage
Node.js 與 google cloud storageNode.js 與 google cloud storage
Node.js 與 google cloud storage
 
Mastering Access Control Policies
Mastering Access Control PoliciesMastering Access Control Policies
Mastering Access Control Policies
 
Mastering Access Control Policies (SEC302) | AWS re:Invent 2013
Mastering Access Control Policies (SEC302) | AWS re:Invent 2013Mastering Access Control Policies (SEC302) | AWS re:Invent 2013
Mastering Access Control Policies (SEC302) | AWS re:Invent 2013
 
Auto Scaling Groups
Auto Scaling GroupsAuto Scaling Groups
Auto Scaling Groups
 
Behavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberBehavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using Cucumber
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with Solr
 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
 
(SEC303) Mastering Access Control Policies | AWS re:Invent 2014
(SEC303) Mastering Access Control Policies | AWS re:Invent 2014(SEC303) Mastering Access Control Policies | AWS re:Invent 2014
(SEC303) Mastering Access Control Policies | AWS re:Invent 2014
 
A Serverless Approach to Operational Log Visualisation and Analytics
A Serverless Approach to Operational Log Visualisation and AnalyticsA Serverless Approach to Operational Log Visualisation and Analytics
A Serverless Approach to Operational Log Visualisation and Analytics
 
2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...
2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...
2020-02-20 - HashiTalks 2020 - HashiCorp Vault configuration as code via Hash...
 
Elegant Rest Design Webinar
Elegant Rest Design WebinarElegant Rest Design Webinar
Elegant Rest Design Webinar
 
Policy Ninja
Policy NinjaPolicy Ninja
Policy Ninja
 
Rapid Prototyping with Solr
Rapid Prototyping with SolrRapid Prototyping with Solr
Rapid Prototyping with Solr
 
Applied Machine learning using H2O, python and R Workshop
Applied Machine learning using H2O, python and R WorkshopApplied Machine learning using H2O, python and R Workshop
Applied Machine learning using H2O, python and R Workshop
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.
 
SharePoint REST vs CSOM
SharePoint REST vs CSOMSharePoint REST vs CSOM
SharePoint REST vs CSOM
 
Rest
RestRest
Rest
 

More from Vijay Shukla (20)

Introduction of webpack 4
Introduction of webpack 4Introduction of webpack 4
Introduction of webpack 4
 
Preview of Groovy 3
Preview of Groovy 3Preview of Groovy 3
Preview of Groovy 3
 
Jython
JythonJython
Jython
 
Groovy closures
Groovy closuresGroovy closures
Groovy closures
 
Groovy
GroovyGroovy
Groovy
 
Grails services
Grails servicesGrails services
Grails services
 
Grails plugin
Grails pluginGrails plugin
Grails plugin
 
Grails domain
Grails domainGrails domain
Grails domain
 
Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag lib
 
Grails
GrailsGrails
Grails
 
Gorm
GormGorm
Gorm
 
Controller
ControllerController
Controller
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
Command object
Command objectCommand object
Command object
 
Boot strap.groovy
Boot strap.groovyBoot strap.groovy
Boot strap.groovy
 
Vertx
VertxVertx
Vertx
 
Custom plugin
Custom pluginCustom plugin
Custom plugin
 
Spring security
Spring securitySpring security
Spring security
 
Config/BuildConfig
Config/BuildConfigConfig/BuildConfig
Config/BuildConfig
 
GORM
GORMGORM
GORM
 

Recently uploaded

React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 

Recently uploaded (20)

React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 

REST

  • 2. Agenda ✔ What is REST service ✔ Guidelines to create REST Api ✔ Domain class as REST resource ✔ Implementing REST Controller ✔ Customizing Response Rendering ✔ Versioning REST Resources
  • 3. What is REST service ✔ Service:- App that is hosted in backend and ready to serve data ✔ REST is stand for (Representational State Transfer)
  • 4. Guidelines to create REST Api ✔ Use HTTP methods (Client will request data with http) ✔ Expose directory structure like URIs ✔ Transfer XML or JSON (Javascript Object Notation) or both ✔ Be stateless. (server does not store any state about the client session on the server side.)
  • 5. REST is very simple and involves • XML, JSON as a communication medium • Combined with URL parameters • Use HTTP methods GET, POST, PUT, DELETE
  • 6. Each HTTP method maps to an action type • GET:- retrieving data • POST:- creating data • PUT:- updating data • DELETE:- Delete data
  • 7. Domain classes as REST resources • Expose a domain class as a REST resource. It can be done by adding grails.rest.Resource @Resource • Specify a URI@Resource(uri = '/persons') • Now domain is available as a REST resource either JSON or XML formats. Default type is XML. • Ex:- • package com • import grails.rest.Resource • @Resource(uri = '/persons') • class Person { • static constraints = { • } • }
  • 9. • package com • import grails.rest.Resource • @Resource(uri = '/persons') • class Person { • String firstName • String lastName • Long age • static constraints = { • } • <person id="1"> • <age>25</age> • <firstName>Vijay</firstNa me> • <lastName>Shukla</lastN ame> • </person>
  • 10. • <list> • <person id="1"> • <age>25</age> • <firstName>Vijay</firstNa me> • <lastName>Shukla</last Name> • </person> • <person id="2"> • <age>30</age> • [{"class":"com.Person" ,"id":1,"age":25,"firstN ame":"Vijay","lastNam e":"Shukla"},{"class":"c om.Person","id":2,"ag e":30,"firstName":"Kar an","lastName":"Aah
  • 11. •If you want to change the defult representation from XML to JSON then •add formats option like:- •@Resource(uri = '/persons', formats = ['json', 'xml'])
  • 12. • [{"class":"com.Person","i d":1,"age":25,"firstName ":"Vijay","lastName":"Sh ukla"},{"class":"com.Per son","id":2,"age":30,"first Name":"Karan","lastNa me":"Aahuja"}] • Instead of using the file extension in the URI, you can also obtain a JSON response using the ACCEPT header. • curl -i -H "Accept: application/json"
  • 13. You can create a new resource by issuing a POST request: • curl -i -X POST -H "Content-Type: application/json" -d '{"firstName":"Testing", "lastName":"REST", "age":"85"}' • HTTP/1.1 201 Created • Server: Apache-Coyote/1.1 • X-Application-Context: application:development • Location: http://localhost:8080/persons/3
  • 14. When any Error Occured then • curl -i -X POST -H "Content-Type: application/json" -d '{"firstName":"Testing"}' http://localhost:8080/persons • HTTP/1.1 422 Unprocessable Entity • Server: Apache-Coyote/1.1 • X-Application-Context: application:development • Content-Type: application/json;charset=UTF-8 • Transfer-Encoding: chunked • Date: Sun, 10 Jan 2016 03:32:48 GMT • {"errors":[{"object":"com.Person","field":"age","r
  • 15. Updating can be done with a PUT request: • curl -i -X PUT -H "Content-Type: application/json" -d '{"firstName":"Testing", "lastName":"Renaming", "age":"05"}' • Response:- • HTTP/1.1 200 OK • Server: Apache-Coyote/1.1 • X-Application-Context: application:development • Location: http://localhost:8080/persons/1 • Content-Type: application/json;charset=UTF-8 • Transfer-Encoding: chunked • Date: Sat, 09 Jan 2016 14:06:10 GMT • {"class":"com.Person","id":1,"age":5,"firstName":"Testing","lastName":"Rena ming"} • Now by hitting
  • 16. If you not provide any ID to be update by PUT • curl -i -X PUT -H "Content-Type: application/json" -d '{"firstName":"Testing", "lastName":"Renaming", "age":"05"}' http://localhost:8080/persons • HTTP/1.1 405 Method Not Allowed • Server: Apache-Coyote/1.1 • X-Application-Context: application:development • Allow: GET, HEAD • Content-Type: application/json;charset=UTF-8 • Transfer-Encoding: chunked • Date: Sun, 10 Jan 2016 03:35:27 GMT • {"timestamp":1452396927350,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestM ethodNotSupportedException","message":"Request method
  • 17. a resource can be deleted with DELETE request: • curl -i -X DELETE -H "Content-Type: application/json" • Response:- HTTP/1.1 204 No Content • Server: Apache-Coyote/1.1 • X-Application-Context: application:development • Date: Sat, 09 Jan 2016 14:08:35 GMT • Now, by hitting • [{"class":"com.Person","id":2,"age":30,"firstName":"Karan","lastName ":"Aahuja"},{"class":"com.Person","id":3,"age":85,"firstName":"Testing ","lastName":"REST"}]
  • 18. If the data you want to delete is not available • curl: (6) Could not resolve host: Content-Type • HTTP/1.1 404 Not Found • Server: Apache-Coyote/1.1 • X-Application-Context: application:development • Content-Length: 0 • Date: Sat, 09 Jan 2016 14:10:07 GMT
  • 19. Update only one field:- • curl -X PATCH -H "Content-Type: application/json" -d '{"firstName":"REST API TESTING"}' http://localhost:8080/persons/2• {"class":"com.Person","id":2,"age":30,"firstName":"REST API TESTING","lastName":"Aahuja"} • Now hitting • [{"class":"com.Person","id":1,"age":25,"firstName":"Vijay","lastN ame":"Shukla"},{"class":"com.Person","id":2,"age":30,"firstNam e":"REST API TESTING","lastName":"Aahuja"}]
  • 20. •We can enable read-only capabilities ny setting reaadOnly attribute to true:- •@Resource(uri='/books', readOnly=true) •In this case POST, PUT and DELETE requests will be forbidden. •package com •import grails.rest.Resource •@Resource(uri = '/persons', formats = ['json', 'xml'], readOnly = true) •class Person { • String firstName • String lastName • Long age • static constraints = { • } •}
  • 21. • curl -i -H "Accept: application/json" http://localhost:8080/persons • HTTP/1.1 200 OK • Server: Apache-Coyote/1.1 • X-Application-Context: application:development • Content-Type: application/json;charset=UTF -8 • Transfer-Encoding: chunked • Date: Sat, 09 Jan 2016 14:15:05 GMT • [{"class":"com.Person","id":1," • curl -i -X POST -H "Content-Type: application/json" -d '{"firstName":"DO NOT", "lastName":"ENTER", "age":"85"}' http://localhost:8080/per sons • HTTP/1.1 405 Method Not Allowed • Server: Apache- Coyote/1.1 • X-Application-Context: application:development • Content-Length: 0 • Date: Sat, 09 Jan 2016 • If you have done any changes then refresh your application else you may get this error • curl -i -H "Accept: application/json" http://localhost:8080/persons • curl: (7) Failed to connect to localhost port 8080: Connection
  • 22. •If you prefer to keep all url part in UrlMapping then simply remove uri part from domain and below line in UrlMapping.groovy •"/persons"(resources:"person") •Ex:- •import grails.rest.Resource •@Resource(formats = ['json', 'xml'], readOnly = true) •class Person { • String firstName • String lastName • Long age • static constraints = { • } •}
  • 23. Works Done by Resource Annotation ✔ Automatic Mappings ✔ No Controllers created ✔ UrlMappiings.groovy not updated ✔ HTTP status codes ✔ HTTP methods
  • 24. REST-ful Controller • Create domain • Create controller/ Generate Controller • Add this line to URLMppings.groovy • "/companies"(controller: "company", action: "index", method: "GET") • "/companies"(controller: "company", action: "save", method: "POST") • "/companies/$id"(controller: "company", action: "update", method: "PUT") • "/companies/$id"(controller: "company", action: "patch", method: "PATCH")
  • 25. ✔ Controller Class must extends RestfulController ✔ Add static response formats ✔ class CompanyController extends RestfulController { ✔ static responseFormats = ["json", "xml"] ✔ CompanyController() { ✔ super(Company) ✔ } ✔ }
  • 26. URL MAPPING REPORTS ✔ HTTP Methods ✔via mappings ✔“/custom”(controller=”custom”, action=”index”, method=”GET”) ✔via controllers ✔static allowedMethods = [sav:”POST”, update:”PUT”] ✔ Either use allowedMethod way or mapping ways
  • 27. Default Media Types ✔ xml if nothing specified ✔ on mappings and controllers ✔formats = [“json”,”xml”] ✔ Extension ✔/countries.xml ✔/countries.json ✔ Requesting a format not included returns 406 Not Acceptable
  • 28. Custom Response Renderer • Register custom JSON or XML renderers bean in resources.groovy • beans = { • countryJsonRenderer(JsonCollectionRenderer, Country) { • excludes = ['abreviation'] • } • personJsonRenderer(XmlCollectionRenderer, Person){ • excludes = ["age"] • }
  • 29. Custom Response Renderer • Registeriing Custome Renderer in Bootstrap.grroovy • JSON.registerObjectMarshaller(Country) { • return [ • id : it.id, • countryName : it.countryName, • abbreviation: it.abbreviation, • continent : it.continent • ] • }