Loading PasteShare...

Getting Started with REST APIs: A Complete Beginner's Guide

By James Delaney Nov 04, 2025 1 min read 31 views

What is a REST API?

REST (Representational State Transfer) is an architectural style for designing networked applications. APIs built using REST principles are called RESTful APIs.

Key REST Principles

  • Stateless: Each request contains all information needed
  • Client-Server: Separation of concerns
  • Cacheable: Responses can be cached
  • Uniform Interface: Consistent interaction patterns

HTTP Methods

// GET - Retrieve data
GET /api/users

// POST - Create new resource
POST /api/users

// PUT - Update entire resource
PUT /api/users/123

// DELETE - Remove resource
DELETE /api/users/123

Building Your First API

Let's create a simple user management API using Node.js and Express:

const express = require('express');
const app = express();

// Middleware
app.use(express.json());

// Sample data
let users = [
  { id: 1, name: 'John Doe', email: 'john@example.com' },
  { id: 2, name: 'Jane Smith', email: 'jane@example.com' }
];

// GET all users
app.get('/api/users', (req, res) => {
  res.json(users);
});

// GET user by ID
app.get('/api/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).json({ error: 'User not found' });
  res.json(user);
});

// POST new user
app.post('/api/users', (req, res) => {
  const { name, email } = req.body;
  const newUser = {
    id: users.length + 1,
    name,
    email
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Testing Your API

Use tools like Postman or curl to test your endpoints:

# Get all users
curl http://localhost:3000/api/users

# Create new user
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice Johnson","email":"alice@example.com"}'

Best Practices

  • Use meaningful HTTP status codes
  • Implement proper error handling
  • Add input validation
  • Use consistent naming conventions
  • Document your API endpoints

Remember: Good APIs are designed with the consumer in mind. Always consider how developers will use your endpoints.

Comments (0)

Please login or register to leave a comment.

No comments yet. Be the first to share your thoughts!