Ever needed to quickly prototype an API endpoint but didn't want to set up a full Express server? I've been using a tiny Node.js script with the built-in http module for quick testing. Here's a minimal example that handles GET and POST:
javascript
const http = require('http');
const server = http.createServer((req, res) => {
const { method, url } = req;
if (method === 'GET' && url === '/api/hello') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello World' }));
} else if (method === 'POST' && url === '/api/data') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
const data = JSON.parse(body);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ received: data }));
});
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000, () => console.log('Server running on port 3000'));
For more complex prototyping, I've been using a tool called QuickAPI that generates full REST endpoints from a simple schema. What's your quickest way to spin up a test API?
Top comments (0)