APIs and Database
Learning objectives
- You know that APIs can also rely on a database.
An API that interacts with the database is also relatively straightforward to create. Let's look at building a simple API that interacts with the table addresses
that was added to the Docker project in the part Database Migrations of the chapter Application Containerization. The tablle is as follows.
CREATE TABLE addresses (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
address TEXT NOT NULL
);
An API that would allow retrieving all the addresses and adding addresses could be implemented as follows. Here, we assume that we have the database.js
file in the same directory as the application, and that the database.js
exports the sql
function that can be used to create database queries. Furthermore, we assume that Hono is exported from deps.js
.
import { Hono } from "./deps.js";
import { sql } from "./database.js";
const app = new Hono();
app.get("/addresses", async (c) => {
return c.json(await sql`SELECT * FROM addresses`);
});
app.post("/addresses", async (c) => {
const body = await c.req.json();
await sql`INSERT INTO addresses (name, address) VALUES (${body.name}, ${body.address})`;
return c.json({ status: "ok" });
});
Deno.serve(app.fetch);
While APIs could in practice use any types of paths and any types of methods, and return any type of data, it is meaningful to think about how to implement them. Let's look into RESTful APIs next.