SlideShare a Scribd company logo
Getting Started with Apex REST
Services
Matthew Lamb, Appirio, Technical Architect
@SFDCMatt
Safe Harbor
Safe harbor statement under the Private Securities Litigation Reform Act of 1995:
This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties
materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results
expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be
deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other
financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any
statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services.
The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new
functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our
operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of any
litigation, risks associated with completed and any possible mergers and acquisitions, the immature market in which we operate, our
relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our
service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to
larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is
included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most recent
fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor
Information section of our Web site.
Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently
available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions
based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these
forward-looking statements.
Matthew Lamb
Technical Architect
@SFDCMatt
Helping Enterprises Become:
Efficient
Effective
Agile
Social
Mobile
Session Objectives ==
▪ Briefly define, what is a REST service?
▪ How to create custom REST services in Apex
▪ How to call those custom REST services
▪ Tips-and-Tricks / Do’s and Don’ts / Code Sample
Session Objectives !=
▪ SOAP
▪ Web service design patterns / philosophies
▪ Security relevant to a public API
▪ Programmatic authentication into Salesforce
By a show of hands…
▪ Apex SOAP web services
▪ RESTful web service protocols
▪ Native REST API
• Know about it?
• Used it?
What is REST?
▪ Representational State Transfer
▪ REST is:
• An architecture style, not a protocol
• HTTP-based
• Client-server
• Stateless
What is REST?
▪ Uses standard HTTP methods, sent to an endpoint
• POST, GET, DELETE, PUT, PATCH
• https://na10.salesforce.com/services/apexrest/myaccountservice/

▪ Receive a response payload and a status in return
• JSON or XML
• 200 (OK), 404 (Not Found), etc -> bit.ly/responsecodes

▪ Commonly, HTTP verbs are mapped to CRUD operations
• POST = Create

GET = Read

DELETE = Delete

PUT/PATCH = Update
Why Use Apex REST?
▪ All sObjects, standard or custom, come with a REST API
▪ Apex REST used for defining custom interactions
▪ Good for abstracting complex interactions to a single call
• Inserting / updating multiple objects
• Callouts to external systems
• Custom search interfaces
Apex REST Basics
▪ All custom Apex REST services are accessed in the same namespace
• /services/apexrest/
• https://na15.salesforce.com/services/apexrest/<custom_path>

https://na10.salesforce.com/services/apexrest/v1/joborders
Base URL (your org)

Apex REST Namespace

