Next js Api Prisma SqLite
Published: 2022-11-12 10:16:53

https://nextjs.org/
https://www.postman.com/
https://www.prisma.io/
CRUD API POSTMAN

```
pnpm crate next-app next_simple_api
Typescrip > No 
Eslint > No
```

```
//hello.js

https://nextjs.org/docs/api-routes/introduction
export default function handler(req, res) {
  res.status(200).json({ name: 'John Doe' })
}
```

![Image Browser api](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tw3i5glaqgp2s7eo0i6j.png)
```
//hello.js

export default function handler(req, res) {
  res.status(200).json({
    name: "Andi Ismail",
    age: 36,
    jomblo: false,
  });
}
```

![Image browser edit](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f1vxg5obihlepct9yudm.png)

`ctrl c mematikan server`

```
pnpm install prisma
npx prisma init
```
ganti psgresql ke sqlite

```
//.env

DATABASE_URL="file:./db.sqlite"
```
selanjutnya kita buat model dan mengganti provider dari posgre ke sqlite
```
//schema.prisma

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

model Notes {
  //kolom         Tipe            Option
  id              Int             @id @default(autoincrement())
  title           String
  note            String
  author          String
  createdAt       DateTime        @default(now())
  updatedAt       DateTime        @updatedAt
}
```
`npx prisma generate
 npx prisma db push
`

```
//package.json

{
  "name": "next_simple_api",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@prisma/client": "^4.6.1", //berhasil 
    "next": "13.0.3",
    "prisma": "^4.6.1",
    "react": "18.2.0",
    "react-dom": "18.2.0"
  }
}
```
buat file baru `db.js` di folder prisma

```
//db.js

import {PrismaClient} from "@prisma/client"
export const db = new PrismaClient()
```
buat folder baru `notes > create.js`

```
//create.js
import { db } from "../../../prisma/db"; 

export default async function handler(req, res){

    if (req.method !== "POST"){
        return res.status(401).json({
            success : false,
            message : "method not allowed"
        })
    }
    try {
        const data = await req.body
        const createNote =await db.notes.create({
            data : data
        })
        return res.status(201).json({
            success : true,
            query : createNote
        })

    }catch (error) {
        return res.status(401).json({
            success : false,
            query : error.message
        })
    }
}

```
![Image postman](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ocni979bgpigfun6gfg7.png)

dengan menggunakan postman kita akan menangkap `req.body` di create.js yang telah kita buat. di post man kita buat kita buat new collection, add folder, add request, di body rubah ke raw dan tipe data JSON

![Image postman create note](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7qpv3y77om3fs2mv7n7f.png)

![Image error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onhwjdrptnwxn4y0jrdw.png)

error disini tertulis note seharusnya notes
`const createNote = await db.notes.create({`

```
//create.js

import { db } from "../../../prisma/db";

export default async function handler(req, res) {
  if (req.method !== "POST") {
    return res.status(401).json({
      success: false,
      message: "method not allowed",
    });
  }
  try {
    const data = await req.body;
    const createNote = await db.notes.create({
      data: data,
    });
    return res.status(201).json({
      success: true,
      query: createNote,
    });
  } catch (error) {
    return res.status(401).json({
      success: false,
      error: error.message,
    });
  }
}

```

![Image postman post pertama](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ky9ihc0yt8br83geza4f.png)

selanjutnya kita lihat fitur dari prisma studio sam aseprti seperti php myadmin

`npx prisma studio`

![Image Notes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zcuq20m8ynz39ooz8gq3.png)

cuman untuk data base tidak boleh serperti ini sehingga kita harus buat api sendiri.

```
//read.js

import {db} from "../../../prisma/db"

export default  async function handler (req, res){

    //check req method 
    if (req.method !== "GET"){
        return res.status(401).json({
            success : false,
            message : "req method not allowed"
        })
    }

    try {
        const result = await db.notes.findMany()
        return res.status(200).json({
            success :true,
            query : result
        })
    } catch (error){
        return res.status(401).json({
            success : false,
            error : error.message
        })
    }
}
```
selanjutnya kita ke postman kembali, untuk menambhakan add request di folder notes, kita beri nama READ NOTES kemudian send 

![Image read](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mbgcvwyyc1fcakrgvx5o.png)

sekarang sudah bisa baca data di postman selanjutnya kita akan menambahkan delete data 

```
//delete.js

import { db } from "../../../prisma/db"

export default async function handler (req, res){

    if(req.method !=="DELETE"){
        return res.status(401).json({
            success : false,
            message : "req method not allowed"
        })
    }

    try {

        //req query
        const {id} = await req.query
        const deleteNote = await db.notes.delete({
            where : {
                id : parseInt(id)
            }
        })
        return res.status(201).json({
            success : true,
            message : "Berhasil delete data",
            query : deleteNote
        })
    }

    catch (error) {
        return res.status(401).json({
            success : false,
            error : error.message
        })
    }
}
```
selanjtunya kita ke postman lagi add request DELETE NOTE ubah get jadi DELETE masukkan url seperti read `http://localhost:3000/api/notes/delete?id=1`

![Image delete](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d67wcbr0z5hvktak3wbr.png)

selanjutnya kita akan bikin yang terakhir yaitu delete.

```
//update.js

import { db } from "../../../prisma/db";

export default async function handler (req, res){

    if(req.method !=="PUT"){
        return res.status(401).json({
            success : false,
            message : "method not allowed"
        })
    }
    try {
        const {id} = await req.query
        const newData = await req.body
        const updateNote = await db.notes.update({
            where : {
                id : parseInt(id)
            },
            data : newData
        })
        return res.status(201).json({
            success : true,
            message : "data berhasil di update",
            query : updateNote
        })
    }
    catch (error){
        return res.status(401).json({
            success : false,
            error : error.message
        })
    }
}
```

selanjutnya kita kepostman, add request ubah menjadi PUT, body > raw > JSON, masukkan url `http://localhost:3000/api/notes/update?id=2`

![Image postman](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/373zrxx0hc81npvejiyd.png)


![Image prisma](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/83vu3iu02t5el22eanel.png)

https://github.com/andiks2018/JvalleyNext-CRUDApiPostmanPrisman.git