Module 6: API Routes in Next.js

ඔබේ Next.js යෙදුම Full-Stack app එකක් බවට පත් කරමු.

1. API Routes යනු කුමක්ද?

මේ දක්වා අප ඉගෙන ගත්තේ Next.js භාවිතයෙන් frontend (පරිශීලකයාට පෙනෙන කොටස) නිර්මාණය කරන ආකාරයයි. නමුත් බොහෝ නවීන යෙදුම් වලට backend එකක්ද (server-side logic, database interactions) අවශ්‍ය වෙනවා. සාමාන්‍යයෙන් මේ සඳහා Express.js (Node.js) වැනි වෙනම framework එකකින් backend server එකක් හදන්න වෙනවා.

නමුත් Next.js හි ඇති විශිෂ්ටතම ලක්ෂණයක් තමයි API Routes. මෙයින් ඔබට ඉඩ සලසනවා, ඔබේ Next.js project එක ඇතුළතම, වෙනම backend server එකක් නොමැතිව, සම්පූර්ණ backend API එකක් නිර්මාණය කිරීමට.

pages/api directory එක තුළ ඔබ සාදන ඕනෑම file එකක්, API endpoint එකක් ලෙස සැලකෙනවා. උදාහරණයක් ලෙස, pages/api/hello.js file එකක් සෑදුවොත්, එය /api/hello යන URL එකෙන් access කළ හැකි API endpoint එකක් බවට පත් වෙනවා.

2. API Route එකක් නිර්මාණය කිරීම

API Route එකක් කියන්නේ Node.js serverless function එකක් export කරන JavaScript module එකක්. මෙම function එකට parameters දෙකක් ලැබෙනවා: `req` (request) සහ `res` (response). මේවා Node.js හි standard HTTP server objects වලට සමානයි.

අපි සරලම API route එකක් හදමු. `pages/api/greeting.js` නමින් file එකක් සාදා පහත code එක ඇතුළත් කරන්න.

// File: pages/api/greeting.js

// req = HTTP incoming message, res = HTTP server response
export default function handler(req, res) {
  // We set the status code to 200 (OK)
  // and send a JSON response
  res.status(200).json({ message: 'Hello from the API!' });
}

දැන් ඔබේ browser එකෙන් http://localhost:3000/api/greeting වෙත පිවිසෙන්න. ඔබට `{ "message": "Hello from the API!" }` යන JSON response එක දැකගත හැකි වනු ඇත. සුභ පැතුම්, ඔබ ඔබේ පළමු API endpoint එක නිර්මාණය කර අවසන්!

3. GET, POST, PUT, DELETE Requests හැසිරවීම

RESTful API එකක, එකම endpoint එකට එන විවිධ HTTP methods (GET, POST, etc.) වලට විවිධ දේ කරන්න වෙනවා. උදාහරණයක් ලෙස, `/api/notes` endpoint එකට:

  • GET request එකක් ආවොත්, සියලුම notes return කරන්න ඕන.
  • POST request එකක් ආවොත්, අලුත් note එකක් save කරන්න ඕන.

අපිට `req.method` property එක check කරලා, අදාළ method එකට අනුව logic එක ලියන්න පුළුවන්.

// File: pages/api/notes.js