Your custom path
Apex REST Basics
▪ If you know Apex…
▪ @RestResource(urlMapping=‘/<custom_path>/*’)
• Class level annotation to define a Global Class as an Apex REST service
• custom_path is a customizable URL you define for your end point

▪ @HttpPost, @HttpGet, @HttpDelete, @HttpPut, @HttpPatch
• Method level annotations to map HTTP methods functionality
Apex REST Basics
▪ RestContext class
• Container class for the RestRequest and RestResponse objects
• bit.ly/RestContext

▪ RestRequest and RestResponse
• Aptly named classes instantiated for each call to an Apex REST endpoint
• bit.ly/RestRequest
• bit.ly/RestResponse
Apex REST Basics
▪ RestRequest
• Provides access to all aspects of the request
• Inbound requests are automatically deserialized into a RestRequest instance
• headers, httpMethod, params, remoteAddress, requestBody, requestURI, resourcePath

▪ RestResponse
• Provides access to all aspects of the response
• statusCode, responseBody, headers
• Method return value is automatically serialized into the reponseBody
A Simple Apex REST Service
▪ REST_AccountService_V1
• Given an Account External Id, return a few details about the Account
• Endpoint is /v1/accounts/*, which means the service is at:
– https://na15.salesforce.com/services/apexrest/v1/accounts/

• @HttpGet method will take in an Account Id and return several data points about
that Account
Calling our simple Apex REST service
▪ GET @ /services/apexrest/v1/accounts/1006
• Success!
• https://na15.salesforce.com/services/apexrest/v1/accounts/1006
• JSON or XML
• Changes available in real time

▪ GET @ /services/apexrest/v1/accounts/6654
• Fail!
• Error handling
We can make him better than he was
▪ REST_AccountService_V2
• Success!
• Automatic serialization FTW!
– Apex primitives (excluding Blob)
– sObjects
– Lists or maps (with String keys) of Apex primitives or sObjects
– User-defined types that contain member variables of the types listed above
Operating on the resource and its entities
▪ So far we’ve been operating only on specific entities
• /v2/accounts/1003

▪ REST_AccountService_V3
• Maintain existing record lookup via foreign key
– /v3/accounts/1023

• Query string provides search capabilities
– /v3/accounts?Name=United
We GET it, what’s next?
▪ POST, PUT, PATCH, DELETE
Resource
accounts/
accounts/1147

GET

POST

PUT/PATCH

DELETE

Search Accounts

Create a new Account

Error

Error

Retrieve a specific
Account

Error

Update a specific Account

Remove a specific Account

▪ Verbs -> CRUD is oversimplifying it a bit
• bit.ly/PutOrPost
Let’s try POST on for size
▪ REST_AccountService_V4
• Should feel familiar
• Request body is required for POST
• Parameters map to method signature
• Same error handling principles apply

▪ Method definition strictly defines what can be passed
• Might be great for your use case, might not
• If you need more flexibility…
Several more flexible ways to allow input
▪ REST_AccountService_V5
• Your POST (or PUT or PATCH) method can take sObjects
• If you include a valid field, it’ll be deserialized into the sObject instance

▪ REST_AccountService_V6
• You could also take Lists of sObjects!

▪ REST_AccountService_v7
• Or even wrapper classes!
What’s next?
▪ PUT / PATCH / DELETE
▪ Similar to what you’ve seen today
▪ Write test coverage
▪ Download all the code
▪ http://github.com/sfdcmatt/DF13ApexRest
Matthew Lamb
Technical Architect
@SFDCMatt
We want to hear
from YOU!
Please take a moment to complete our
session survey
Surveys can be found in the “My Agenda”
portion of the Dreamforce app
Getting Started With Apex REST Services

More Related Content

What's hot (20)

PPTX
Salesforce integration best practices columbus meetup
MuleSoft Meetup
 
PPT
Customizing Oracle EBS OA Framework
iWare Logic Technologies Pvt. Ltd.
 
PPTX
Demystify Salesforce Bulk API
Dhanik Sahni
 
PPTX
Salesforce Streaming event - PushTopic and Generic Events
Dhanik Sahni
 
PPTX
Salesforce asynchronous apex
Badan Singh Pundeer
 
PPTX
REST API Design & Development
Ashok Pundit
 
PPTX
Data model in salesforce
Chamil Madusanka
 
PDF
Apex Enterprise Patterns: Building Strong Foundations
Salesforce Developers
 
PPT
Salesforce Integration
Joshua Hoskins
 
PPTX
Rest presentation
srividhyau
 
PDF
Webservices in SalesForce (part 1)
Mindfire Solutions
 
PPTX
Integrating with salesforce
Mark Adcock
 
PPTX
Web api
Sudhakar Sharma
 
PPT
Best Implementation Practices with BI Publisher
Mohan Dutt
 
PPT
Oracle Fusion Application
Arman Sadat Hossain
 
PPTX
REST-API introduction for developers
Patrick Savalle
 
PPTX
Oracle REST Data Services: Options for your Web Services
Jeff Smith
 
PDF
A comprehensive guide to Salesforce Org Strategy
Gaytri khandelwal
 
PPTX
Angular introduction students
Christian John Felix
 
Salesforce integration best practices columbus meetup
MuleSoft Meetup
 
Customizing Oracle EBS OA Framework
iWare Logic Technologies Pvt. Ltd.
 
Demystify Salesforce Bulk API
Dhanik Sahni
 
Salesforce Streaming event - PushTopic and Generic Events
Dhanik Sahni
 
Salesforce asynchronous apex
Badan Singh Pundeer
 
REST API Design & Development
Ashok Pundit
 
Data model in salesforce
Chamil Madusanka
 
Apex Enterprise Patterns: Building Strong Foundations
Salesforce Developers
 
Salesforce Integration
Joshua Hoskins
 
Rest presentation
srividhyau
 
Webservices in SalesForce (part 1)
Mindfire Solutions
 
Integrating with salesforce
Mark Adcock
 
Best Implementation Practices with BI Publisher
Mohan Dutt
 
Oracle Fusion Application
Arman Sadat Hossain
 
REST-API introduction for developers
Patrick Savalle
 
Oracle REST Data Services: Options for your Web Services
Jeff Smith
 
A comprehensive guide to Salesforce Org Strategy
Gaytri khandelwal
 
Angular introduction students
Christian John Felix
 

Viewers also liked (7)

PDF
Best Practices for RESTful Web Services
Salesforce Developers
 
PDF
RESTful API Design, Second Edition
Apigee | Google Cloud
 
PDF
Salesforce Apex Language Reference
salesforcer
 
PPTX
Forcelandia 2015
Jeff Douglas
 
PPT
Using Node.js for Mocking Apex Web Services
Jeff Douglas
 
PPTX
Using the Tooling API to Generate Apex SOAP Web Service Clients
Daniel Ballinger
 
PPT
Advanced Platform Series - OAuth and Social Authentication
Salesforce Developers
 
Best Practices for RESTful Web Services
Salesforce Developers
 
RESTful API Design, Second Edition
Apigee | Google Cloud
 
Salesforce Apex Language Reference
salesforcer
 
Forcelandia 2015
Jeff Douglas
 
Using Node.js for Mocking Apex Web Services
Jeff Douglas
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Daniel Ballinger
 
Advanced Platform Series - OAuth and Social Authentication
Salesforce Developers
 
Ad

Similar to Getting Started With Apex REST Services (20)

PPTX
Apex REST
Boris Bachovski
 
PPTX
Using Apex for REST Integration
Salesforce Developers
 
PPTX
SFDC REST API
Bohdan Dovhań
 
PPTX
Episode 11 building & exposing rest api in salesforce v1.0
Jitendra Zaa
 
PDF
Designing Custom REST and SOAP Interfaces on Force.com
Salesforce Developers
 
PPTX
Elevate Tel Aviv
sready
 
PPTX
The Power of Salesforce APIs World Tour Edition
Peter Chittum
 
PPT
Designing custom REST and SOAP interfaces on Force.com
Steven Herod
 
PPTX
Mastering-Salesforce-Development-A-Comprehensive-Overview (1).pptx
Anupama Kate
 
PPTX
Salesforce Campus Tour - Developer Advanced
James Ward
 
PDF
Building towards a Composite API Framework in Salesforce
Salesforce Developers
 
PDF
SalesForce WebServices part 2
Mindfire Solutions
 
PPTX
February 2020 Salesforce API Review
Lydon Bergin
 
PDF
Boxcars and Cabooses: When one more XHR is too much - Peter Chittum - Codemot...
Codemotion
 
PPTX
All Aboard the Boxcar! Going Beyond the Basics of REST
Pat Patterson
 
PPTX
REST API: Do More in the Feed with Action Links
Salesforce Developers
 
PPTX
Secure Development on the Salesforce Platform - Part I
Salesforce Developers
 
PPTX
Introduction to Apex for Developers
Salesforce Developers
 
DOCX
Salesforce Integration
Er. Prashant Veer Singh
 
PPTX
Salesforce Campus Tour - Developer Intro
James Ward
 
Apex REST
Boris Bachovski
 
Using Apex for REST Integration
Salesforce Developers
 
SFDC REST API
Bohdan Dovhań
 
Episode 11 building & exposing rest api in salesforce v1.0
Jitendra Zaa
 
Designing Custom REST and SOAP Interfaces on Force.com
Salesforce Developers
 
Elevate Tel Aviv
sready
 
The Power of Salesforce APIs World Tour Edition
Peter Chittum
 
Designing custom REST and SOAP interfaces on Force.com
Steven Herod
 
Mastering-Salesforce-Development-A-Comprehensive-Overview (1).pptx
Anupama Kate
 
Salesforce Campus Tour - Developer Advanced
James Ward
 
Building towards a Composite API Framework in Salesforce
Salesforce Developers
 
SalesForce WebServices part 2
Mindfire Solutions
 
February 2020 Salesforce API Review
Lydon Bergin
 
Boxcars and Cabooses: When one more XHR is too much - Peter Chittum - Codemot...
Codemotion
 
All Aboard the Boxcar! Going Beyond the Basics of REST
Pat Patterson
 
REST API: Do More in the Feed with Action Links
Salesforce Developers
 
Secure Development on the Salesforce Platform - Part I
Salesforce Developers
 
Introduction to Apex for Developers
Salesforce Developers
 
Salesforce Integration
Er. Prashant Veer Singh
 
Salesforce Campus Tour - Developer Intro
James Ward
 
Ad

More from Salesforce Developers (20)

PDF
Sample Gallery: Reference Code and Best Practices for Salesforce Developers
Salesforce Developers
 
PDF
Maximizing Salesforce Lightning Experience and Lightning Component Performance
Salesforce Developers
 
PDF
Local development with Open Source Base Components
Salesforce Developers
 
PPTX
TrailheaDX India : Developer Highlights
Salesforce Developers
 
PDF
Why developers shouldn’t miss TrailheaDX India
Salesforce Developers
 
PPTX
CodeLive: Build Lightning Web Components faster with Local Development
Salesforce Developers
 
PPTX
CodeLive: Converting Aura Components to Lightning Web Components
Salesforce Developers
 
PPTX
Enterprise-grade UI with open source Lightning Web Components
Salesforce Developers
 
PPTX
TrailheaDX and Summer '19: Developer Highlights
Salesforce Developers
 
PDF
Live coding with LWC
Salesforce Developers
 
PDF
Lightning web components - Episode 4 : Security and Testing
Salesforce Developers
 
PDF
LWC Episode 3- Component Communication and Aura Interoperability
Salesforce Developers
 
PDF
Lightning web components episode 2- work with salesforce data
Salesforce Developers
 
PDF
Lightning web components - Episode 1 - An Introduction
Salesforce Developers
 
PDF
Migrating CPQ to Advanced Calculator and JSQCP
Salesforce Developers
 
PDF
Scale with Large Data Volumes and Big Objects in Salesforce
Salesforce Developers
 
PDF
Replicate Salesforce Data in Real Time with Change Data Capture
Salesforce Developers
 
PDF
Modern Development with Salesforce DX
Salesforce Developers
 
PDF
Get Into Lightning Flow Development
Salesforce Developers
 
PDF
Integrate CMS Content Into Lightning Communities with CMS Connect
Salesforce Developers
 
Sample Gallery: Reference Code and Best Practices for Salesforce Developers
Salesforce Developers
 
Maximizing Salesforce Lightning Experience and Lightning Component Performance
Salesforce Developers
 
Local development with Open Source Base Components
Salesforce Developers
 
TrailheaDX India : Developer Highlights
Salesforce Developers
 
Why developers shouldn’t miss TrailheaDX India
Salesforce Developers
 
CodeLive: Build Lightning Web Components faster with Local Development
Salesforce Developers
 
CodeLive: Converting Aura Components to Lightning Web Components
Salesforce Developers
 
Enterprise-grade UI with open source Lightning Web Components
Salesforce Developers
 
TrailheaDX and Summer '19: Developer Highlights
Salesforce Developers
 
Live coding with LWC
Salesforce Developers
 
Lightning web components - Episode 4 : Security and Testing
Salesforce Developers
 
LWC Episode 3- Component Communication and Aura Interoperability
Salesforce Developers
 
Lightning web components episode 2- work with salesforce data
Salesforce Developers
 
Lightning web components - Episode 1 - An Introduction
Salesforce Developers
 
Migrating CPQ to Advanced Calculator and JSQCP
Salesforce Developers
 
Scale with Large Data Volumes and Big Objects in Salesforce
Salesforce Developers
 
Replicate Salesforce Data in Real Time with Change Data Capture
Salesforce Developers
 
Modern Development with Salesforce DX
Salesforce Developers
 
Get Into Lightning Flow Development
Salesforce Developers
 
Integrate CMS Content Into Lightning Communities with CMS Connect
Salesforce Developers
 

Recently uploaded (20)

PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 

Getting Started With Apex REST Services

  • 1. Getting Started with Apex REST Services Matthew Lamb, Appirio, Technical Architect @SFDCMatt
  • 2. Safe Harbor Safe harbor statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services. The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of any litigation, risks associated with completed and any possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most recent fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor Information section of our Web site. Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
  • 5. Session Objectives == ▪ Briefly define, what is a REST service? ▪ How to create custom REST services in Apex ▪ How to call those custom REST services ▪ Tips-and-Tricks / Do’s and Don’ts / Code Sample
  • 6. Session Objectives != ▪ SOAP ▪ Web service design patterns / philosophies ▪ Security relevant to a public API ▪ Programmatic authentication into Salesforce
  • 7. By a show of hands… ▪ Apex SOAP web services ▪ RESTful web service protocols ▪ Native REST API • Know about it? • Used it?
  • 8. What is REST? ▪ Representational State Transfer ▪ REST is: • An architecture style, not a protocol • HTTP-based • Client-server • Stateless
  • 9. What is REST? ▪ Uses standard HTTP methods, sent to an endpoint • POST, GET, DELETE, PUT, PATCH • https://na10.salesforce.com/services/apexrest/myaccountservice/ ▪ Receive a response payload and a status in return • JSON or XML • 200 (OK), 404 (Not Found), etc -> bit.ly/responsecodes ▪ Commonly, HTTP verbs are mapped to CRUD operations • POST = Create GET = Read DELETE = Delete PUT/PATCH = Update
  • 10. Why Use Apex REST? ▪ All sObjects, standard or custom, come with a REST API ▪ Apex REST used for defining custom interactions ▪ Good for abstracting complex interactions to a single call • Inserting / updating multiple objects • Callouts to external systems • Custom search interfaces
  • 11. Apex REST Basics ▪ All custom Apex REST services are accessed in the same namespace • /services/apexrest/ • https://na15.salesforce.com/services/apexrest/<custom_path> https://na10.salesforce.com/services/apexrest/v1/joborders Base URL (your org) Apex REST Namespace Your custom path
  • 12. Apex REST Basics ▪ If you know Apex… ▪ @RestResource(urlMapping=‘/<custom_path>/*’) • Class level annotation to define a Global Class as an Apex REST service • custom_path is a customizable URL you define for your end point ▪ @HttpPost, @HttpGet, @HttpDelete, @HttpPut, @HttpPatch • Method level annotations to map HTTP methods functionality
  • 13. Apex REST Basics ▪ RestContext class • Container class for the RestRequest and RestResponse objects • bit.ly/RestContext ▪ RestRequest and RestResponse • Aptly named classes instantiated for each call to an Apex REST endpoint • bit.ly/RestRequest • bit.ly/RestResponse
  • 14. Apex REST Basics ▪ RestRequest • Provides access to all aspects of the request • Inbound requests are automatically deserialized into a RestRequest instance • headers, httpMethod, params, remoteAddress, requestBody, requestURI, resourcePath ▪ RestResponse • Provides access to all aspects of the response • statusCode, responseBody, headers • Method return value is automatically serialized into the reponseBody
  • 15. A Simple Apex REST Service ▪ REST_AccountService_V1 • Given an Account External Id, return a few details about the Account • Endpoint is /v1/accounts/*, which means the service is at: – https://na15.salesforce.com/services/apexrest/v1/accounts/ • @HttpGet method will take in an Account Id and return several data points about that Account
  • 16. Calling our simple Apex REST service ▪ GET @ /services/apexrest/v1/accounts/1006 • Success! • https://na15.salesforce.com/services/apexrest/v1/accounts/1006 • JSON or XML • Changes available in real time ▪ GET @ /services/apexrest/v1/accounts/6654 • Fail! • Error handling
  • 17. We can make him better than he was ▪ REST_AccountService_V2 • Success! • Automatic serialization FTW! – Apex primitives (excluding Blob) – sObjects – Lists or maps (with String keys) of Apex primitives or sObjects – User-defined types that contain member variables of the types listed above
  • 18. Operating on the resource and its entities ▪ So far we’ve been operating only on specific entities • /v2/accounts/1003 ▪ REST_AccountService_V3 • Maintain existing record lookup via foreign key – /v3/accounts/1023 • Query string provides search capabilities – /v3/accounts?Name=United
  • 19. We GET it, what’s next? ▪ POST, PUT, PATCH, DELETE Resource accounts/ accounts/1147 GET POST PUT/PATCH DELETE Search Accounts Create a new Account Error Error Retrieve a specific Account Error Update a specific Account Remove a specific Account ▪ Verbs -> CRUD is oversimplifying it a bit • bit.ly/PutOrPost
  • 20. Let’s try POST on for size ▪ REST_AccountService_V4 • Should feel familiar • Request body is required for POST • Parameters map to method signature • Same error handling principles apply ▪ Method definition strictly defines what can be passed • Might be great for your use case, might not • If you need more flexibility…
  • 21. Several more flexible ways to allow input ▪ REST_AccountService_V5 • Your POST (or PUT or PATCH) method can take sObjects • If you include a valid field, it’ll be deserialized into the sObject instance ▪ REST_AccountService_V6 • You could also take Lists of sObjects! ▪ REST_AccountService_v7 • Or even wrapper classes!
  • 22. What’s next? ▪ PUT / PATCH / DELETE ▪ Similar to what you’ve seen today ▪ Write test coverage ▪ Download all the code ▪ http://github.com/sfdcmatt/DF13ApexRest
  • 24. We want to hear from YOU! Please take a moment to complete our session survey Surveys can be found in the “My Agenda” portion of the Dreamforce app