Skip to content

Commit 919a561

Browse files
committed
[Fundamentals] Env variables in API calls
1 parent d7739b4 commit 919a561

File tree

1 file changed

+88
-18
lines changed

1 file changed

+88
-18
lines changed

src/content/docs/fundamentals/api/how-to/make-api-calls.mdx

Lines changed: 88 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,31 @@ sidebar:
55
order: 2
66
---
77

8+
import { TabItem, Tabs } from "~/components";
9+
810
Once you [create your API token](/fundamentals/api/get-started/create-token/), all API requests are authorized in the same way. Cloudflare uses the [RFC standard](https://tools.ietf.org/html/rfc6750#section-2.1) `Authorization: Bearer <API_TOKEN>` interface. An example request is shown below.
911

1012
{/* <!-- The following example uses an invalid API key to demonstrate what those keys look like --> */}
1113

1214
```bash
13-
curl "https://api.cloudflare.com/client/v4/zones/{zone_id}" \
15+
curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID" \
1416
--header "Authorization: Bearer YQSn-xWAQiiEh9qM58wZNnyQS7FUdoqGIUAbrh7T"
1517
```
1618

1719
Never send or store your API token secret in plaintext. Also be sure not to check it into code repositories, especially public ones.
1820

21+
Consider defining [environment variables](#environment-variables) for the zone or account ID, as well as for authentication credentials (for example, the API token).
22+
1923
To format JSON output for readability in the command line, you can use a tool like `jq`, a command-line JSON processor. For more information on obtaining and installing `jq`, refer to [Download jq](https://stedolan.github.io/jq/download/).
2024

2125
The following example will format the curl JSON output using `jq`:
2226

2327
```bash
24-
curl "https://api.cloudflare.com/client/v4/zones/{zone_id}" \
25-
--header "Authorization: Bearer <API_TOKEN>" | jq .
28+
curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID" \
29+
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq .
2630
```
2731

28-
## Using Cloudflares APIs
32+
## Using Cloudflare's APIs
2933

3034
Every Cloudflare API element is fixed to a version number. The latest version is Version 4. The stable base URL for all Version 4 HTTPS endpoints is: `https://api.cloudflare.com/client/v4/`
3135

@@ -39,14 +43,15 @@ For specific guidance on making API calls, refer to the following resources:
3943

4044
Several Cloudflare endpoints have optional query parameters to filter incoming results, such as [List Zones](/api/resources/zones/methods/list/).
4145

42-
When adding those query parameters, make sure you enclose the URL in quotes `'` (just like the header values), or the API call might error.
46+
When adding those query parameters, make sure you enclose the URL in double quotes `""` (just like the header values), or the API call might error.
4347

44-
```bash "'"
45-
curl 'https://api.cloudflare.com/client/v4/zones?account.id=<ACCOUNT_ID>' \
46-
--header 'Authorization: Bearer <CF_API_TOKEN>' \
47-
--header 'Content-Type: application/json'
48+
```bash '"'
49+
curl "https://api.cloudflare.com/client/v4/zones?account.id=$ACCOUNT_ID" \
50+
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
4851
```
4952

53+
You can enclose strings using either single quotes (`''`) or double quotes (`""`). However, using single quotes prevents variable substitution in shells like `bash`. In the previous example, this would mean that the `$ACCOUNT_ID` and `$CLOUDFLARE_API_TOKEN` [environment variables](#environment-variables) would not be replaced with their values.
54+
5055
### Pagination
5156

5257
Sometimes there will be too many results to display via the default page size, for example you might receive the following:
@@ -63,7 +68,7 @@ There are two query parameter options, which can be combined to paginate across
6368
- `page=x` enables you to select a specific page.
6469
- `per_page=xx` enables you to adjust the number of results displayed on a page. If you select too many, you may get a timeout.
6570

66-
An example might be `https://api.cloudflare.com/client/v4/zones/zone-identifier/dns_records?per_page=100&page=2`.
71+
An example might be `https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?per_page=100&page=2`.
6772

6873
Other options are:
6974

@@ -78,7 +83,7 @@ Recent versions of Windows 10 and 11 [already include the curl tool](https://cur
7883

7984
### Using a Command Prompt window
8085

81-
To use the Cloudflare API with curl on a Command Prompt window, you must use double quotes (`"`) as string delimiters instead of single quotes (`'`).
86+
To use the Cloudflare API with curl on a Command Prompt window, you must use double quotes (`"`) as string delimiters.
8287

8388
A typical `PATCH` request will be similar to the following:
8489

@@ -110,10 +115,10 @@ PowerShell has specific cmdlets (`Invoke-RestMethod` and `ConvertFrom-Json`) for
110115
The following example uses the `Invoke-RestMethod` cmdlet:
111116

112117
```powershell
113-
Invoke-RestMethod -URI 'https://api.cloudflare.com/client/v4/zones/{zone_id}/ssl/certificate_packs?ssl_status=all' -Method 'GET' -ContentType 'application/json' -Headers @{'X-Auth-Email'='<EMAIL>';'X-Auth-Key'='<API_KEY>'}
118+
Invoke-RestMethod -URI "https://api.cloudflare.com/client/v4/zones/$Env:ZONE_ID/ssl/certificate_packs?ssl_status=all" -Method 'GET' -ContentType 'application/json' -Headers @{'X-Auth-Email'=$Env:CLOUDFLARE_EMAIL;'X-Auth-Key'=$Env:CLOUDFLARE_API_KEY}
114119
```
115120

116-
```txt title="Example output"
121+
```txt output
117122
result : {@{id=78411cfa-5727-4dc1-8d4a-773d01f17c7c; type=universal; hosts=System.Object[];
118123
primary_certificate=c173c8a1-9724-4e96-a748-2c4494186098; status=active; certificates=System.Object[];
119124
created_on=2022-12-09T23:11:06.010263Z; validity_days=90; validation_method=txt;
@@ -124,13 +129,15 @@ errors : {}
124129
messages : {}
125130
```
126131

132+
The command assumes that the environment variables `ZONE_ID`, `CLOUDFLARE_EMAIL`, and `CLOUDFLARE_API_KEY` have been previously defined. For more information, refer to [Environment variables](#environment-variables).
133+
127134
By default, the output will only contain the first level of the JSON object hierarchy (in the above example, the content of objects such as `hosts` and `certificates` is not shown). To show additional levels and format the output like the `jq` tool, you can use the `ConvertFrom-Json` cmdlet specifying the desired maximum depth (by default, `2`):
128135

129136
```powershell
130-
Invoke-RestMethod -URI 'https://api.cloudflare.com/client/v4/zones/{zone_id}/ssl/certificate_packs?ssl_status=all' -Method 'GET' -ContentType 'application/json' -Headers @{'X-Auth-Email'='<EMAIL>';'X-Auth-Key'='<API_KEY>'} | ConvertTo-Json -Depth 5
137+
Invoke-RestMethod -URI "https://api.cloudflare.com/client/v4/zones/$Env:ZONE_ID/ssl/certificate_packs?ssl_status=all" -Method 'GET' -Headers @{'X-Auth-Email'=$Env:CLOUDFLARE_EMAIL;'X-Auth-Key'=$Env:CLOUDFLARE_API_KEY} | ConvertTo-Json -Depth 5
131138
```
132139

133-
```json title="Example output"
140+
```json output
134141
{
135142
"result": [
136143
{
@@ -174,7 +181,7 @@ You can also use the curl tool in PowerShell. However, in PowerShell `curl` is a
174181
A typical `PATCH` request with curl will be similar to the following:
175182

176183
```powershell
177-
curl.exe --request PATCH "https://api.cloudflare.com/client/v4/user/invites/{id}" --header "Authorization: Bearer <API_TOKEN>" --data '{\"status\": \"accepted\"}'
184+
curl.exe --request PATCH "https://api.cloudflare.com/client/v4/user/invites/{id}" --header "Authorization: Bearer $Env:CLOUDFLARE_API_TOKEN" --data '{\"status\": \"accepted\"}'
178185
```
179186

180187
To escape a double quote (`"`) character in a request body (specified with `-d` or `--data`), prepend it with another double quote (`"`) or a backslash (`\`). You must escape double quotes even when using single quotes (`'`) as string delimiters.
@@ -184,7 +191,70 @@ To break a single command in two or more lines, use a backtick (`` ` ``) charact
184191
```powershell
185192
curl.exe --request PATCH `
186193
"https://api.cloudflare.com/client/v4/user/invites/{id}" `
187-
--header "X-Auth-Email: <EMAIL>" `
188-
--header "X-Auth-Key: <API_KEY>" `
194+
--header "X-Auth-Email: $Env:CLOUDFLARE_EMAIL" `
195+
--header "X-Auth-Key: $Env:CLOUDFLARE_API_KEY" `
189196
--data '{\"status\": \"accepted\"}'
190197
```
198+
199+
## Environment variables
200+
201+
You can define environment variables for values that repeat between curl commands, such as the zone or account ID. The lifetime of an environment variable can be the current shell session, all future sessions of the current user, or even all future sessions of all users on the machine you are defining them.
202+
203+
You can also use environment variables for keeping authentication credentials (API token, API key, and email) for reuse in different commands. However, make sure you define these values in the smallest possible scope (either the current shell session only or all new sessions for the current user).
204+
205+
The procedure for setting environment variables depends on your platform and shell.
206+
207+
<Tabs> <TabItem label="Linux and macOS">
208+
209+
To define two environment variables for the current shell session, run the following commands:
210+
211+
```sh
212+
export ZONE_ID='f2ea6707005a4da1af1b431202e96ac5'
213+
export CLOUDFLARE_API_TOKEN='<API_TOKEN>'
214+
```
215+
216+
When referencing the variable in curl commands, add a `$` prefix to the variable name (for example, `$ZONE_ID`). Make sure that the full string referencing the variable is either unquoted or enclosed in double quotes (`""`).
217+
218+
To define an environment variable for all new shell sessions for the current user, add the command above at the end of your shell configuration file (for example, `~/.bashrc` for the `bash` shell and `~/.zshrc` for the `zsh` shell).
219+
220+
</TabItem> <TabItem label="PowerShell">
221+
222+
To define two environment variables named `ZONE_ID` and `CLOUDFLARE_API_TOKEN` for the current PowerShell session, run the following commands:
223+
224+
```powershell
225+
$Env:ZONE_ID='f2ea6707005a4da1af1b431202e96ac5'
226+
$Env:CLOUDFLARE_API_TOKEN='<API_TOKEN>'
227+
```
228+
229+
When referencing the variable in curl commands, add a `$Env:` prefix to the variable name (for example, `$Env:ZONE_ID`). Make sure that the full string referencing the variable is either unquoted or enclosed in double quotes (`""`).
230+
231+
To define an environment variable for all new PowerShell sessions of the current user, set the variable in your PowerShell profile. You can get the path to your PowerShell profile by running `echo $PROFILE`.
232+
233+
Alternatively, set the variable for all new PowerShell sessions of the current user using the `SetEnvironmentVariable()` method of the `System.Environment` class. For example:
234+
235+
```powershell
236+
[Environment]::SetEnvironmentVariable("ZONE_ID", "f2ea6707005a4da1af1b431202e96ac5", "User")
237+
```
238+
239+
Running this command will not affect the current session. You will need to close and start a new PowerShell session.
240+
241+
</TabItem> <TabItem label="Windows Command Prompt">
242+
243+
To define a two environment variables for the current Command Prompt session, run the following commands:
244+
245+
```txt
246+
C:\>set ZONE_ID=f2ea6707005a4da1af1b431202e96ac5
247+
C:\>set CLOUDFLARE_API_TOKEN=<API_TOKEN>
248+
```
249+
250+
When referencing a variable in curl commands, enclose the variable name in `%` characters (for example, `%ZONE_ID%`).
251+
252+
To define an environment variable for all future Command Prompt sessions of the current user, run the following command:
253+
254+
```txt
255+
C:\>setx ZONE_ID f2ea6707005a4da1af1b431202e96ac5
256+
```
257+
258+
Running this command will not affect the current window. You will need to either run the `set` command or close and start a new Command Prompt window.
259+
260+
</TabItem> </Tabs>

0 commit comments

Comments
 (0)