Part 3: Postgrest Service
In the previous section we’ve created the database service and bootstraped it with our entities and user roles. Now it’s time to configure the PostgREST service and tie it up with the DB.
We’ll start by modifying the docker-compose.yml
file and adding the following config under the server
section:
version: '3'
services:
db:
# PostgreSQL database config
server:
image: postgrest/postgrest
ports:
- "3000:3000"
links:
- db:db
environment:
PGRST_DB_URI: postgres://authenticator:password@db:5432/app_db
PGRST_DB_SCHEMA: api
PGRST_DB_ANON_ROLE: api_anon
depends_on:
- db
swagger:
# Swagger OpenAPI config
Let’s go through each of the sections of the postgrest
service.
The server
section specifies which dokcker image to use. We’ll use the default postgrest
image here that runs on linux/Amd64
(remember that Docker is basically linux in a secure sandbox).
The ports
section tell docker-compose
to run postgrest service on port 3000 and map it to localhost’s port# 3000.
The links
section attaches our PostgreSQL DB db
to this postgrest service. This way Postgrest can access the DB securely.
The environment
section is the one where we configure the postgrest service and fine tune it with our needs. The Docker image of postgrest uses these environment variables to configure the service1
PGRST_DB_URI
: specifies the PostgreSQL query string to connect to the DB. We’ll use theauthenticator
role here which has only limited rights on the DB.[^2].PGRST_DB_SCHEMA
: specifies the SQL schema that’s exposed to postgrest. This keeps the DB encapsulated.PGRST_DB_ANON_ROLE
: This is therole
that is used to perform unauthenticated queries. In the previous steps we’ve configured read access to the roleapi_anon
.
The depends_on
section ensures that the postgrest service waits and connects to the db
service.
With these changes, we can now run the service and test the anonymous access to the API! Let’s start the services using docker-compose up
. This will start the DB and the postgrest service. Open another terminal and issue the following curl command.
curl -i -X GET localhost:3000/amenity
This will result in the following output, and we’ll receive a JSON object. This is the same data we inserted in the last step.
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Date: Mon, 02 Mar 2020 20:21:54 GMT
Server: postgrest/6.0.2 (713b214)
Content-Type: application/json; charset=utf-8
Content-Range: 0-0/*
Content-Location: /amenity
[{"amenity_id":3,"amenity_name":"Brandenburger tor","amenity_address":"Pariser Platz, 10117 Berlin","created_on":"2020-03-02T18:28:10.827536+00:00"}]
That’s it! In the next section we’ll secure the API using Authentication from Auth0.