Express simple Api
Published: 2022-12-03 00:18:24

```
mkdir express_simpleApi
cd express_simpleApi
npm init -y //akan menjawab yes untuk semua pertanyaan 
npm install express dotenv prisma cors
npm install -D @babel/core @babel/node @babel/preset-env @babel/cli 

```
karena express masih menggunakan javascript es-5 maka kita gunakan babel sebagai compiler agar bisa digunakan es-6.

npm install -D //artinya kita menginstall aplikasi hanya sampai di tahap develop, nanti akan di generate menajdi apk biasa

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

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

![Image express](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3mc7a8igybk6mx72muv4.png)

buat file .babelrc

```
// .babelrc

{
    "presets": ["@babel/preset-env"]
}
```
kita rubah package.json kita akan gunakan node monitor

```
//package.json

{
  "name": "express_simpleapi",
  "version": "1.0.0",
  "description": "",
  "main": "app/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon --exec babel-node app/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "prisma": "^4.7.1"
  },
  "devDependencies": {
    "@babel/cli": "^7.19.3",
    "@babel/core": "^7.20.5",
    "@babel/node": "^7.20.5",
    "@babel/preset-env": "^7.20.2"
  }
}

```
kita install nodemon

```
npm install -g nodemon
```
kita buat file index js dalam folder app

```
//index.js

// sekaramg kit sudah bisa menggunakan es-6 di javascript
import express from "express";

const app = express()

//listener
app.listen(9000, ()=>{
    console.log('server beckend berjalan....')
})
```
ini hasilnya 

![Image server berjalan](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m573owdds7c3tk2beeya.png)

```
//index.js

// sekaramg kit sudah bisa menggunakan es-6 di javascript
import express from "express";

const app = express()

app.get("/", (req, res)=>{
    res.status(200).send("server terhubung..")
})

//listener
app.listen(9000, ()=>{
    console.log('server beckend berjalan..')
})

```

![Image server terhubung](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x8xojomp8r2r0esg50nl.png)

ganti menggunakan bectick

```
app.get("/", (req, res)=>{
    res.status(200).send(`
        <h1>Hello Express JS</h1>
    `)
})
```

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

kita tidak menggunakan send tapi json.

```
//route
app.get("/", (req, res)=>{
    res.status(200).json({
        success :true,
        message:"server berhasil terhubung"
    })
})
```

![Image json version](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2345a7zz6f1chg91gvjb.png)

install json view extension chrome, hasilnya jadi beda.

![Image json view](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wteh9nqc2tpcndn8pmxr.png)

selanjutnya kita ke network, refresh akan muncul localhost, klik 2 kali

![Image inspect header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6qp35p21xrf17sex2363.png)

![Image inspect preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fpne50ewy6obk0gkuvzx.png)

![Image inspect response](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7t5ls2xc57m6uvb09ooq.png)

kita akan baca hasil dari req dengan console.log

```
//route
app.get("/", (req, res)=>{
    console.log(req.headers) //lihat hasil req
    res.status(200).json({
        success :true,
        message:"server berhsil terhubung"
    })
})
```
hasil dari console log tidak terlihat di inspect disisi client, melainkan disisi beckend /terminal.

![Image terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7hbwj0db2frpah8g6aph.png)

sekarang kita coba kirim query, kita akan coba menampilkan query dan title

```
//route
app.get("/note/create", (req, res)=>{
    //console.log(req.headers)

    const{title, content}= req.query
    res.status(200).json({
        //success :true,
        //message:"server berhsil terhubung"
        success : true,
        data : {
            title : title,
            content : content
        }    
    })
})
```

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

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

masih kosong, kita harus ini title dan contentnya. isi http://localhost:9000/note/create?title=ini title&content=ini content blog saya
kemudian enter

![Image isi title dan content](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/guxkn64khnsdh8yhuzy0.png)

![Image hasil nya](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/28iqypxrpzzb4ito7hgw.png)

kita sudah berhasil menangkap query dan sekarang kita akan menangkap params, kita masih menggunakan method get. params=1

```
//params
app.get("/note/read/:id", (req, res)=>{
    const {id} = req.params
    res.status(200).json({
        success :true,
        data : {
            id:id
        }
    })
})
```

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

sekarang kita ke prisma jalankan dengan 
`npx prisma init`

```
//env

DATABASE_URL="file:./db.sqlite"

```

```
//schema.prisma

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

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

model Notes {
  id            Int       @id @default(autoincrement())
  title         String    
  content       String
  author        String
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt
}

`npx prisma db push`

```
selanjutnya kita jalankan prisma db push, maka dan otomatis akan mengenerate prisma tanda berhasil akan muncul file db.sqlite

![Image db-sqlite](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zwvclkkrqwfjpj9i68so.png)

selanjutnya kita buat connection.js

```
//connection.js

import {PrismaClient} from "@prisma/client"

const db = new PrismaClient

export default db
```
sebenarnya bisa langsung mengganti get ke post tapi tidak kelihatan disi client , jadi pakai get aja dulu. `app.get("/note/create",`

```
//index.js

// sekaramg kit sudah bisa menggunakan es-6 di javascript
import express from "express";
import db from "../prisma/connection";

const app = express()

//route
app.get("/note/create", async (req, res)=>{
    //console.log(req.headers)

    const{title, content, author}= req.query
    const createNote = await db.notes.create({
        data : {
            title : title,
            content : content,
            author:author
        }
    })
    res.status(200).json({
        //success :true,
        //message:"server berhsil terhubung"
        success : true,
        data : createNote  
    })
})

//params
app.get("/note/read/:id", async(req, res)=>{
    const readNotes = await db.notes.findMany()
    
    res.status(200).json({
        success :true,
        data : readNotes
    })
})

//listener
app.listen(9000, ()=>{
    console.log('server beckend berjalan..')
})
```

![Image kita belum punya data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d4o28gbtw45mqooo4o8m.png)

data masih 0

sekarang kita isi, cara isinya di urlnya %20 = spasi

![Image berhasil](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8133yu41266t8uih1azu.png)

sekarang kita buka lagi note read sudah terisi sesuai dengan apa yan gkita inputkan 

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

![Image tulisan kedua](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7f2se4v3rp67wwn8endh.png)

![Image hasil tulisan kedua](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5hal4ztrvbnp3p4eftvv.png)

sekarang kita buka read note maka akan muncul dua data 

![Image dua data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/64v18momd3nejrpr37hu.png)

```
//package.json

{
  "name": "express_simpleapi",
  "version": "1.0.0",
  "description": "",
  "main": "app/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon --exec babel-node app/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@prisma/client": "^4.7.1",
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "prisma": "^4.7.1"
  },
  "devDependencies": {
    "@babel/cli": "^7.19.3",
    "@babel/core": "^7.20.5",
    "@babel/node": "^7.20.5",
    "@babel/preset-env": "^7.20.2"
  }
}

```

https://github.com/andiks2018/JvalleyExpress-membuatApi.git