DuckDB Extension
HTTP Client
Make HTTP requests from DuckDB SQL and read the response as JSON. Use it to fetch a small API response or enrich a small set of rows.
On this page
The DuckDB 2.0 build sends requests through DuckDB's HTTP stack: https:// and non-GET requests need httpfs (autoloaded), requests are refused when enable_external_access is false, https:// is never redirected to http://, and http_head returns headers as a JSON object. See Changes in the DuckDB 2.0 release.
Bring a small API response into a SQL query
HTTP Client adds functions for making HTTP requests from DuckDB. A call returns the response status, headers, and body, which you can inspect and parse with SQL before storing or joining the result.
Use it to look up API metadata, inspect an endpoint, or enrich a small set of records. Calls wait for the response and buffer it in memory. Check the status before reading the body, and save responses to a table when later queries should reuse the same data.
Example
Fetch a repository from the GitHub API
This request needs no API key. It returns the HTTP status and repository name; the response body is parsed as JSON before extracting the name.
Tested with DuckDB 1.5.6. Run this example in the DuckDB CLI or a native client.
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://duckdb-extensions.query.farm';
INSTALL http_client FROM query_farm;
LOAD http_client FROM query_farm;
WITH response AS MATERIALIZED (
SELECT http_get(
'https://api.github.com/repos/duckdb/duckdb'
) AS res
)
SELECT
(res->>'status')::INTEGER AS status,
((res->>'body')::JSON)->>'full_name' AS repository
FROM response;
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://haybarn-extensions.query.farm';
INSTALL http_client FROM query_farm;
LOAD http_client FROM query_farm;
WITH response AS MATERIALIZED (
SELECT http_get(
'https://api.github.com/repos/duckdb/duckdb'
) AS res
)
SELECT
(res->>'status')::INTEGER AS status,
((res->>'body')::JSON)->>'full_name' AS repository
FROM response;
INSTALL http_client FROM community;
LOAD http_client;
WITH response AS MATERIALIZED (
SELECT http_get(
'https://api.github.com/repos/duckdb/duckdb'
) AS res
)
SELECT
(res->>'status')::INTEGER AS status,
((res->>'body')::JSON)->>'full_name' AS repository
FROM response;
Expected result
| status | repository |
|---|---|
| 200 | duckdb/duckdb |
The result above assumes a successful request. Check the HTTP status before using the body: GitHub can return an error or rate-limit the request. Calls are synchronous and the response is buffered in memory.
Common tasks
- Send a JSON body Make a POST request with headers and a JSON payload.
- Handle an unsuccessful response Check the status before extracting fields from the body.
- Save a response for later queries Store API results in a table to avoid repeating requests.
- Call an API for each row with VGI An alternative approach using a VGI worker, with a worked example.
Deep Dive
Technical Details
Response handling
Each request returns a JSON object with status, reason, and body (plus the response headers on DuckDB 2.0). The body is a string: cast it to JSON before extracting fields from a JSON response. Check the status first, because an error response may have a different shape from a successful response.
Requests are synchronous and the full response is buffered in memory. Use this extension for small responses and limited numbers of requests. On the DuckDB 2.0 build, DuckDBβs http_timeout and http_retries settings apply and http_client_max_response_size caps the body; request scheduling and rate limiting belong in the calling application.
Architecture
The extension is a thin SQL surface over a synchronous HTTP request. There is no ATTACH, no connection pool and no background fetcher β a small set of HTTP functions:
http_get(url, headers, params)βGETrequest.headersandparamsare optionalMAPs;paramsis appended to the URL as a query string.http_post(url, headers, body)βPOSTwith aJSONbody sent asapplication/json. The body parameter is namedparamson the Haybarn 1.5 build; DuckDB 2.0 calls itbodyand still acceptsparams =>.http_post_form(url, headers, params)βPOSTwithparamsURL-encoded asapplication/x-www-form-urlencoded.http_head(url, headers)βHEADrequest; returns the response headers instead of a body.http_put(url, headers, body)andhttp_delete(url, headers)β DuckDB 2.0 only.
Each call returns a JSON object β {status, reason, body}, plus headers on DuckDB 2.0 β that you extract with DuckDBβs JSON operators. The body is a string; cast it with (body)::JSON if the response is JSON and you want to drill in. A request that gets no response at all does not raise an error: it returns status -1 and the failure message in reason. HTTP error statuses are returned, not raised.
Because the function shape is stable and synchronous, the result of an http_* call composes cleanly into CTEs, lateral joins, and CREATE TABLE AS β anywhere a scalar JSON value is acceptable. The cost is the obvious one: one HTTP call per evaluation, in the order DuckDB chooses to evaluate the scalar.
Every http_* function is registered as VOLATILE, like random(). DuckDB never folds a call with constant arguments at plan time, so SELECT http_post(...)->>'access_token' sends exactly one request. Earlier builds could send such a request twice, which matters for non-idempotent endpoints like OAuth code exchanges and webhooks.
Changes in the DuckDB 2.0 release
The DuckDB 2.0 build replaces the extensionβs own HTTP client with DuckDBβs HTTP stack and closes several security gaps.
- httpfs is required for
https://and for every method except plain-HTTPGET. DuckDB autoloads it when it is installed or installable; otherwise the call fails with a message telling you toINSTALL httpfs; LOAD httpfs;. - Requests are refused when
enable_external_accessis false. https://is never redirected tohttp://β such a redirect raises an error. When a redirect moves to another scheme, host or port, theAuthorization,CookieandProxy-Authorizationheaders you passed are not forwarded. A303(and a301/302answering aPOST) is followed with a body-lessGET, as browsers do;307/308keep the method and body.http_headreturnsheadersas a JSON object instead of a JSON-encoded string.(res->>'headers')::JSONworks on both builds; on 2.0 you can writeres->'headers'->>'content-type'.- Bodies that are not valid UTF-8 are base64-encoded, with
"body_encoding": "base64"in the result, instead of producing invalid JSON. DuckDBβs HTTP client does not decompress responses, so if you sendAccept-Encoding: gzipyourself, a compressed body comes back base64-encoded β leave that header out. - URLs are validated: only
http://andhttps://(a URL without a scheme is still treated ashttp://), a host is required, and spaces or control characters must be percent-encoded.user:password@hostin the URL is sent as basic auth. Header names and values with line breaks are rejected. NULLarguments: aNULLurl still returnsNULL; aNULLheaders,paramsorbodynow means βnoneβ instead of making the resultNULL.
Also new in the DuckDB 2.0 build:
- New functions:
http_putandhttp_delete.headers,paramsandbodyare optional and can be passed by name;http_posttakesbody =>(withparams =>kept as an alias). - DuckDBβs HTTP settings apply:
http_timeout(connect and read timeout, default 30 seconds β earlier builds had a fixed 10-second read timeout and no connect timeout),http_retries(idempotent requests only, neverPOST),http_proxy, and the CA/certificate settings of httpfs. - HTTP secrets: a
bearer_tokenorextra_http_headersstored in an HTTP secret is sent to URLs within the secretβs scope, and looked up again on every redirect hop. - Response headers are included in every result as
headers. - Limits:
SET http_client_max_response_size = <bytes>(default 100 MiB) caps the body β aGETstops reading as soon as it is exceeded β andSET http_client_max_redirects = <n>(default 10;0returns the3xxresponse itself) bounds redirects. Queries can be interrupted between rows and while aGETbody streams in. paramsare percent-encoded and appended with&when the URL already has a query string; fragments (#...) are not sent.
There is no PATCH: DuckDBβs HTTP layer has no PATCH request type.
Securing credentials
Any value passed inline to headers or params ends up in the cached query plan and EXPLAIN output. For Bearer tokens, OAuth client secrets, and other credentials, source them from the environment with getenv and bind them via SET VARIABLE:
SET VARIABLE api_token = getenv('API_TOKEN');
SELECT http_post( 'https://api.example.com/users', headers => MAP{ 'authorization': 'Bearer ' || :api_token, 'content-type': 'application/json' },);getenv resolves at parse time, so the literal credential never appears in any cached query plan or session log. The same pattern works for OAuth client credentials passed to http_post_form β see the Cookbook for that recipe.
On the DuckDB 2.0 build you can keep a bearer token out of your queries entirely with an HTTP secret scoped to the API:
CREATE SECRET api_auth ( TYPE http, BEARER_TOKEN 'your-token', SCOPE 'https://api.example.com/');
SELECT http_get('https://api.example.com/me');Scoping per-row calls
Per-row enrichment is the most common reason to reach for this extension, and the most common reason to regret it. A query like
SELECT u.id, http_get('https://api.example.com/score/' || u.id::VARCHAR) AS rFROM users u;issues one HTTP call per row, sequentially, with no connection reuse exposed at the SQL layer. For ten rows itβs instant; for ten thousand rows itβs slow and very likely rate-limited by the upstream server.
Practical guardrails:
- Pre-aggregate to a small set of distinct keys before joining against the API. If
usershas 100k rows but only 200 unique scores, fetch the 200 unique scores into a CTE first. LIMITaggressively during development to avoid accidentally hammering an endpoint while you iterate.- Cache results into a DuckDB table with
CREATE TABLE ASβ repeat queries hit the cache, not the API. - Sleep is not exposed. If you need rate limiting between calls, run the query in batches from your application layer rather than in one large SQL statement.
For genuinely large fetches, prefer one bulk call that returns many rows over many small per-row calls β most REST APIs offer a list endpoint for that reason.
Compared to alternatives
- shellfs +
curlβ pipecurloutput throughread_csv/read_json. Use shellfs when you need streaming reads of large responses (HTTP Client buffers the whole body), curl-only features (cookies, complex TLS, client certs), or shell-pipeline composition withawk/jq. Use HTTP Client when the response is small and you want the result as a JSON value directly inside aSELECT. - httpserver β the inverse direction: serve DuckDB query results as an HTTP API rather than consume one. Pair them when you want one DuckDB instance to fetch from upstream APIs and another to expose results to downstream consumers.
- Application-layer Python / Node + DuckDB β appropriate when you need retries, parallelism, connection reuse, or any HTTP feature this extension doesnβt expose. The tradeoff is the boilerplate and the round-trip back into SQL.
Reference
Extension Contents
Quick reference to all available functions and settings organized by category.
| Name | Type | Description |
|---|---|---|
|
Configuration
|
||
| http_client_max_redirects | Object type: Setting | How many redirects the http_client functions follow (0 returns the 3xx response) |
| http_client_max_response_size | Object type: Setting | Largest HTTP response body, in bytes, that the http_client functions will accept |
|
Requests
Issue HTTP requests from DuckDB SQL. |
||
| http_delete() | Object type: Scalar function |
New in the DuckDB 2.0 build. Issue an HTTP DELETE request (without a body).
|
| http_get() | Object type: Scalar function |
Issue an HTTP GET against url and return the response as JSON.
|
| http_head() | Object type: Scalar function |
Issue an HTTP HEAD request.
|
| http_post() | Object type: Scalar function |
Issue an HTTP POST with a JSON request body.
|
| http_post_form() | Object type: Scalar function |
Issue an HTTP POST with the params map encoded as application/x-www-form-urlencoded β the body shape used by HTML forms, many older REST APIs, and OAuth 2.0 token endpoints.
|
| http_put() | Object type: Scalar function |
New in the DuckDB 2.0 build. Issue an HTTP PUT with a JSON request body β for REST APIs that create or replace a resource at a known URL.
|
No extension contents match that search.
API Reference
Function Reference
Configuration
Settings
Configure the http client extension behavior using these settings.
http_client_max_redirects
How many redirects the http_client functions follow (0 returns the 3xx response)
10
http_client_max_response_size
Largest HTTP response body, in bytes, that the http_client functions will accept
104857600
Practical Examples
Cookbook
Real-world recipes and patterns for common use cases.
Read the response shape
Every http_* function returns a JSON object with status, reason, and body β plus the response headers as a JSON object on DuckDB 2.0 (http_head returns only status, reason and headers). Pull them out with ->>:
WITH r AS ( SELECT http_get('https://httpbin.org/get') AS res)SELECT (res->>'status')::INT AS status, (res->>'reason') AS reason, res->>'body' AS bodyFROM r;To dive into a JSON response body, cast it on the way out: ((res->>'body')::JSON)->>'$.field'. See http_get for the full signature.
A request that never gets a response β DNS failure, refused connection, TLS error, or a timeout (DuckDBβs http_timeout on the 2.0 build; a fixed 10-second read timeout on earlier builds) β does not raise an error. It returns status -1 with the failure in reason (for example HTTP GET request failed. Connection error.), so check status before trusting body.
GET a JSON API and project a field
SELECT ((http_get('https://api.github.com/repos/duckdb/duckdb')->>'body')::JSON)->>'$.stargazers_count' AS stars;Same pattern for any read endpoint that returns JSON β fetch, cast body to JSON, project with ->>.
POST a JSON body
params becomes the JSON body. Set content-type so the server knows to parse it as JSON:
SELECT http_post( 'https://api.example.com/users', headers => MAP{ 'accept': 'application/json', 'content-type': 'application/json' }, params => MAP{ 'name': 'Alice', });See http_post.
POST as application/x-www-form-urlencoded
For HTML forms, older REST APIs, and most OAuth 2.0 token endpoints. The extension sets the Content-Type for you β you donβt need to put it in headers:
SELECT http_post_form( 'https://oauth.example.com/token', headers => MAP{}, params => MAP{ 'grant_type': 'client_credentials', 'client_id': :client_id, 'client_secret': :client_secret });See http_post_form.
Authorize with a Bearer token from the environment
Source credentials from the environment with getenv and bind them via SET VARIABLE so they donβt leak into cached query plans or EXPLAIN output:
SET VARIABLE api_token = getenv('API_TOKEN');
SELECT http_post( 'https://api.example.com/comments', headers => MAP{ 'authorization': 'Bearer ' || :api_token, 'content-type': 'application/json' }, params => MAP{'body': 'Hello from DuckDB'});Exchange OAuth credentials for an access token
The classic application/x-www-form-urlencoded handshake β followed by a JSON parse on the response body to lift the access token out:
SET VARIABLE client_id = getenv('OAUTH_CLIENT_ID');SET VARIABLE client_secret = getenv('OAUTH_CLIENT_SECRET');
WITH t AS ( SELECT http_post_form( 'https://oauth.example.com/token', headers => MAP{}, params => MAP{ 'grant_type': 'client_credentials', 'client_id': :client_id, 'client_secret': :client_secret } ) AS res)SELECT ((res->>'body')::JSON)->>'$.access_token' AS access_tokenFROM t;Per-row enrichment from a REST API
SELECT u.id, u.email, ((http_get('https://api.example.com/score/' || u.id::VARCHAR)->>'body')::JSON)->>'$.score' AS scoreFROM users uWHERE u.last_seen > now() - INTERVAL 1 HOURLIMIT 100;Practical for tens or hundreds of rows. For thousands, pre-aggregate to distinct keys first or cache the result into a DuckDB table β one HTTP call per row adds up fast.
Cache responses into a table
Hit the API once, query the cache forever after:
CREATE TABLE api_scores ASSELECT u.id, ((http_get('https://api.example.com/score/' || u.id::VARCHAR)->>'body')::JSON)->>'$.score' AS scoreFROM (SELECT DISTINCT id FROM users) u;Re-run this only when you want a refresh. Subsequent joins against api_scores are local and fast.
Conditional logic on the status code
Branch in SQL based on the HTTP status β use CASE on the status field:
WITH r AS ( SELECT http_get('https://api.example.com/things/42') AS res)SELECT CASE (res->>'status')::INT WHEN 200 THEN 'ok' WHEN 404 THEN 'missing' WHEN 429 THEN 'rate-limited' ELSE 'unexpected' END AS outcome, res->>'body' AS bodyFROM r;Liveness check with HEAD
SELECT (http_head('https://httpbin.org/')->>'status')::INT AS status;http_head returns the status and reason like http_get, plus the response headers (lower-cased names) in headers β a JSON object on DuckDB 2.0, a JSON-encoded string on earlier builds, so (res->>'headers')::JSON works on both β but the server skips the body. Useful for βis this URL reachable?β probes before a heavier GET.
Trigger a webhook from a SQL pipeline
End a pipeline by POSTing a summary to a webhook. The call is synchronous, but a failed request does not raise an error: check the returned status (-1 means no response arrived) if the pipeline must know the webhook landed:
SET VARIABLE hook = getenv('WEBHOOK_URL');
SELECT http_post( :hook, headers => MAP{'content-type': 'application/json'}, params => MAP{ 'event': 'pipeline_complete', 'rows': (SELECT count(*)::VARCHAR FROM staging), 'finished': now()::VARCHAR });Update and delete resources (DuckDB 2.0)
http_put and http_delete complete the REST verbs. Read a response header with ->'headers':
SELECT (http_put('https://httpbin.org/put', body => {'name': 'duck'})->>'status')::INT AS put_status, (http_delete('https://httpbin.org/delete')->>'status')::INT AS delete_status, http_get('https://httpbin.org/get')->'headers'->>'content-type' AS content_type;Keep a token in an HTTP secret (DuckDB 2.0)
Requests go through DuckDBβs HTTP stack, so an HTTP secret adds the bearer token to every request within its scope β and never to another host a redirect points at:
CREATE SECRET github_token ( TYPE http, BEARER_TOKEN 'ghp_your_token', SCOPE 'https://api.github.com/');
SELECT (http_get('https://api.github.com/user')->>'status')::INT AS status;Platform Support
Compatibility
Extension availability may vary by platform and DuckDB version. Check below to ensure this extension supports your environment before installation.
Quick Facts
Platforms
DuckDB 2.0.0
- Linux x86_64aarch64
- Linux (musl) Not available
- macOS Apple Silicon
- Windows x86_64
- WASM Not available
Compiled binary sizes
| Platform | Architecture | Size |
|---|---|---|
| Linux | x86_64 | 6.88 MB |
| Linux | aarch64 | 6.51 MB |
| macOS | Apple Silicon | 5.24 MB |
| Windows | x86_64 | 12.18 MB |
Compressed download sizes for the release shown above.
DuckDB & Haybarn
Release calendar- DuckDB v2.0.0 Query.Farm repository Supported
- Haybarn v1.5.6 Built-in community repository Supported
Browser examples use Haybarn-Wasm 2.0.0-rc12.
Checked .