agentleFS
jiten-singh-shahijiten-singh-shahi/salesforce-claude-code/.cursor/skills/sf-api-design/SKILL.md

sf-api-design

Skill15 starsChanged 7 months agoMITView on GitHub

Salesforce API design — custom REST endpoints, batch operations, Composite API, error envelopes, auth. Use when designing APIs exposed from Salesforce. Do NOT use for outbound callouts or Platform Events.

The file

We split this skill into the rules it gives an agent

4 rules. About 0 are common, 1 is distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use WITH USER_MODE in SOQL and AccessLevel.USER_MODE in DML

    line 224
  2. Very specific:

    Use Security.stripInaccessible() when you need field-level enforcement on DML -- check getRemovedFields() for critical fields

    line 225
  3. Distinctive:

    Use proper HTTP status codes (200, 201, 400, 404, 500)

    line 227
  4. Very specific:

    Use Database.insert(records, false) for bulk APIs to support partial success

    line 230

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Salesforce API Design

Patterns for designing and implementing custom APIs on the Salesforce platform. Callout limits, Composite API limits, and Named Credential details live in the reference file.

@../_reference/INTEGRATION_PATTERNS.md

When to Use

  • Designing custom REST or SOAP APIs exposed from Salesforce using Apex
  • Establishing consistent API response envelopes and error handling patterns
  • Configuring authentication for inbound API access
  • Building batch REST endpoints for bulk operations
  • Reviewing Apex API code for security (CRUD/FLS, input validation, status codes)

Custom REST API Pattern

@RestResource(urlMapping='/api/accounts/*')
global with sharing class AccountAPI {

    @HttpGet
    global static void getAccount() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;

        String accountId = req.requestURI.substringAfterLast('/');

        try {
            Account acc = [
                SELECT Id, Name, Industry, AnnualRevenue
                FROM Account WHERE Id = :accountId
                WITH USER_MODE LIMIT 1
            ];

            res.statusCode = 200;
            res.responseBody = Blob.valueOf(JSON.serialize(
                new ApiResponse(true, acc, null)));
        } catch (QueryException e) {
            res.statusCode = 404;
            res.responseBody = Blob.valueOf(JSON.serialize(
                new ApiResponse(false, null, 'Account not found')));
        } catch (Exception e) {
            res.statusCode = 500;
            res.responseBody = Blob.valueOf(JSON.serialize(
                new ApiResponse(false, null, 'An internal error occurred')));
        }
    }

    @HttpPost
    global static void createAccount() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;

        try {
            Object parsed = JSON.deserializeUntyped(req.requestBody.toString());
            if (!(parsed instanceof Map<String, Object>)) {
                res.statusCode = 400;
                res.responseBody = Blob.valueOf(JSON.serialize(
                    new ApiResponse(false, null,
                        'Expected JSON object, got ' +
                        (parsed instanceof List<Object> ? 'array' : 'primitive')
                    )));
                return;
            }
            Map<String, Object> body = (Map<String, Object>) parsed;
            Account acc = new Account(
                Name = (String) body.get('name'),
                Industry = (String) body.get('industry')
            );

            // stripInaccessible — check getRemovedFields() to avoid silent data loss
            SObjectAccessDecision decision = Security.stripInaccessible(
                AccessType.CREATABLE, new List<Account>{acc});
            if (!decision.getRemovedFields().isEmpty()) {
                res.statusCode = 403;
                res.responseBody = Blob.valueOf(JSON.serialize(
                    new ApiResponse(false, null,
                        'Insufficient field permissions for: ' +
                        decision.getRemovedFields())));
                return;
            }
            insert decision.getRecords();

            res.statusCode = 201;
            res.responseBody = Blob.valueOf(JSON.serialize(
                new ApiResponse(true, decision.getRecords()[0], null)));
        } catch (Exception e) {
            res.statusCode = 400;
            res.responseBody = Blob.valueOf(JSON.serialize(
                new ApiResponse(false, null, e.getMessage())));
        }
    }

    global class ApiResponse {
        public Boolean success;
        public Object data;
        public String error;

        public ApiResponse(Boolean success, Object data, String error) {
            this.success = success;
            this.data = data;
            this.error = error;
        }
    }
}

