How to build a distributed backend API with Yugabyte and postREST
Before we jump to the action, I want to present our main actors.
PostgREST is a standalone web server that turns your PostgreSQL database directly into a RESTful API. The structural constraints and permissions in the database determine the API endpoints and operations.
Yugabyte it's a NewSQL database. Combines the strength of both worlds, ACID default support and horizontal scalability. In their words "Modern applications need a cloud-native database that eliminates tradeoffs and silos. The world's leading enterprises are modernizing from Oracle, SQL Server, DB2 and other legacy RDBMSs to YugabyteDB for mission-critical applications."
First, we need to spin up our Yugabyte. The easiest way to do this is using a dockerfile.
version: '2'
services:
db:
image: yugabytedb/yugabyte:latest
user: root
command: "bin/yugabyted start --daemon=false"
ports:
- "7000:7000"
- "9000:9000"
- "5433:5433"
- "9042:9042" # live chat
restart: always # run as a service
volumes:
- /yb_data:/home/yugabyte/yb_data
Then, we are going to configure the DB for the testing
--Create schema
create schema api;
-- CreateTable and dummy values to test
create table api.todos (
id serial primary key,
done boolean not null default false,
task text not null,
due timestamptz
);
insert into api.todos (task) values
('finish tutorial 0'), ('pat self on back');
--Create an user and configure all the required grantees
create role web_anon nologin;
grant usage on schema api to web_anon;
grant select on api.todos to web_anon;
create role authenticator noinherit login password 'mysecretpassword';
grant web_anon to authenticator;
After that, we need to configure our postREST to connect to our local Yugabyte container. We will use the Yugabyte DB and the user/password created in the previous step.
db-uri = "postgres://authenticator:mysecretpassword@localhost:5433/yugabyte"
db-schemas = "api"
db-anon-role = "web_anon"
And we start the web server
Then, we can run our docker file
docker-compose up
now, we have a RESTful API to consume our data.
postgres@MSI:/home/felipe$ curl http://localhost:3000/todos
[{"id":1,"done":false,"task":"finish tutorial 0","due":null},
{"id":2,"done":false,"task":"pat self on back","due":null}]
postgres@MSI:/home/felipe$
Or by web
In the next article, we will see how to add other operations PUT/POST/DELETE
Thanks for reading
Subscribe to my newsletter
Read articles from Felipe Schneider directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Felipe Schneider
Felipe Schneider
Hello, my name is Felipe Schneider. I'm from Uruguay. I'm a tech enthusiast with a focus on DBs and empowering end users and small businesses to get the most out of their technology stack. Now I'm working on Azure SQL, Dataverse, Power Apps and SQL Server for a living, in my spare time I'm working on a SaaS product