Membuat basic REST API dengan express js (NodeJS) dan MySQL

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

Table of Contents

Introduction

In this tutorial, we will walk through the process of creating a basic REST API using Express.js (Node.js) and MySQL. This guide is ideal for those looking to understand how to set up a server, create CRUD operations, and connect to a MySQL database. By the end, you'll have a functional API that can handle basic data operations.

Step 1: Project Setup

  1. Install Node.js if you haven't already.
  2. Create a new directory for your project and navigate into it:
    mkdir express-mysql-api
    cd express-mysql-api
    
  3. Initialize a new Node.js project:
    npm init -y
    
  4. Install Express and Nodemon:
    npm install express
    npm install --save-dev nodemon
    

Step 2: Create and Run Express Server

  1. Create a new file named server.js in your project directory.
  2. Add the following code to set up a basic Express server:
    const express = require('express');
    const app = express();
    const PORT = process.env.PORT || 3000;
    
    app.use(express.json());
    
    app.listen(PORT, () => {
        console.log(`Server is running on port ${PORT}`);
    });
    
  3. Run the server using Nodemon:
    npx nodemon server.js
    

Step 3: Test API with Postman

  1. Download and install Postman if you haven't.
  2. Create a new request to http://localhost:3000 and send a GET request to test your server.

Step 4: Understanding Routing in Express

  1. Add routes to your server:
    app.get('/api', (req, res) => {
        res.send('Hello, API!');
    });
    
  2. Test this route in Postman by sending a GET request to http://localhost:3000/api.

Step 5: Learn HTTP Methods for REST API

  • GET: Retrieve data
  • POST: Create new data
  • PUT: Update existing data
  • DELETE: Remove data

Step 6: Define Response for REST API

  1. Standardize your API responses by creating a consistent structure:
    const responseHandler = (res, data, status = 200) => {
        res.status(status).json(data);
    };
    

Step 7: Project Structure

  1. Organize your project by creating the following folders:

    • routes
    • controllers
    • models
  2. Separate your routes into their respective files for better maintainability.

Step 8: Understand Middleware

  • Middleware are functions executed during the request-response cycle. They can modify request and response objects, end requests, and call the next middleware.

Step 9: Create Dummy CRUD Operations

  1. Create a Create operation:
    app.post('/api/users', (req, res) => {
        // Logic to create a user
    });
    
  2. Create a Read operation:
    app.get('/api/users', (req, res) => {
        // Logic to read users
    });
    
  3. Create an Update operation:
    app.put('/api/users/:id', (req, res) => {
        // Logic to update a user
    });
    
  4. Create a Delete operation:
    app.delete('/api/users/:id', (req, res) => {
        // Logic to delete a user
    });
    

Step 10: Set Up MySQL

  1. Install MySQL and create a new database.
    CREATE DATABASE express_api;
    USE express_api;
    CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255));
    

Step 11: Connect Express to MySQL

  1. Install MySQL package:
    npm install mysql
    
  2. Create a connection in your server.js file:
    const mysql = require('mysql');
    
    const db = mysql.createConnection({
        host: 'localhost',
        user: 'your_username',
        password: 'your_password',
        database: 'express_api'
    });
    
    db.connect(err => {
        if (err) throw err;
        console.log('MySQL connected');
    });
    

Step 12: Refactor MySQL Connection Configuration

  • Move your database connection logic to a separate module for cleaner code organization.

Step 13: Set Up Environment Variables

  1. Install dotenv:

    npm install dotenv
    
  2. Create a .env file to store your environment variables:

    DB_HOST=localhost
    DB_USER=your_username
    DB_PASS=your_password
    DB_NAME=express_api
    
  3. Load these variables in your server.js:

    require('dotenv').config();
    

Step 14: Implement CRUD Operations with MySQL

  1. Insert data into MySQL:

    app.post('/api/users', (req, res) => {
        const user = req.body;
        db.query('INSERT INTO users SET ?', user, (err, result) => {
            if (err) return res.status(500).send(err);
            responseHandler(res, { id: result.insertId, ...user });
        });
    });
    
  2. Retrieve data:

    app.get('/api/users', (req, res) => {
        db.query('SELECT * FROM users', (err, results) => {
            if (err) return res.status(500).send(err);
            responseHandler(res, results);
        });
    });
    
  3. Update data:

    app.put('/api/users/:id', (req, res) => {
        const { id } = req.params;
        db.query('UPDATE users SET ? WHERE id = ?', [req.body, id], (err) => {
            if (err) return res.status(500).send(err);
            responseHandler(res, { message: 'User updated' });
        });
    });
    
  4. Delete data:

    app.delete('/api/users/:id', (req, res) => {
        const { id } = req.params;
        db.query('DELETE FROM users WHERE id = ?', id, (err) => {
            if (err) return res.status(500).send(err);
            responseHandler(res, { message: 'User deleted' });
        });
    });
    

Step 15: Understand HTTP Status Codes

  • Familiarize yourself with common HTTP status codes, such as:
    • 200 OK
    • 201 Created
    • 204 No Content
    • 400 Bad Request
    • 404 Not Found
    • 500 Internal Server Error

Step 16: Optimize Postman Workspace

  • Create collections in Postman to group related API requests for better organization.

Step 17: Serve Static Files

  1. Set up static files in Express:
    app.use(express.static('public'));
    

Step 18: Upload Files in Express

  1. Install multer for handling file uploads:
    npm install multer
    
  2. Add file upload logic:
    const multer = require('multer');
    const upload = multer({ dest: 'uploads/' });
    
    app.post('/upload', upload.single('file'), (req, res) => {
        res.send('File uploaded successfully');
    });
    

Conclusion

You've successfully built a basic REST API using Express.js and MySQL. You've learned about project setup, CRUD operations, connecting to a database, and handling file uploads. As the next steps, consider expanding your API with user authentication, implementing error handling, or deploying your application. For further exploration, refer to the GitHub repository mentioned in the video description.