Batch REST Endpoint Pattern

@HttpPost
global static void bulkCreate() {
    RestRequest req = RestContext.request;
    RestResponse res = RestContext.response;

    try {
        List<Object> items = (List<Object>) JSON.deserializeUntyped(
            req.requestBody.toString());
        List<Account> accounts = new List<Account>();

        for (Object item : items) {
            Map<String, Object> fields = (Map<String, Object>) item;
            accounts.add(new Account(
                Name = (String) fields.get('name'),
                Industry = (String) fields.get('industry')
            ));
        }

        SObjectAccessDecision decision = Security.stripInaccessible(
            AccessType.CREATABLE, accounts);
        List<Database.SaveResult> results =
            Database.insert(decision.getRecords(), false);

        List<Object> response = new List<Object>();
        for (Integer i = 0; i < results.size(); i++) {
            Map<String, Object> row = new Map<String, Object>();
            row.put('index', i);
            row.put('success', results[i].isSuccess());
            row.put('id', results[i].isSuccess() ? results[i].getId() : null);
            if (!results[i].isSuccess()) {
                row.put('errors', results[i].getErrors()[0].getMessage());
            }
            response.add(row);
        }

        res.statusCode = 200;
        res.responseBody = Blob.valueOf(JSON.serialize(
            new ApiResponse(true, response, null)));
    } catch (Exception e) {
        res.statusCode = 400;
        res.responseBody = Blob.valueOf(JSON.serialize(
            new ApiResponse(false, null, e.getMessage())));
    }
}

Error Handling Patterns

Structured error codes for API consumers:

global class ApiError {
    public String code;
    public String message;
    public String field;

    public ApiError(String code, String message, String field) {
        this.code = code;
        this.message = message;
        this.field = field;
    }
}

// Standard error codes:
// FIELD_REQUIRED     — Missing required field
// RECORD_NOT_FOUND   — Record ID doesn't exist or no access
// GOVERNOR_LIMIT     — Operation would exceed governor limits
// INSUFFICIENT_ACCESS — User lacks CRUD/FLS permission
// VALIDATION_FAILED  — Validation rule or trigger prevented save
// DUPLICATE_VALUE    — Unique field constraint violated

Authentication for Inbound APIs

MethodUse WhenSetup
Named PrincipalAll API users share one Salesforce userConnected App + single auth
Per-UserEach API caller maps to a Salesforce userConnected App + OAuth per user
JWT BearerServer-to-server, no user interactionConnected App + X.509 certificate
API Key (Custom)Simple external toolsCustom Metadata + header validation

Anti-Patterns

Anti-PatternProblemFix
God endpoint (all CRUD in one method)Hard to maintain and testOne method per operation (@HttpGet, @HttpPost)
No paginationTimeouts, governor limitsAdd LIMIT + OFFSET or cursor-based pagination
Exposing internal Salesforce IDsSecurity risk, breaks across orgsUse external IDs or custom identifiers
No error codesConsumers can't programmatically handle errorsReturn structured error codes
No API versioningBreaking changes affect all consumersVersion via URL path: /api/v1/accounts/
WITHOUT SHARING on API classBypasses record-level securityUse WITH SHARING on REST resources
Returning all fieldsWastes bandwidth, exposes sensitive dataReturn only requested/needed fields

Best Practices

  • Use WITH USER_MODE in SOQL and AccessLevel.USER_MODE in DML
  • Use Security.stripInaccessible() when you need field-level enforcement on DML -- check getRemovedFields() for critical fields
  • Return consistent response envelopes (success, data, error)
  • Use proper HTTP status codes (200, 201, 400, 404, 500)
  • Implement rate limiting awareness (API request limits)
  • Version APIs via URL path (/api/v1/accounts/)
  • Use Database.insert(records, false) for bulk APIs to support partial success

Related

  • Constraints: sf-security-constraints
  • Reference: @../_reference/INTEGRATION_PATTERNS.md

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.