#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
7 min read
•Question 16 of 28hard

What are API security best practices?

Essential security measures for APIs.

What You'll Learn

  • Authentication & authorization
  • Input validation
  • Security headers

Authentication & Authorization

code.jsJavaScript
// Always use HTTPS
// Use strong authentication (JWT, OAuth)
// Implement proper authorization checks

app.get('/users/:id', authenticate, async (req, res) => {
  // Check if user can access this resource
  if (req.user.id !== req.params.id && !req.user.isAdmin) {
    return res.status(403).json({ error: 'Forbidden' });
  }
  // ...
});

Input Validation

code.jsJavaScript
const { body, validationResult } = require('express-validator');

app.post('/users',
  body('email').isEmail().normalizeEmail(),
  body('password').isLength({ min: 8 }),
  body('name').trim().escape(),
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(422).json({ errors: errors.array() });
    }
    // ...
  }
);

Security Headers

code.jsJavaScript
const helmet = require('helmet');
app.use(helmet());

// Manual headers
app.use((req, res, next) => {
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.setHeader('X-Frame-Options', 'DENY');
  res.setHeader('X-XSS-Protection', '1; mode=block');
  next();
});

Rate Limiting & Throttling

code.jsJavaScript
const rateLimit = require('express-rate-limit');

app.use(rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100,
}));

Other Best Practices

  • Never expose sensitive data in URLs
  • Log security events
  • Use parameterized queries (prevent SQL injection)
  • Sanitize all user inputs
  • Implement request size limits