1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Fetch Data From An Endpoint In SQL as a Postgres TIL

This commit is contained in:
jbranchaud
2025-03-17 17:31:32 -05:00
parent 92d732c769
commit 595ac85f17
2 changed files with 51 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1619 TILs and counting..._
_1620 TILs and counting..._
See some of the other learning resources I work on:
- [Ruby Operator Lookup](https://www.visualmode.dev/ruby-operators)
@@ -838,6 +838,7 @@ If you've learned something here, support my efforts writing daily TILs by
- [Escaping String Literals With Dollar Quoting](postgres/escaping-string-literals-with-dollar-quoting.md)
- [Export Query Results To A CSV](postgres/export-query-results-to-a-csv.md)
- [Extracting Nested JSON Data](postgres/extracting-nested-json-data.md)
- [Fetch Data From An Endpoint In SQL](postgres/fetch-data-from-an-endpoint-in-sql.md)
- [Fetch Specific Number Of Results](postgres/fetch-specific-number-of-results.md)
- [Find Duplicate Records In Table Without Unique Id](postgres/find-duplicate-records-in-table-without-unique-id.md)
- [Find Records That Contain Duplicate Values](postgres/find-records-that-contain-duplicate-values.md)

View File

@@ -0,0 +1,49 @@
# Fetch Data From An Endpoint In SQL
The [`pgsql-http` extension](https://github.com/pramsey/pgsql-http) provides a
variety of functions for allowing PostgreSQL to act as an HTTP client. This is
a bit unorthodox and may not be a good idea in production systems. That said,
it is cool that it is possible. Let's look at an example of it.
First, I've installed the extension on the Docker container running my local
Postgres server.
```bash
$ docker exec -it still-postgres-1 bash
$ apt-get update
$ apt-get install postgres-16-http # I'm running Postgres v16
$ exit
```
Then I'll connect to a `psql` session in that container for the `postgres` database.
```bash
$ docker exec still-postgres-1 psql -U postgres -d postgres
```
Then I enable the extension.
```sql
> create extension if not exists http;
CREATE EXTENSION
```
Now I can point a PostgreSQL statement at a live endpoint like
[https://httpbun.com/ip](https://httpbun.com/ip) which will respond with a
chunk of JSON including the IP address for that project's server. I do this
using `http_get` which makes a `GET` request to the given endpoint. The body is
included in the result set.
```bash
> select content from http_get('http://httpbun.com/ip');
content
-----------------------------
{ +
"origin": "73.75.236.101"+
} +
(1 row)
```