export default function handler(req, res) {
  if (req.method === 'GET') {
    // Handle GET request - e.g., fetch all notes
    res.status(200).json({ notes: ['Note 1', 'Note 2'] });
  } else if (req.method === 'POST') {
    // Handle POST request - e.g., save a new note
    const newNote = req.body.note; // Accessing the request body
    console.log('New note received:', newNote);
    res.status(201).json({ success: true, note: `Saved: ${newNote}` });
  } else {
    // Handle any other HTTP method
    res.setHeader('Allow', ['GET', 'POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

POST request එකකදී යවන data (`{ "note": "My new note" }` වැනි) `req.body` object එකෙන් ලබාගන්න පුළුවන්. Next.js ස්වයංක්‍රීයව request body එක parse කර දෙනවා.

4. Database එකකට සම්බන්ධ වීම

සැබෑ ලෝකයේ යෙදුමකදී, දත්ත තැන්පත් කරන්නේ database එකක. API route එකක් යනු server-side code එකක් නිසා, ඔබට මෙහි සිට කෙලින්ම database එකකට සම්බන්ධ විය හැකිය.

ඔබට Prisma, Mongoose (MongoDB සඳහා), හෝ node-postgres (PostgreSQL සඳහා) වැනි library එකක් install කර, database connection logic එක ඔබේ API route එක තුළ ලිවිය හැකිය.

// Example structure (pseudo-code) for connecting to a DB
import { connectToDatabase } from '../../lib/db'; // A helper function

export default async function handler(req, res) {
  if (req.method === 'GET') {
    try {
      const db = await connectToDatabase();
      const notes = await db.collection('notes').find({}).toArray();
      res.status(200).json({ notes });
    } catch (error) {
      res.status(500).json({ error: 'Failed to fetch notes' });
    }
  }
  // ... handle other methods
}

වැදගත්: Database credentials වැනි සංවේදී තොරතුරු කිසිවිටකත් code එකේ hard-code කරන්න එපා. ඒවා Environment Variables (`.env.local` file) වල තැන්පත් කරන්න.

5. Hands-on: සරල Notes API එකක් නිර්මාණය

දැන් අපි database එකක් වෙනුවට සරල in-memory array එකක් භාවිතා කරලා, notes save කරන සහ get කරන API එකක් හදමු.

  1. API Route File එක සෑදීම:

    `pages/api/notes.js` file එක (ඉහත උදාහරණයේ තිබූ) සාදා, එයට පහත code එක ඇතුළත් කරන්න. අපි මෙහි data තාවකාලිකව server එකේ memory එකේ තියාගන්නවා.

    // File: pages/api/notes.js
    
    // Let's use a simple in-memory array to store notes for this example
    let notes = [
      { id: 1, text: 'First note from the server' },
      { id: 2, text: 'Second note about Next.js' },
    ];
    
    export default function handler(req, res) {
      if (req.method === 'GET') {
        // Return all notes
        res.status(200).json(notes);
      } else if (req.method === 'POST') {
        const newNoteText = req.body.text;
        if (!newNoteText) {
          return res.status(400).json({ error: 'Note text cannot be empty' });
        }
        const newNote = {
          id: Date.now(), // Use timestamp for a unique ID
          text: newNoteText,
        };
        notes.push(newNote);
        res.status(201).json(newNote);
      } else {
        res.setHeader('Allow', ['GET', 'POST']);
        res.status(405).end(`Method ${req.method} Not Allowed`);
      }
    }
    
  2. API එක පරීක්ෂා කිරීම (Testing):

    API endpoints test කරන්න Postman, Insomnia වැනි මෙවලමක් භාවිතා කිරීම ඉතා පහසුයි.

    • GET Request: Postman එකෙන් `GET` request එකක් http://localhost:3000/api/notes වෙත යවන්න. ඔබට αρχικά notes දෙක JSON array එකක් ලෙස ලැබෙනු ඇත.
    • POST Request: Postman එකේ method එක `POST` ලෙස වෙනස් කර, Body tab එකට ගොස්, `raw` සහ `JSON` තෝරන්න. ඉන්පසු පහත JSON එක ඇතුළත් කර request එක යවන්න:
      {
          "text": "This is my new note from Postman!"
      }
      ඔබට status 201 (Created) සමග ඔබ දැන් සෑදූ note එකේ details (`id` සහ `text`) response එක ලෙස ලැබෙනු ඇත.
    • දැන් නැවත GET request එක යැව්වොත්, ඔබට අලුතින් එකතු කළ note එක ද ඇතුළුව notes 3ක් පෙනෙනු ඇත. (Development server එක restart කළහොත්, memory එක reset වී data නැති වී යයි).

මෙමගින්, frontend එකෙන් (උදා: React component එකක `fetch` function එකක් හරහා) මෙම API endpoints call කර, දත්ත ලබාගැනීමට සහ යැවීමට පුළුවන්. ඔබ දැන් Frontend සහ Backend දෙකම එකම project එකක කළමනාකරණය කරන Full-Stack developer කෙනෙකු වීමේ මාවතේ වැදගත් පියවරක් තබා ඇත!