Thuta Learning
ရှာဖွေရန်
ProjectsWeb Developmentbeginner

Mini Project: User API

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

ဒီ mini project မှာ Express.js နဲ့ Simple User API တစ်ခုတည်ဆောက်ပါမယ်။ Users အားလုံးကြည့်မယ်၊ user တစ်ယောက်ရှာမယ်၊ user အသစ်ထည့်မယ်။ Database မပါသေးပေမယ့် REST API ရဲ့အခြေခံ flow ကိုအပြည့်မြင်နိုင်ပါတယ်။

javascript
const express = require('express');

const app = express();
const port = 3000;

app.use(express.json());

let users = [
  { id: 1, name: 'Aung Aung' },
  { id: 2, name: 'Mya Mya' }
];

app.get('/api/users', (req, res) => {
  res.json({ count: users.length, data: users });
});

app.get('/api/users/:id', (req, res) => {
  const id = Number(req.params.id);
  const user = users.find((item) => item.id === id);

  if (!user) {
    return res.status(404).json({ message: 'User not found' });
  }

  res.json({ data: user });
});

app.post('/api/users', (req, res) => {
  const name = req.body.name;

  if (!name || name.trim() === '') {
    return res.status(400).json({ message: 'Name is required' });
  }

  const newUser = { id: users.length + 1, name: name.trim() };
  users.push(newUser);

  res.status(201).json({ message: 'User created', data: newUser });
});

app.use((req, res) => {
  res.status(404).json({ message: 'Route not found' });
});

app.listen(port, () => {
  console.log(`Simple User API running at http://localhost:${port}`);
});

ဒီ project code က lesson အားလုံးကိုပေါင်းထားတာပါ။ Server setup, middleware, GET routes, POST route, validation, fallback 404 route အထိပါပါတယ်။ app.use((req,res)=>...) ကိုအောက်ဆုံးထားထားတာက အပေါ်က route တွေမကိုက်တော့မှ 404 ပြန်ပေးစေချင်လို့ပါ။

You should see
Run: node app.js Test endpoints: GET http://localhost:3000/api/users GET http://localhost:3000/api/users/1 POST http://localhost:3000/api/users

Info

Route order ကိုသတိထားပါ။ 404 fallback ကိုအပေါ်တင်ထားရင် အောက်က route တွေဆီမရောက်တော့ပါ။

နောက်တစ်ဆင့်

ဒီ project ကိုနားလည်ပြီးရင် CRUD အပြည့်အတွက် PUT/PATCH နှင့် DELETE routes တွေကို ကိုယ်တိုင်ထပ်ရေးကြည့်ပါ။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Server restart လုပ်တိုင်း in-memory users data က original state ပြန်ဖြစ်ပါမယ်။ Data မပျောက်ချင်ရင် နောက်တစ်ဆင့်မှာ database သို့ file storage ချိတ်ရပါမယ်။

လေ့ကျင့်ခန်း

ဒီ mini project ကိုနောက်ပိုင်း MongoDB/PostgreSQL ချိတ်ခြင်း၊ authentication ထည့်ခြင်း၊ frontend form ချိတ်ခြင်း၊ search/filter/pagination ထည့်ခြင်းနဲ့ဆက်တိုးနိုင်ပါတယ်။

You'll know it worked when:

Mini Project: User API | Thuta Learning