Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
INSERT INTO sqlpage_functions (
"name",
"introduced_in_version",
"icon",
"description_md"
)
VALUES (
'fetch',
'0.20.3',
'transfer-vertical',
'Sends an HTTP request and returns the results as a string.
---
icon: transfer-vertical
since: 0.20.3
category: external-services
summary: Send an HTTP request and read the response body.
parameters:
- name: url
type: TEXT
required: true
description: Either a string containing an URL to request, or a json object in the standard format of the
request interface of the web fetch API.
---

Sends an HTTP request and returns the results as a string.

## HTTP request examples

Expand All @@ -21,55 +24,55 @@ We use the simplest form of the fetch function, that takes the URL to fetch as a


```sql
set url = ''https://nominatim.openstreetmap.org/search?format=json&q='' || sqlpage.url_encode($user_search);
set url = 'https://nominatim.openstreetmap.org/search?format=json&q=' || sqlpage.url_encode($user_search);
set api_results = sqlpage.fetch($url);

select ''map'' as component;
select 'map' as component;
select $user_search as title,
CAST($api_results->>0->>''lat'' AS FLOAT) as latitude,
CAST($api_results->>0->>''lon'' AS FLOAT) as longitude;
CAST($api_results->>0->>'lat' AS FLOAT) as latitude,
CAST($api_results->>0->>'lon' AS FLOAT) as longitude;
```

### POST query with a body

In this example, we use the complex form of the function to make an
authenticated POST request, with custom request headers and a custom request body.

We use SQLite''s json functions to build the request body.
We use SQLite's json functions to build the request body.
See [the list of SQL databases and their JSON functions](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) for
more information on how to build JSON objects in your database.

```sql
set request = json_object(
''method'', ''POST'',
''url'', ''https://postman-echo.com/post'',
''headers'', json_object(
''Content-Type'', ''application/json'',
''Authorization'', ''Bearer '' || sqlpage.environment_variable(''MY_API_TOKEN'')
'method', 'POST',
'url', 'https://postman-echo.com/post',
'headers', json_object(
'Content-Type', 'application/json',
'Authorization', 'Bearer ' || sqlpage.environment_variable('MY_API_TOKEN')
),
''body'', json_object(
''Hello'', ''world''
'body', json_object(
'Hello', 'world'
)
);
set api_results = sqlpage.fetch($request);

select ''code'' as component;
select 'code' as component;
select
''API call results'' as title,
''json'' as language,
'API call results' as title,
'json' as language,
$api_results as contents;
```


### Authenticated request using Basic Auth

Here''s how to make a request to an API that requires [HTTP Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication):
Here's how to make a request to an API that requires [HTTP Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication):

```sql
set request = json_object(
''url'', ''https://api.example.com/data'',
''username'', ''my_username'',
''password'', ''my_password''
'url', 'https://api.example.com/data',
'username', 'my_username',
'password', 'my_password'
);
set api_results = sqlpage.fetch($request);
```
Expand Down Expand Up @@ -100,7 +103,7 @@ Use it to skip the request when the value is already cached:

```sql
set current_field_value = (select field from my_table where id = 1);
set target_url = case when $current_field_value is null then ''https://example.com/api/field/1'' end;
set target_url = case when $current_field_value is null then 'https://example.com/api/field/1' end;
set api_value = sqlpage.fetch($target_url);
update my_table set field = $api_value where id = 1 and field is null and $api_value is not null;
```
Expand All @@ -123,19 +126,3 @@ If the query returns more than one row or more than one column, SQLPage returns

If you need to handle errors or inspect the response headers or the status code,
use [`sqlpage.fetch_with_meta`](?function=fetch_with_meta).
'
);
INSERT INTO sqlpage_function_parameters (
"function",
"index",
"name",
"description_md",
"type"
)
VALUES (
'fetch',
1,
'url',
'Either a string containing an URL to request, or a json object in the standard format of the request interface of the web fetch API.',
'TEXT'
);
83 changes: 83 additions & 0 deletions examples/official-site/content/functions/fetch_with_meta.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
---
icon: transfer-vertical
since: 0.34.0
category: external-services
summary: Send an HTTP request and read its status, headers, and body.
parameters:
- name: url
type: TEXT
required: true
description: Either a string containing an URL to request, or a json object in the standard format of the
request interface of the web fetch API.
---

Sends an HTTP request and returns detailed metadata about the response, including status code, headers, and body.

This function is similar to [`fetch`](?function=fetch), but returns a JSON object containing detailed information about the response.
When the response declares a `content-type` of `application/json`, the parsed body is returned under `json_body`:
```json
{
"status": 200,
"headers": {
"content-type": "application/json",
"content-length": "1234"
},
"json_body": { "name": "ditto" }
}
```

For every other content type, the body is returned as a string under `body`:
```json
{
"status": 200,
"headers": {
"content-type": "text/html",
"content-length": "1234"
},
"body": "<html>...</html>"
}
```

If the request fails or encounters an error (e.g., network issues, invalid UTF-8 response), instead of throwing an error,
the function returns a JSON object with an "error" field containing the error message.

### Example: Basic Usage

```sql
-- Make a request and get detailed response information
set response = sqlpage.fetch_with_meta('https://pokeapi.co/api/v2/pokemon/ditto');

-- redirect the user to an error page if the request failed
select 'redirect' as component, 'error.sql' as link
where
json_extract($response, '$.error') is not null
or json_extract($response, '$.status') != 200;

-- Extract data from the response json body
select 'card' as component;
select
json_extract($response, '$.json_body.name') as title,
json_extract($response, '$.json_body.abilities[0].ability.name') as description;
```

### Example: Advanced Request with Authentication

```sql
set request = json_object(
'method', 'POST',
'url', 'https://sqlpage.free.beeceptor.com',
'headers', json_object(
'Content-Type', 'application/json',
'Authorization', 'Bearer ' || sqlpage.environment_variable('API_TOKEN')
),
'body', json_object(
'key', 'value'
)
);
set response = sqlpage.fetch_with_meta($request);

-- Check response content type
select 'debug' as component, $response as response;
```

The function accepts the same parameters as the [`fetch` function](?function=fetch).
96 changes: 0 additions & 96 deletions examples/official-site/sqlpage/migrations/58_fetch_with_meta.sql

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,6 @@ WITH copy(name, category, summary) AS (VALUES



('fetch', 'external-services', 'Send an HTTP request and read the response body.'),
('fetch_with_meta', 'external-services', 'Send an HTTP request and read its status, headers, and body.'),
('send_mail', 'external-services', 'Send email with optional attachments through an SMTP server.'),

('configuration_directory', 'server-and-runtime', 'Locate the directory for SQLPage configuration and templates.'),
Expand Down
Loading