DEV Community 👩‍💻👨‍💻

Cover image for Express simple Api
Andi Ismail
Andi Ismail

Posted on

Express simple Api

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 

Enter fullscreen mode Exit fullscreen mode

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

Image babel

Image express

buat file .babelrc

// .babelrc

{
    "presets": ["@babel/preset-env"]
}
Enter fullscreen mode Exit fullscreen mode

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"
  }
}

Enter fullscreen mode Exit fullscreen mode

kita install nodemon

npm install -g nodemon
Enter fullscreen mode Exit fullscreen mode

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....')
})
Enter fullscreen mode Exit fullscreen mode

ini hasilnya

Image server berjalan

//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..')
})

Enter fullscreen mode Exit fullscreen mode

Image server terhubung

ganti menggunakan bectick

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

Image becktick

kita tidak menggunakan send tapi json.

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

Image json version

install json view extension chrome, hasilnya jadi beda.

Image json view

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

Image inspect header

Image inspect preview

Image inspect response

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"
    })
})
Enter fullscreen mode Exit fullscreen mode

hasil dari console log tidak terlihat di inspect disisi client, melainkan disisi beckend /terminal.

Image terminal

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
        }    
    })
})
Enter fullscreen mode Exit fullscreen mode

Image /

Image kosong

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

Image hasil nya

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
        }
    })
})
Enter fullscreen mode Exit fullscreen mode

Image params

sekarang kita ke prisma jalankan dengan
npx prisma init

//env

DATABASE_URL="file:./db.sqlite"

Enter fullscreen mode Exit fullscreen mode
//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`

Enter fullscreen mode Exit fullscreen mode

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

Image db-sqlite

selanjutnya kita buat connection.js

//connection.js

import {PrismaClient} from "@prisma/client"

const db = new PrismaClient

export default db
Enter fullscreen mode Exit fullscreen mode

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..')
})
Enter fullscreen mode Exit fullscreen mode

Image kita belum punya data

data masih 0

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

Image berhasil

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

Image read note

Image tulisan kedua

Image hasil tulisan kedua

sekarang kita buka read note maka akan muncul dua data

Image dua data

//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"
  }
}

Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.