Tutorial NodeJS RESTful API (Bahasa Indonesia)

3 min read 2 hours ago
Published on Nov 28, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will learn how to create a RESTful API using NodeJS, MySQL, Prisma, and ExpressJS. This guide will walk you through the entire process, from setting up your project to implementing user, contact, and address management functionalities. By the end of this tutorial, you will have a fully functional API that can be used in various applications.

Step 1: Gather Requirements

Before starting, ensure you have the following:

  • Node.js installed on your machine.
  • MySQL server running.
  • Basic understanding of JavaScript and RESTful APIs.

Step 2: Project Setup

  1. Create a New Project Directory

    • Open your terminal and create a new folder for your project:
      mkdir my-restful-api
      cd my-restful-api
      
  2. Initialize a Node.js Project

    • Run the following command to create a package.json file:
      npm init -y
      
  3. Install Required Packages

    • Install the necessary dependencies:
      npm install express prisma @prisma/client mysql2
      

Step 3: Setup Database

  1. Create a MySQL Database

    • Launch your MySQL client and create a new database for your application:
      CREATE DATABASE my_database;
      
  2. Configure Prisma

    • Create a new file named schema.prisma in your project directory, and configure it to connect to your MySQL database:
      datasource db {
        provider = "mysql"
        url      = "mysql://username:password@localhost:3306/my_database"
      }
      
      generator client {
        provider = "prisma-client-js"
      }
      
      model User {
        id        Int    @id @default(autoincrement())
        name      String
        email     String @unique
        password  String
      }
      
      model Contact {
        id        Int    @id @default(autoincrement())
        userId    Int
        name      String
        phone     String
      }
      
      model Address {
        id        Int    @id @default(autoincrement())
        userId    Int
        street     String
        city       String
      }
      
  3. Run Prisma Migrations

    • Generate and apply the migration to your database:
      npx prisma migrate dev --name init
      

Step 4: Create API Endpoints

  1. Setup Express Server

    • Create a file named server.js and set up your Express server:
      const express = require('express');
      const app = express();
      const PORT = 3000;
      
      app.use(express.json());
      
      app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
      });
      
  2. Implement User API Endpoints

    • Create endpoints for user registration, login, and management.
    • Example for user registration:
      app.post('/api/register', async (req, res) => {
        // logic to register user
      });
      
  3. Implement Contact API Endpoints

    • Create endpoints to manage contacts (create, read, update, delete).
  4. Implement Address API Endpoints

    • Create endpoints to manage addresses (create, read, update, delete).

Step 5: Test Your API

  1. Manual Testing

    • Use a tool like Postman to send requests to your API endpoints.
    • Verify that each endpoint works correctly by checking the responses.
  2. Handle Errors Gracefully

    • Ensure that your API returns meaningful error messages for invalid requests.

Conclusion

You have now built a RESTful API using NodeJS, MySQL, Prisma, and ExpressJS. This API allows for user management, contact management, and address management. You can expand upon this foundation by adding features such as authentication, logging, and more complex data relationships. As next steps, consider deploying your API to a cloud service or integrating it with a frontend application.