Apex REST Interview Questions: Build Your Own API (60+ Q&A)

Apex REST Interview Questions with answers on RestResource, HTTP annotations, request and response handling, authentication, versioning and API scenarios.

Updated 17 min read
Apex REST Interview Questions featured image with sample question cards

Apex REST Interview Questions come up whenever a role involves partners or outside systems. Writing the class is simple, and the interesting answers are about the contract you are offering and who can call it.

Last reviewed for the Winter ’27 release (November 2026).

This post covers the questions asked, grouped into the annotations, request and response handling, authentication and access, versioning and design, and scenario questions where a partner integration is failing.

Apex REST Interview Questions diagram showing URL, token, verb and response

Caption: The token decides the user, so your endpoint runs with that user’s permissions.

What Apex REST Interview Questions Cover

Apex REST Interview Questions test whether you treat an endpoint as a public contract. Once a partner calls it, you cannot change the shape without warning them.

Think of it like a shop counter. Securing the endpoint uses the rules in the post on CRUD and FLS, and the OAuth side is covered in OAuth flows. Anything you put on it, somebody will come back for.

Apex REST Interview Questions start with the shape of the class. An Apex REST class exposes methods at a URL under the apexrest path. The platform handles routing, serialisation and authentication, and you handle the logic.

The Annotations

AnnotationWhat it does
RestResourceMarks the class and sets the URL mapping
HttpGetThe method that answers a GET
HttpPostThe method that answers a POST
HttpPutThe method that answers a PUT
HttpPatchThe method that answers a PATCH
HttpDeleteThe method that answers a DELETE

One method per verb, and all of them static, which Apex REST Interview Questions check early. That rule accounts for several Apex REST Interview Questions on its own.

@RestResource(urlMapping='/courses/v1/*')
global with sharing class CourseApi {

    @HttpGet
    global static CourseDto doGet() {
        String courseId = RestContext.request.requestURI.substringAfterLast('/');
        Course__c c = [
            SELECT Id, Name, Fee__c FROM Course__c
            WHERE Id = :courseId WITH USER_MODE LIMIT 1
        ];
        return new CourseDto(c);
    }

    @HttpPost
    global static void doPost(String name, Decimal fee) {
        insert as user new Course__c(Name = name, Fee__c = fee);
        RestContext.response.statusCode = 201;
    }
}

Two details there come up in most Apex REST Interview Questions. The POST parameters are taken from the JSON body by name, and the status code is set on the response rather than returned.

Apex REST vs the Standard REST API

Apex REST Interview Questions comparison with the standard REST API

Caption: Use the platform API for ordinary record access, and write Apex REST for a purpose built contract.

NeedPick
Read and write records normallyStandard REST API
A payload shaped for one partnerApex REST
Several objects saved as one unitApex REST, or the composite resource
Business logic applied on the way inApex REST
Nothing to maintainStandard REST API

The post on Apex REST services covers the implementation, and the post on the REST API with Postman covers the platform API.

Apex REST Interview Questions on the Annotations

Q1: What marks a class as an Apex REST service?

The @RestResource annotation with a urlMapping.

