Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion command-snapshot.json
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
[]
[
{
"alias": [],
"command": "api:request:rest",
"flagAliases": [],
"flagChars": ["H", "S", "X", "i", "o"],
"flags": ["api-version", "body", "flags-dir", "header", "include", "method", "stream-to-file", "target-org"],
"plugin": "@salesforce/plugin-api"
}
]
56 changes: 56 additions & 0 deletions messages/rest.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# summary

Make an authenticated HTTP request to Salesforce REST API and print the response.

# examples

- List information about limits in the org with alias "my-org":

<%= config.bin %> <%= command.id %> 'limits' --target-org my-org

- List all endpoints

<%= config.bin %> <%= command.id %> '/'

- Get the response in XML format by specifying the "Accept" HTTP header:

<%= config.bin %> <%= command.id %> 'limits' --target-org my-org --header 'Accept: application/xml'

- POST to create an Account object

<%= config.bin %> <%= command.id %> 'sobjects/account' --body "{\"Name\" : \"Account from REST API\",\"ShippingCity\" : \"Boise\"}" --method POST

- or with a file 'info.json' containing

```json
{
"Name": "Demo",
"ShippingCity": "Boise"
}
```

<%= config.bin %> <%= command.id %> 'sobjects/account' --body info.json --method POST

- Update object

<%= config.bin %> <%= command.id %> 'sobjects/account/<Account ID>' --body "{\"BillingCity\": \"San Francisco\"}" --method PATCH

# flags.include.summary

Include the HTTP response status and headers in the output.

# flags.method.summary

HTTP method for the request.

# flags.header.summary

HTTP header in "key:value" format.

# flags.stream-to-file.summary

Stream responses to a file.

# flags.body.summary

