Generate me a working api project. With express js
- User
Generate me a working api project. With express js
Assistant
Here's a step-by-step guide to creating a simple RESTful API with Express.js. This example will create a basic "Todo List" API:
Step 1: Set Up the Project
-
Install Node.js (if you haven't already): https://nodejs.org/
-
Create a new directory for your project:
mkdir todo-api cd todo-api -
Initialize a Node.js project:
npm init -y -
Install dependencies:
npm install express cors dotenv
Step 2: Project Structure
Your project should look like this:
todo-api/ ├── server.js ├── routes/ │ └── todos.js ├── middlewares/ │ └── error-handler.js └── .env
Step 3: Create
server.js// server.js import express from 'express'; import cors from 'cors'; import dotenv from 'dotenv'; import todosRoute from './routes/todos.js'; dotenv.config(); const app = express(); const PORT = process.env.PORT || 3000; // Middleware app.use(cors()); app.use(express.json()); // Routes app.use('/api/todos', todosRoute); // Error handling middleware app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); }); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
Step 4: Create
routes/todos.js// routes/todos.js import express from 'express'; const router = express.Router(); // In-memory "database" (replace with a real DB like MongoDB later) let todos = [ { id: 1, text: 'Learn Express.js', completed: false }, { id: 2, text: 'Build an API', completed: false }, ]; // GET all todos router.get('/', (req, res) => { res.json(todos); }); // POST a new todo router.post('/', (req, res) => { const newTodo = { id: Date.now(), text: req.body.text, completed: false, }; todos.push(newTodo); res.status(201).json(newTodo); }); // PUT (update) a todo router.put('/:id', (req, res) => { const todo = todos.find(t => t.id === Number(req.params.id)); if (!todo) return res.status(404).send('Todo not found'); todo.text = req.body.text || todo.text; todo.completed = req.body.completed || todo.completed; res.json(todo); }); // DELETE a todo router.delete('/:id', (req, res) => { const index = todos.findIndex(t => t.id === Number(req.params.id)); if (index === -1) return res.status(404).send('Todo not found'); const removedTodo = todos.splice(index, 1); res.json(removedTodo[0]); }); export default router;
Step 5: Create
.envFilePORT=3000
Step 6: Run the Server
Start the server:
node server.js
Test the API
Use tools like curl, Postman, or Insomnia to test the endpoints:
-
GET all todos:
curl http://localhost:3000/api/todos -
Add a new todo:
curl -X POST -H "Content-Type: application/json" -d '{"text":"Buy milk"}' http://localhost:3000/api/todos -
Update a todo:
curl -X PUT -H "Content-Type: application/json" -d '{"text":"Learn Node.js", "completed":true}' http://localhost:3000/api/todos/1 -
Delete a todo:
curl -X DELETE http://localhost:3000/api/todos/2
Next Steps
- Add a real database (e.g., MongoDB, PostgreSQL).
- Implement authentication (JWT, OAuth).
- Add environment variables for sensitive data.
- Write unit tests with Jest or Mocha.
- Add pagination, sorting, and filtering to endpoints.
Let me know if you'd like help expanding any part of this! 😊
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.