# Connecting API With EchoAPI At Vscode,

Assalamualaikum, hallo guys these we will try to use api on my project, lets start

# Create Database

you can create project and install this

```bash
npm i drizzle-orm pg dotenv
npm i -d drizzle-kit
```

then you can create data base on postgres

```bash
//open on postgres ubuntu
sudo -i -u postgres
psql

//open on windows
psql -U postgres

//create database
create database pesantren
```

# Connecting Database

then you can create file `.env` ant typing this

```javascript
//for local host
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/pesantren"

//for online database, exemple: supabase and anymore
DATABASE_URL="postgresql://postgres.yieipycgkveuhreikdyy:[YOUR-PASSWORD]@aws-1-ap-southeast-1.pooler.supabase.com:6543/postgres?sslmode=require"
```

then you can create schema or table on directory `db/schema.js`

```javascript
import { pgTable, serial, varchar, timestamp } from 'drizzle-orm/pg-core';
 
export const santri = pgTable('student', {
  id: serial('id').primaryKey(),
  nama: varchar('nama', { length: 256 }).notNull(),
  kelas: varchar('kelas', { length: 50 }),
  createdAt: timestamp('created_at').defaultNow().notNull(),
});
```

then you can create connecting schema and database on `drizzle.config.js`

```javascript
import 'dotenv/config';
 
export default {
  dialect: 'postgresql',
  schema: './db/schema.js',
  out: './drizzle',
  dbCredentials: {
    url: process.env.DATABASE_URL,
  },
};
```

then you can git init and add this on `package.json` on scripts

```javascript
"scripts": {
  "db:generate": "drizzle-kit generate",
  "db:migrate": "drizzle-kit migrate",
  "dev": "node --watch server.js",
  "start":"node server.js"
}
```

then you can running migration database

```bash
npm run db:generate   # generate file migrasi
npm run db:migrate    # eksecution migrasi (create tabel)
```

then you can check on your database

```pgsql
SELECT * FROM student;
```

then you can setup early data on `db/index.js`

```javascript
import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';
import 'dotenv/config';
import * as schema from './schema.js';
 
const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});
 
export const db = drizzle(pool, { schema });
```

then create `db/seed.js`

```javascript
import { db } from './index.js';
import { santri } from './schema.js';
 
async function main() {
  await db.insert(santri).values([
    { id: 1, nama: 'Ahmad Fauzi', kelas: 11 },
    { id: 2, nama: 'Muhammad Rizky', kelas: 12 },
    { id: 3, nama: 'Alwi Saputra', kelas: 10 },
  ]);
 
  console.log(' Data santri berhasil di-seed');
}
 
main();
```

then running `seed.js`

```bash
node db.seed.js
```

# Use API With EchoAPI

then you can setup api, in this segmen we will use hono

```bash
npm i hono @hono/node-server
```

then create file server on `server.js`

```javascript
import { Hono } from 'hono';
import { serve } from '@hono/node-server';
import { db } from './db/index.js';
import { santri } from './db/schema.js';
import { eq } from 'drizzle-orm';

const app = new Hono();

//[C]Create
app.post('/api/santri', async (c) => {
    const data = await c.req.json();
    const result = await db.insert(santri).values(data).returning();
    return c.json({error: false, data: result[0]}, 201);
});

app.get('/api/santri', async (c) => {
    const result = await db.query.santri.findMany()
    return c.json({error: false, data: result})
});

app.get('/api/santri/:id', async (c) => {
    const id = Number(c.req.param('id'));
    const result = await db.query.santri.findFirst({
        where: eq(santri.id, id)
    })
    if (!result) return c.json({error: true, massage: 'Not found'}, 404);
    return c.json({error: false, data:result})
});

app.put('/api/santri/:id', async (c) => {
    const id = Number(c.req.param('id'));
    const data = await c.req.json();
    const result = await db.update(santri).set(data).where(eq(santri.id, id)).returning();
    
    if (!result) return c.json({error: true, massage: 'Not found'}, 404);
    return c.json({error: false, data:result[0]})
});

app.delete('/api/santri/:id', async (c) => {
    const id = Number(c.req.param('id'));
    const result = await db.delete(santri).where(eq(santri.id, id)).returning();
    if (result.length === 0){
        return c.json({error: true, massage: 'Not found'}, 404);
    }
    return c.json({error: false, massage: `delete id ${id}`});
});

app.get('/', async (c) => {
    return c.html(
        `<div><h1>Doc API</h1></div><a href="/api/santri" target="_parent">/api/santri</a>`
    );
});

serve({ fetch: app.fetch, port: 5429});
console.log(`✅ API running at http://localhost:5429`);
```

then you can running `server.js` then active

```javascript
node server.js
```

then we need use api, this is echoAPI (extension on Visual Studio Code)

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758852271402/e4ec4619-7205-463e-a768-b44cbb4131f2.png align="center")

then setting this for post method

```javascript
http://localhost:5429/api/santri
{
    "id":4,
    "nama":"Ahmad",
    "kelas":"x-b"
}
```

and this result the running or after send

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758852375321/738402ca-c12b-447a-af96-d3d9637a4e64.png align="center")

then we **get all data** you can use this, get method

```javascript
http://localhost:5429/api/santri
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758852563975/80d07ae3-404a-4c2b-82c0-a23ece631026.png align="center")

then get some data use this,

```javascript
http://localhost:5429/api/santri/find_id
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758852627892/20829823-985d-4855-b240-efcd9fa1f972.png align="center")

then use this for update data, put method

```javascript
http://localhost:5429/api/santri/find_id
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758852677957/62d24c4a-d877-4fde-9737-214a856b5f34.png align="center")

then use this for delete data, delete method

```javascript
http://localhost:5429/api/santri/find_id
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1758852723662/dbd19a56-1f1a-4886-a72d-dbf9894152ca.png align="center")

# Closing

thanks for watching
