Skip to content

Commit b9a7b2f

Browse files
honzajavorekclaude
andauthored
docs(academy): use fetch and Authorization header in API & client solution (#3288)
Updates the API mode of the "Using the Apify API & JavaScript client" solution: - Uses Node.js's built-in `fetch` instead of `axios`, which the empty JavaScript template doesn't install. Closes #3279. - Sends `APIFY_TOKEN` in an `Authorization: Bearer` header instead of a `token` query parameter, since tokens in URLs tend to end up in logs. Closes #3280. Also fixes a few wording nits on the page along the way. --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent df2f857 commit b9a7b2f

1 file changed

Lines changed: 29 additions & 15 deletions

File tree

‎sources/academy/platform/expert_scraping_with_apify/solutions/using_api_and_client.md‎

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ When asked how to set up the source code, select **Local only**, and wait until
4646

4747
```js
4848
import { Actor } from 'apify';
49-
import axios from 'axios';
5049

5150
await Actor.init();
5251

@@ -98,47 +97,54 @@ const withClient = async () => {
9897

9998
## Calling a task via API {#calling-a-task-via-api}
10099

101-
First, we'll create a function (right under the `withClient()`) function named `withAPI` and instantiate a new variable which represents the API endpoint to run our task:
100+
First, right under `withClient()`, we'll create a function named `withAPI()` and define the API endpoint for running our task:
102101

103102
```js
104103
const withAPI = async () => {
105-
const uri = `https://api.apify.com/v2/actor-tasks/${TASK}/run-sync-get-dataset-items?`;
104+
const uri = `https://api.apify.com/v2/actor-tasks/${TASK}/run-sync-get-dataset-items`;
106105
};
107106
```
108107

109108
To add the query parameters to the URL, we could create a long string literal, plugging in all of our input values. However, there is a much better way: [`URLSearchParams`](https://nodejs.org/api/url.html#new-urlsearchparams). By using `URLSearchParams`, we can add the query parameters in an object:
110109

111110
```js
112111
const withAPI = async () => {
113-
const uri = `https://api.apify.com/v2/actor-tasks/${TASK}/run-sync-get-dataset-items?`;
112+
const uri = `https://api.apify.com/v2/actor-tasks/${TASK}/run-sync-get-dataset-items`;
114113
const url = new URL(uri);
115114

116115
url.search = new URLSearchParams({
117116
memory,
118117
format: 'csv',
119118
limit: maxItems,
120119
fields: fields.join(','),
121-
token: process.env.APIFY_TOKEN,
122120
});
123121
};
124122
```
125123

126-
Finally, let's make a `POST` request to our endpoint. You can use any library you want, but in this example, we'll use [`axios`](https://www.npmjs.com/package/axios). Don't forget to run `npm install axios` if you're going to use this package too!
124+
Finally, let's make a `POST` request to our endpoint. We'll use [`fetch`](https://nodejs.org/api/globals.html#fetch), which is provided by Node.js out of the box.
125+
126+
The request needs to be authenticated with an API token, which is available in the `APIFY_TOKEN` environment variable. We'll send it in the `Authorization` header:
127127

128128
```js
129129
const withAPI = async () => {
130-
const uri = `https://api.apify.com/v2/actor-tasks/${TASK}/run-sync-get-dataset-items?`;
130+
const uri = `https://api.apify.com/v2/actor-tasks/${TASK}/run-sync-get-dataset-items`;
131131
const url = new URL(uri);
132132

133133
url.search = new URLSearchParams({
134134
memory,
135135
format: 'csv',
136136
limit: maxItems,
137137
fields: fields.join(','),
138-
token: process.env.APIFY_TOKEN,
139138
});
140139

141-
const { data } = await axios.post(url.toString());
140+
const response = await fetch(url, {
141+
method: 'POST',
142+
headers: { Authorization: `Bearer ${process.env.APIFY_TOKEN}` },
143+
});
144+
if (!response.ok) {
145+
throw new Error(`Request failed with status ${response.status}: ${await response.text()}`);
146+
}
147+
const data = await response.text();
142148

143149
return Actor.setValue('OUTPUT', data, { contentType: 'text/csv' });
144150
};
@@ -149,8 +155,11 @@ const withAPI = async () => {
149155
Now, since we've written both of these functions, all we have to do is write a conditional statement based on the boolean value from `useClient`:
150156

151157
```js
152-
if (useClient) await withClient();
153-
else await withAPI();
158+
if (useClient) {
159+
await withClient();
160+
} else {
161+
await withAPI();
162+
}
154163
```
155164

156165
And before we push to the platform, let's not forget to write an input schema in the `.actor/input_schema.json` file:
@@ -205,7 +214,6 @@ To ensure we're on the same page, here is what the final code looks like:
205214

206215
```js
207216
import { Actor } from 'apify';
208-
import axios from 'axios';
209217

210218
await Actor.init();
211219

@@ -230,18 +238,24 @@ const withClient = async () => {
230238
};
231239

232240
const withAPI = async () => {
233-
const uri = `https://api.apify.com/v2/actor-tasks/${TASK}/run-sync-get-dataset-items?`;
241+
const uri = `https://api.apify.com/v2/actor-tasks/${TASK}/run-sync-get-dataset-items`;
234242
const url = new URL(uri);
235243

236244
url.search = new URLSearchParams({
237245
memory,
238246
format: 'csv',
239247
limit: maxItems,
240248
fields: fields.join(','),
241-
token: process.env.APIFY_TOKEN,
242249
});
243250

244-
const { data } = await axios.post(url.toString());
251+
const response = await fetch(url, {
252+
method: 'POST',
253+
headers: { Authorization: `Bearer ${process.env.APIFY_TOKEN}` },
254+
});
255+
if (!response.ok) {
256+
throw new Error(`Request failed with status ${response.status}: ${await response.text()}`);
257+
}
258+
const data = await response.text();
245259

246260
return Actor.setValue('OUTPUT', data, { contentType: 'text/csv' });
247261
};

0 commit comments

Comments
 (0)