Skip to content

Commit edee013

Browse files
Fix code example generation for optional JSON body
Refactors the generateExamples function to only include Content-Type headers and body parameters in cURL, JavaScript, and PowerShell examples when a request body is present. This prevents unnecessary headers and parameters in generated code samples for endpoints that do not require a body.
1 parent 5d8cfa1 commit edee013

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

docs/api.js

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
11
function generateExamples(endpoint, method, body = null) {
22
let curlBodyString = '';
3+
let curlHeaderString = '';
34
let psBodyString = '';
5+
let psContentTypeString = '';
6+
let psBodyParams = '';
47

58
if (body) {
69
const curlJsonString = JSON.stringify(body).replace(/"/g, '\\"');
710
curlBodyString = ` -d "${curlJsonString}"`;
11+
curlHeaderString = ' -H "Content-Type: application/json"';
812
psBodyString = `-Body (ConvertTo-Json ${JSON.stringify(body)})`;
13+
psContentTypeString = '-ContentType \'application/json\'';
14+
psBodyParams = ' `\n ' + psBodyString + ' `\n ' + psContentTypeString;
915
}
1016

1117
return {
12-
cURL: `curl -u user:pass -H "Content-Type: application/json" -X ${method.trim()} -k https://localhost:47990${endpoint.trim()}${curlBodyString}`,
18+
cURL: `curl -u user:pass${curlHeaderString} -X ${method.trim()} -k https://localhost:47990${endpoint.trim()}${curlBodyString}`,
1319
Python: `import json
1420
import requests
1521
from requests.auth import HTTPBasicAuth
@@ -22,19 +28,18 @@ requests.${method.trim().toLowerCase()}(
2228
JavaScript: `fetch('https://localhost:47990${endpoint.trim()}', {
2329
method: '${method.trim()}',
2430
headers: {
25-
'Authorization': 'Basic ' + btoa('user:pass'),
26-
'Content-Type': 'application/json',
31+
'Authorization': 'Basic ' + btoa('user:pass'),${body ? `\n 'Content-Type': 'application/json',` : ''}
2732
}${body ? `,\n body: JSON.stringify(${JSON.stringify(body)}),` : ''}
2833
})
2934
.then(response => response.json())
3035
.then(data => console.log(data));`,
3136
PowerShell: `Invoke-RestMethod \`
3237
-SkipCertificateCheck \`
33-
-ContentType 'application/json' \`
3438
-Uri 'https://localhost:47990${endpoint.trim()}' \`
3539
-Method ${method.trim()} \`
36-
-Headers @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes('user:pass'))}
37-
${psBodyString}`
40+
-Headers @{
41+
Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes('user:pass'))
42+
}${psBodyParams}`
3843
};
3944
}
4045

0 commit comments

Comments
 (0)