This example starts with the sqlc
tutorial and adds babyapi
functionality on top of it for the HTTP layer. It provides a custom implementation of the babyapi.Storage
interface to wrap the queries generated by sqlc
. It also implements connectivity to Turso cloud SQLite.
In addition to the storage backend, this example demonstrates how to extend the built-in CLI to add custom arguments and custom setup for only initializing DB for the server and not the client.
First, build the project
git clone https://github.com/calvinmclean/babyapi.git
cd babyapi/examples/sql
go build -o babyapi-sql .
Then, run the server:
./babyapi-sql serve
And use the provided CLI client to create resources:
# Create
./babyapi-sql client authors post --data '{
"name": "J.R.R. Tolkien",
"bio": "English writer and philologist",
"genre": "Fantasy"
}'
# List
./babyapi-sql client authors list
# Search
./babyapi-sql client authors list -q "genre=Fantasy"
By default, this will use an in-memory SQLite database. You can also use a local file storage or cloud-based Turso DB.
./babyapi-sql serve --db memory
./babyapi-sql serve --db file
# Optionally set filename using environement variable
SQLITE_FILE=my_file.db ./babyapi-sql serve --db file
If you want to use Turso, follow step one of their tutorial to create and use a new cloud database. Then, run it using the database URL and auth as env vars:
TURSO_DATABASE_URL=
TURSO_AUTH_TOKEN=
./babyapi-sql serve --db turso