Example: @RestResource(urlMapping=’/courses/*’) global with sharing class CourseApi { … }

Interview tip: write the class signature from memory, with global and with sharing.

Q2: What path does the endpoint live under?

Under /services/apexrest/, followed by your mapping.

Example: https://yourdomain.my.salesforce.com/services/apexrest/courses/a01xx0000000001

Follow-up you may get: Can you include a namespace? Yes, packaged endpoints use /services/apexrest/namespace/…

Q3: Must the class be global?

Yes. The class must be global, and the methods global and static.

That is because outside systems call the endpoint, so it must be visible beyond your namespace.

Q4: How many methods can answer one verb?

One method per HTTP verb in a class, so a second @HttpGet method is a compile error.

If you need several GET behaviours, branch inside the method, or use separate classes with different mappings.

Interview tip: this catches many candidates. Say “one method per verb” clearly.

Q5: What does an asterisk in the mapping do?

It matches anything after that point, which is how you accept an ID in the URL.

Example: urlMapping=’/courses/*’ answers /courses/a01xx0000000001 and /courses/a01xx0000000001/enrolments.

Q6: How do you read that id?

From RestContext.request.requestURI, usually taking the last segment.

Example: String uri = RestContext.request.requestURI; Id courseId = uri.substring(uri.lastIndexOf(‘/’) + 1);

Follow-up you may get: How do you read path parameters better? Split the URI on / and validate each part.

Q7: Can a method name be anything?

Yes. The annotation, like @HttpGet or @HttpPost, decides the verb, not the method name.

Use clear names like getCourse or createEnrolment so the code reads well.

Q8: Which verbs support a request body?

POST, PUT and PATCH.

GET and DELETE take their inputs from the URL and query parameters instead.

Q9: How are POST parameters supplied?

As JSON keys that match the method’s parameter names.

Example: @HttpPost global static Id create(String name, Decimal fee) is called with {“name”: “Apex Basics”, “fee”: 15000}.

Interview tip: mention the null parameter trap right after. It shows experience.

Q10: What happens if a key does not match?

The parameter arrives as null, which looks like a client error but is a naming mismatch.

Check the spelling and case of each key, or accept one wrapper object to make the contract clearer.

Q11: How do you accept a whole JSON object instead?

Take one parameter of your own class type, or read the body from RestContext.request.requestBody and deserialize it.

Example: CourseRequest req = (CourseRequest) JSON.deserialize(RestContext.request.requestBody.toString(), CourseRequest.class);

Follow-up you may get: Can you accept a list of sObjects? Yes, as a parameter of type List<Course__c>.

Q12: Can a method return an sObject?

Yes, but a wrapper class is usually clearer and safer to version.

Returning an sObject exposes field API names, and a rename in Salesforce then breaks the partner.

Interview tip: argue for wrapper classes. It shows you think about contracts.

Q13: When should you build an Apex REST endpoint instead of using the standard REST API?

Build one when the partner needs a custom contract: several objects in one call, business rules applied, or a simpler shape than raw sObjects. For plain record reads and writes, the standard REST API already works and needs no code.

Q14: What is the difference between @HttpPut and @HttpPatch?

By convention, PUT replaces or upserts the whole resource, while PATCH updates only the fields sent. Salesforce lets you implement either way, so document which one your endpoint follows.

Q15: How is the return value serialised?

Automatically into JSON, or XML when the client asks for it.

Salesforce serialises the return value with the same rules as JSON.serialize, so wrapper classes with simple fields give clean JSON.

Apex REST Interview Questions on Requests and Responses

Q16: What is RestContext?

A class that gives you the current request and response, through RestContext.request and RestContext.response.

Use it to read headers, parameters and the body, and to set the status code and response body.

Q17: What does RestRequest hold?

The URI, query parameters, headers, the HTTP method, and the body.

Example: RestContext.request.headers.get(‘X-Correlation-Id’) reads a header the partner sent.

Follow-up you may get: How do you read the HTTP method? RestContext.request.httpMethod.

Q18: How do you read a query parameter?

From the params map on the request.

Example: String level = RestContext.request.params.get(‘level’); for /courses?level=Advanced.

Q19: How do you read a raw body?

From requestBody, which is a Blob; call toString() for text.

Example: String json = RestContext.request.requestBody.toString();

Q20: How do you set a status code?

Set statusCode on RestContext.response.

Example: RestContext.response.statusCode = 201;

Follow-up you may get: How do you add a response header? RestContext.response.addHeader(name, value).

Q21: Which status code suits a successful create?

201 Created.

Each outcome should have a clear status:

SituationStatus code
Record created201
Request worked, data returned200
Worked, nothing to return204
Bad input, failed validation400
Not authenticated401
No access to the resource403
Record not found404
Duplicate or conflict409
Unexpected server failure500

Interview tip: list several codes with meanings. Interviewers like precise answers.

Q22: Which suits a validation failure?

400 Bad Request, with a message explaining what was wrong.

Example: {“errorCode”: “INVALID_FEE”, “message”: “Fee must be greater than zero”} so the partner can fix their data.

Q23: Which suits a missing record?

404 Not Found.

Return it when the ID in the URL matches no record the user can see, with a short body like {“errorCode”: “NOT_FOUND”, “message”: “No course with that ID”}. Do not reveal whether the record exists but is hidden.

Q24: Which suits an unexpected failure?

500, with the details logged on your side, not returned.

The partner gets a short message and a reference ID; your log holds the stack trace.

Q25: How do you return a custom error body?

Set the response body and status code yourself, instead of throwing.

Example: RestContext.response.statusCode = 400; RestContext.response.responseBody = Blob.valueOf(JSON.serialize(new ErrorBody(‘INVALID_FEE’, ‘Fee must be positive’)));

Follow-up you may get: Should errors use a standard shape? Yes, one error format across all endpoints.

Q26: What happens if you let an exception escape?

The platform returns a 500 with a generic message, which rarely helps a partner.

It may also include internal details you do not want to share. Catch errors at the endpoint and return a clean response.

Interview tip: say you catch at the boundary and return clean errors.

Q27: How do you return a file?

Set the response body as a Blob and the Content-Type header.

Example: RestContext.response.addHeader(‘Content-Type’, ‘application/pdf’); RestContext.response.responseBody = pdfBlob;

Q28: How do you support a bulk request?

Accept a list in the body and return one result per item.

Use Database.insert with allOrNone false, and map each SaveResult to an item in the response.

Q29: How do you return a list of records with paging?

Accept limit and an offset or a cursor value as query parameters, return that page plus a nextCursor value, and cap the page size. Keyset paging, like the last Id returned, scales better than OFFSET.

Q30: How do you read headers sent by the partner?

Use RestContext.request.headers.get(‘Header-Name’). A correlation ID header is useful to log, so both sides can trace the same request.

Q31: Why return a result per item?

So one bad record does not fail the whole call, which partners expect.

Example response: [{“ref”: “row-1”, “success”: true, “id”: “a01…”}, {“ref”: “row-2”, “success”: false, “error”: “Fee is required”}]

Apex REST Interview Questions on Authentication and Access

Q32: How is a request authenticated?

With an OAuth access token in the Authorization header, as Bearer plus the token.

The partner gets the token from a connected app or external client app using an OAuth flow.

Follow-up you may get: Can you use a session ID instead? Avoid it; use OAuth tokens.

Q33: Which user does the code run as?

The user the token belongs to.

That user’s licence, permissions and Apex class access decide what the call can do.

Q34: Does that mean sharing applies?

Only if the class declares with sharing. Without a keyword, it ignores the user’s sharing.

Declare with sharing and use user mode queries so the token’s user only sees what they should.

Interview tip: many candidates assume the token’s user means sharing applies. Correct that.

Q35: What else must the user have?

Access to the Apex class, granted through a profile or permission set, plus API Enabled.

Without class access, the call fails even with a valid token.

Q36: What happens without that access?

The call is refused with an error, which is a common first day problem.

Add the class to the integration user’s permission set and try again.

Q37: How do you create a user for an integration?

A dedicated integration user with a tight permission set, ideally on the Salesforce Integration licence with API Only.

It cannot log in to the UI, has only the access the integration needs, and its changes are easy to trace.

Follow-up you may get: What licence is best? The Salesforce Integration user licence, where available.

Q38: Which OAuth flow suits a server to server call?

The client credentials flow, or the JWT bearer flow.

Both work with no person logging in. Client credentials uses a secret; JWT uses a certificate to sign a token.

Interview tip: name both flows and when each fits.

Q39: Can a guest user call an Apex REST endpoint?

Yes, through an Experience Cloud site with guest access set up, but treat it as fully public.

Validate every input, expose only what is safe, and never trust IDs sent by the caller.

Q40: Should you write your own authentication?

No. Use OAuth, which the platform already handles properly.

Home made schemes, like a secret in a query parameter, are easy to leak and fail security reviews.

Q41: How do you protect against abuse?

Validate inputs, cap request sizes, and rely on the org’s API limits and the partner’s own rate limiting.

For heavy partners, agree batch sizes and schedules in the integration contract.

Q42: Should the endpoint run in user mode?

Yes by default, so the token user’s permissions are respected.

Use WITH USER_MODE on queries and AccessLevel.USER_MODE on DML.

Q43: What is the difference between a connected app and an external client app?

Both let outside systems use OAuth with Salesforce. External client apps are the newer model with better packaging and security defaults, and Salesforce is moving new integrations toward them.

Q44: How do you restrict which IPs can call your endpoint?

Set IP restrictions on the integration user’s profile, or the connected app’s policies, so tokens only work from the partner’s network. This adds protection if a token leaks.

Q45: How do you log who called you?

The user id from UserInfo, plus the request id, into your logging object.

Example: Logger.info(‘CourseApi.create’, UserInfo.getUserId(), Request.getCurrent().getRequestId()); so each call can be traced later.

Apex REST Interview Questions on Versioning and Design

Q46: How do you version an Apex REST endpoint?

Put the version in the URL mapping, so a new version is a new class.

Example: /v1/courses/* is CourseApiV1 and /v2/courses/* is CourseApiV2. Both can call the same service class.

Q47: Why not change the existing one?

Partners are already calling it, so a change in shape breaks them without warning.

Keep the old version running until every partner has moved, then retire it on an agreed date.

Q48: What counts as a breaking change?

Removing or renaming a field, changing a type, or changing what a status code means.

ChangeBreaking?
Add an optional response fieldNo, if clients ignore unknown fields
Add an optional request fieldNo
Rename or remove a fieldYes
Change a field’s type, like text to numberYes
Make an optional field requiredYes
Change a status code’s meaningYes

Interview tip: give two examples of breaking changes. It shows real API thinking.

Q49: What is a safe change?

Adding an optional field, as long as clients ignore fields they do not know.

Agree that rule with partners at the start, so you can grow the API without new versions for every small change.

Q50: Why use a wrapper class rather than an sObject?

You control the shape, so a field change inside Salesforce does not leak to partners.

Example: a CourseDto with name, fee and startDate stays the same even if Fee__c is renamed to Price__c.

Q51: How do you document the endpoint?

An OpenAPI description or a shared document, kept with the code in source control.

List each endpoint, its fields, status codes and an example request and response.

Q52: How do you test an endpoint from outside?

With a tool like Postman, using a real token against a sandbox.

Save requests in a collection and share it with the partner, so both sides test the same calls.

Follow-up you may get: How do you get a token in Postman? Use the OAuth 2.0 authorisation type with the connected app’s details.

Q53: How do you test it in Apex?

Build a RestRequest, set it on RestContext, call the method, and assert the response.

Example: RestRequest req = new RestRequest(); req.requestURI = ‘/services/apexrest/courses/’ + c.Id; req.httpMethod = ‘GET’; RestContext.request = req; RestContext.response = new RestResponse(); CourseApi.getCourse(); then assert RestContext.response.statusCode.

Interview tip: write the RestContext setup from memory. It is a common written task.

Q54: Should the endpoint contain business logic?

No. It should validate the input and delegate to a service, which other code can also call.

The endpoint handles HTTP details; the service holds the rules.

Q55: Why does that matter?

The same rule then applies to flows, triggers and the API alike.

If enrolment rules live in EnrollmentService, a partner and an LWC cannot get different results.

Q56: How do you keep a payload small?

Return only the fields the partner needs, and add more in a later version if they ask.

Smaller payloads are faster, use less heap, and expose less data.

Q57: How do you expose an Apex REST endpoint to Agentforce or flows?

You usually do not need to. Put the logic in a service, then expose it with @InvocableMethod for flows and agents, and with the REST class for partners. Each entry point is a thin wrapper.

Q58: How do you limit how many records a partner can send in one call?

Check the list size at the start and return a 400 with a clear message if it is over the agreed maximum, like 200. This keeps each call within governor limits.

Q59: Should you support both JSON and XML?

The platform can, and most teams document JSON only to keep the contract simple.

Document one format and stick to it, so partners know exactly what to send and expect.

Scenario Based Apex REST Interview Questions

Q60: Scenario: a partner gets a 401. What do you check?

The token, its expiry, and whether the connected app is set up correctly.

Also check the user is active and not frozen, and that the connected app’s policies allow that user.

Q61: Scenario: a partner gets a 403 with a valid token. Why?

The user has no access to the Apex class.

Grant the Apex class in the integration user’s permission set, then retry.

Q62: Scenario: a POST parameter is always null. What is wrong?

The JSON key does not match the parameter name.

Match the key exactly, including case, or switch to one wrapper parameter.

Q63: Scenario: one bad record fails a batch of 200. What do you change?

Return a result per record and keep the good ones.

Use Database methods with allOrNone false and return each row’s outcome.

Q64: Scenario: a partner needs a new field. How do you ship it?

Add it as an optional field, or a new version if the shape must change.

Agree in the contract that clients ignore unknown fields, so adding is always safe.

Q65: Scenario: a partner reads a field you renamed in Salesforce. What went wrong?

The endpoint returned an sObject, so the internal change leaked.

Return a wrapper class instead, so internal names never reach the partner.

Q66: Scenario: the endpoint is slow with large payloads. What do you do?

Page the response and cap the request size in the contract.

Also check queries are selective and that the code does not loop over related records per item.

Q67: Scenario: a partner retries and creates duplicates. What do you add?

An idempotency key, checked before the insert.

Interview tip: “idempotency key” is the expected term.

Q68: Scenario: an error returns a stack trace to the partner. What do you fix?

Catch it, log the detail, and return a code and message instead.

Return {“errorCode”: “INTERNAL_ERROR”, “reference”: “log ID”} and keep the stack trace in your logs.

Q69: Scenario: a user sees records they should not through your endpoint. Why?

The class has no sharing keyword, or the query is not in user mode.

Declare with sharing and use user mode queries, then test as the integration user.

Q70: Scenario: the business wants an endpoint built this week for one partner. What do you ask?

Who else will use it, since that decides whether it is a contract or a one off.

Who else will use it, since that decides whether it is a long lived contract or a one off.

Q71: Scenario: a partner says your API is down, but your logs show no calls. What do you check?

Whether their requests reach Salesforce at all: the URL and My Domain, the token, IP restrictions, and the connected app. Ask for the exact response they get, because a 401 or 404 points at different causes.

Q72: Scenario: an endpoint must accept data from a mobile app used by customers. What do you change?

Treat it as public: authenticate customers through Experience Cloud or a proper OAuth flow, validate every field, run with sharing and user mode, limit payload sizes, and never trust IDs the app sends.

Q73: Scenario: an interviewer asks how you would design an endpoint from scratch. What do you say?

Version the URL, use a wrapper payload, validate, delegate to a service, and return per record results.

Version the URL, use a wrapper payload, validate input, delegate to a service, run in user mode, and return clear status codes and errors.

Common Mistakes Candidates Make

  • Returning sObjects, so internal changes reach partners, which Apex REST Interview Questions probe directly
  • Forgetting that the class and methods must be global and static
  • Letting exceptions escape as generic 500 responses
  • Putting business logic in the endpoint rather than a service
  • Forgetting Apex class access for the integration user
  • Changing a live endpoint instead of versioning it

Best Practices to Mention in an Interview

  • Version the URL mapping from the first release
  • Use a wrapper class as the payload contract
  • Validate, then delegate to a service other callers share
  • Set honest status codes and a readable error body
  • Return a result per record for bulk requests
  • Run in user mode, with a dedicated integration user
  • Log the caller, the request id and the outcome

Official Resources

Quick Recap

  • Apex REST Interview Questions treat an endpoint as a public contract
  • The class and methods are global and static, one per verb
  • RestContext gives you the request and the response
  • The token decides the user, and the sharing keyword still matters
  • Version in the URL, and return a wrapper rather than an sObject
  • Bulk requests return a result per record

What Is Next

Coming soon: Platform events interview questions and Change Data Capture.