API Development and Integration

Master RESTful API design, GraphQL, API security, documentation, and integration patterns.

advanced Backend Development 6 hours

Chapter 4: API Endpoint Design

Chapter 4 of 14

Chapter 4: API Endpoint Design

4.1 URL Structure

Well-designed URLs are intuitive, consistent, and follow REST conventions.

// RESTful URL patterns
GET    /api/users                    // List all users
GET    /api/users/:id                // Get specific user
POST   /api/users                    // Create user
PUT    /api/users/:id                // Update entire user
PATCH  /api/users/:id                // Partial update
DELETE /api/users/:id                // Delete user

// Nested resources
GET    /api/users/:userId/posts      // Get user's posts
POST   /api/users/:userId/posts      // Create post for user
GET    /api/users/:userId/posts/:postId  // Get specific post

4.2 Query Parameters

// Filtering
GET /api/users?role=admin&status=active

// Pagination
GET /api/users?page=1&limit=10

// Sorting
GET /api/users?sort=name&order=asc

// Searching
GET /api/users?search=john

// Implementation
app.get('/api/users', async (req, res) => {
    const { page = 1, limit = 10, sort = 'createdAt', order = 'desc', search } = req.query;
    
    const query = {};
    if (search) {
        query.$or = [
            { name: { $regex: search, $options: 'i' } },
            { email: { $regex: search, $options: 'i' } }
        ];
    }
    
    const users = await User.find(query)
        .sort({ [sort]: order === 'asc' ? 1 : -1 })
        .limit(limit * 1)
        .skip((page - 1) * limit);
    
    res.json({
        data: users,
        pagination: {
            page: parseInt(page),
            limit: parseInt(limit),
            total: await User.countDocuments(query)
        }
    });
});

4.3 URL Versioning

// URL versioning
/api/v1/users
/api/v2/users

// Header versioning
Accept: application/vnd.api+json;version=1

// Implementation
app.use('/api/v1', v1Routes);
app.use('/api/v2', v2Routes);