File to use as the body for the request. Specify "-" to read from standard input; specify "" for an empty body.
15 changes: 11 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,21 @@
"bugs": "https://github.com/forcedotcom/cli/issues",
"dependencies": {
"@oclif/core": "^4",
"@salesforce/core": "^8.2.7",
"@salesforce/core": "^8.4.0",
"@salesforce/kit": "^3.2.1",
"@salesforce/sf-plugins-core": "^11.3.2"
"@salesforce/sf-plugins-core": "^11.3.2",
"ansis": "^3.3.2",
"got": "^13.0.0",
"proxy-agent": "^6.4.0"
},
"devDependencies": {
"@oclif/plugin-command-snapshot": "^5.2.12",
"@salesforce/cli-plugins-testkit": "^5.3.25",
"@salesforce/dev-scripts": "^10.2.9",
"@salesforce/plugin-command-reference": "^3.1.13",
"@salesforce/plugin-command-reference": "^3.1.16",
"eslint-plugin-sf-plugin": "^1.20.4",
"oclif": "^4.14.15",
"nock": "^13.5.4",
"oclif": "^4.14.19",
"ts-node": "^10.9.2",
"typescript": "^5.5.4"
},
Expand Down Expand Up @@ -52,6 +56,9 @@
"@salesforce/plugin-command-reference"
],
"topics": {
"api": {
"description": "commands to send and interact with API calls"
}
},
"flexibleTaxonomy": true
},
Expand Down
146 changes: 146 additions & 0 deletions src/commands/api/request/rest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/*
* Copyright (c) 2023, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { createWriteStream, readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import got from 'got';
import type { AnyJson } from '@salesforce/ts-types';
import { ProxyAgent } from 'proxy-agent';
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { Messages, Org, SFDX_HTTP_HEADERS, SfError } from '@salesforce/core';
import { Args } from '@oclif/core';
import ansis from 'ansis';
import { getHeaders } from '../../../shared/methods.js';

Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-api', 'rest');

export class Rest extends SfCommand<void> {
public static readonly summary = messages.getMessage('summary');
public static readonly examples = messages.getMessages('examples');
public static state = 'beta';
public static enableJsonFlag = false;
public static readonly flags = {
'target-org': Flags.requiredOrg(),
'api-version': Flags.orgApiVersion(),
include: Flags.boolean({
char: 'i',
summary: messages.getMessage('flags.include.summary'),
default: false,
exclusive: ['stream-to-file'],
}),
method: Flags.option({
options: ['GET', 'POST', 'PUT', 'PATCH', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE'] as const,
summary: messages.getMessage('flags.method.summary'),
char: 'X',
default: 'GET',
})(),
header: Flags.string({
summary: messages.getMessage('flags.header.summary'),
helpValue: 'key:value',
char: 'H',
multiple: true,
}),
'stream-to-file': Flags.string({
summary: messages.getMessage('flags.stream-to-file.summary'),
helpValue: 'Example: report.xlsx',
char: 'S',
exclusive: ['include'],
}),
body: Flags.string({
summary: messages.getMessage('flags.body.summary'),
allowStdin: true,
helpValue: 'file',
}),
};

public static args = {
endpoint: Args.string({
description: 'Salesforce API endpoint',
required: true,
}),
};

public async run(): Promise<void> {
const { flags, args } = await this.parse(Rest);

const org = flags['target-org'];
const streamFile = flags['stream-to-file'];
const headers = flags.header ? getHeaders(flags.header) : {};

// replace first '/' to create valid URL
const endpoint = args.endpoint.startsWith('/') ? args.endpoint.replace('/', '') : args.endpoint;
const url = new URL(
`${org.getField<string>(Org.Fields.INSTANCE_URL)}/services/data/v${
flags['api-version'] ?? (await org.retrieveMaxApiVersion())
}/${endpoint}`
);

const body =
flags.method === 'GET'
? undefined
: // if they've passed in a file name, check and read it
existsSync(join(process.cwd(), flags.body ?? ''))
? readFileSync(join(process.cwd(), flags.body ?? ''))
: // otherwise it's a stdin, and we use it directly
flags.body;

await org.refreshAuth();

const options = {
agent: { https: new ProxyAgent() },
method: flags.method,
headers: {
...SFDX_HTTP_HEADERS,
Authorization: `Bearer ${
// we don't care about apiVersion here, just need to get the access token.
// eslint-disable-next-line sf-plugin/get-connection-with-version
org.getConnection().getConnectionOptions().accessToken!
}`,
...headers,
},
body,
throwHttpErrors: false,
followRedirect: false,
};

if (streamFile) {
const responseStream = got.stream(url, options);
const fileStream = createWriteStream(streamFile);
responseStream.pipe(fileStream);

fileStream.on('finish', () => this.log(`File saved to ${streamFile}`));
fileStream.on('error', (error) => {
throw SfError.wrap(error);
});
responseStream.on('error', (error) => {
throw SfError.wrap(error);
});
} else {
const res = await got(url, options);

// Print HTTP response status and headers.
if (flags.include) {
this.log(`HTTP/${res.httpVersion} ${res.statusCode}`);
Object.entries(res.headers).map(([header, value]) => {
this.log(`${ansis.blue.bold(header)}: ${Array.isArray(value) ? value.join(',') : value ?? '<undefined>'}`);
});
}

try {
// Try to pretty-print JSON response.
this.styledJSON(JSON.parse(res.body) as AnyJson);
} catch (err) {
// If response body isn't JSON, just print it to stdout.
this.log(res.body === '' ? `Server responded with an empty body, status code ${res.statusCode}` : res.body);
}

if (res.statusCode >= 400) {
process.exitCode = 1;
}
}
}
}
25 changes: 25 additions & 0 deletions src/shared/methods.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright (c) 2023, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { SfError } from '@salesforce/core';
import type { Headers } from 'got';

export function getHeaders(keyValPair: string[]): Headers {
const headers: { [key: string]: string } = {};

for (const header of keyValPair) {
const [key, ...rest] = header.split(':');
const value = rest.join(':').trim();
if (!key || !value) {
throw new SfError(`Failed to parse HTTP header: "${header}".`, 'Failed To Parse HTTP Header', [
'Make sure the header is in a "key:value" format, e.g. "Accept: application/json"',
]);
}
headers[key] = value;
}

return headers;
}
2 changes: 1 addition & 1 deletion test/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ module.exports = {
rules: {
// Allow assert style expressions. i.e. expect(true).to.be.true
'no-unused-expressions': 'off',

'no-console': 'off',
// It is common for tests to stub out method.

// Return types are defined by the source code. Allows for quick overwrites.
Expand Down
86 changes: 86 additions & 0 deletions test/commands/api/request/rest.nut.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/

import { join } from 'node:path';
import { readFileSync } from 'node:fs';
import * as os from 'node:os';
import { config, expect } from 'chai';
import { execCmd, TestSession } from '@salesforce/cli-plugins-testkit';

config.truncateThreshold = 0;

const skipIfWindows = os.platform() === 'win32' ? describe.skip : describe;

// windows NUTs have been failing with
// URL No Longer Exists</span></td></tr>
// <tr><td>You have attempted to reach a URL that no longer exists on salesforce.com. <br/><br/>
// You may have reached this page after clicking on a direct link into the application. This direct link might be: <br/>
// A bookmark to a particular page, such as a report or view <br/>
// A link to a particular page in the Custom Links section of your Home Tab, or a Custom Link <br/>
// A link to a particular page in your email templates <br/><br/>
//
// seems to be related to clickjack protection - https://help.salesforce.com/s/articleView?id=000387058&type=1
// I've confirmed the 'api request rest' command passes on windows

skipIfWindows('api:request:rest NUT', () => {
let testSession: TestSession;

before(async () => {
testSession = await TestSession.create({
scratchOrgs: [
{
config: 'config/project-scratch-def.json',
setDefault: true,
},
],
project: { gitClone: 'https://github.com/trailheadapps/dreamhouse-lwc' },
devhubAuthStrategy: 'AUTO',
});
});

after(async () => {
await testSession?.clean();
});

describe('std out', () => {
it('get result in json format', () => {
const result = execCmd("api request rest 'limits'").shellOutput.stdout;

// make sure we got a JSON object back
expect(Object.keys(JSON.parse(result) as Record<string, unknown>)).to.have.length;
});

it('should pass headers', () => {
const result = execCmd("api request rest 'limits' -H 'Accept: application/xml'").shellOutput.stdout;

// the headers will change this to xml
expect(result.startsWith('<?xml version="1.0" encoding="UTF-8"?><LimitsSnapshot>')).to.be.true;
});
});

describe('stream-to-file', () => {
it('get result in json format', () => {
const result = execCmd("api request rest 'limits' --stream-to-file out.txt").shellOutput.stdout;

expect(result.trim()).to.equal('File saved to out.txt');

const content = readFileSync(join(testSession.project.dir, 'out.txt'), 'utf-8');
// make sure we got a JSON object back
expect(Object.keys(JSON.parse(content) as Record<string, unknown>)).to.have.length;
});

it('should pass headers', () => {
const result = execCmd("api request rest 'limits' -H 'Accept: application/xml' --stream-to-file out.txt")
.shellOutput.stdout;

expect(result.trim()).to.equal('File saved to out.txt');

const content = readFileSync(join(testSession.project.dir, 'out.txt'), 'utf-8');
expect(content.startsWith('<?xml version="1.0" encoding="UTF-8"?><LimitsSnapshot>')).to.be.true;
});
});
});
Loading
Loading