API and API Design: API Security

APIs are essential to the architecture of modern software systems, but they also introduce new security risks. In this issue, we explored API Security and the OWASP Top 10.

Hello “👋

Welcome to another week, another opportunity to become a Great Backend Engineer.

Today’s issue is brought to you by Masteringbackend → A great resource for backend engineers. Learn backend development practically.

Before we get started, I have a few announcements:

I have a special gift for you: You will love this one.

The ultimate “Land Your Dream Job” Challenge is here.

We are launching the ultimate guide to landing your dream job in any programming language you choose. We are starting with the Python Programming language.

Land your dream Python Job in 90 days by shipping 30 Python projects in 30 days by completing our daily tasks.

It’s a cohort-based and project-focused challenge where you will be challenged to build 30 Python projects in 30 days.

Here is what you will get:

  • Ship 30+ Python backend projects in 30 days.

  • Instant Access to all 30+ videos

  • Access to data structure and algorithm interview kits.

  • Access our Complete Backend Job Preparation kits (Resume, Cover letter reviews, mock interviews, and job placements).

  • Join & learn from a thriving community of helpful students & alumni from top companies.

Limited Access. The first 500 students will be at $54, others at $100 (We have only 120 slots left.)

Introduction

Securing an API is not an afterthought—it is a fundamental aspect of the API design lifecycle.

As APIs increasingly serve as the connective tissue of modern applications, their exposure to the internet makes them attractive targets for cyberattacks.

Proper API security ensures that an API reliably fulfills its intended purpose while safeguarding sensitive data, maintaining service availability, and upholding user trust.

API security is a set of strategies, practices, and technologies designed to protect APIs from unauthorized access, abuse, data breaches, and performance degradation.

What is API Security?

API security encompasses the practices and tools used to secure APIs throughout their entire lifecycle. This includes measures to authenticate users, authorize access, validate inputs, encrypt data, limit usage, monitor behavior, and handle threats.

APIs expose business logic and data to a variety of clients—including browsers, mobile apps, third-party services, and IoT devices. Because of this broad exposure, any weakness in API design can become an attack vector.

Below are some of the core objectives of API Security:

Core Objectives of API Security

  • Prevent unauthorized access to sensitive resources.

  • Protect against data leaks and injection attacks.

  • Ensure high availability and mitigate DoS attacks.

  • Preserve data integrity and privacy.

Next, let’s explore some of the common API Security Threats according to OWASP Top 10 API Security report.

Common API Security Threats

According to OWASP Top 10 API Security 2023, there are top 10 web and API security vulnerabilities that should be implemented on every API by API developers, and below is the list of them.

  • Broken Authentication

  • Broken Object Level Authorization

  • Broken Object Property Level Authorization

  • Unrestricted Resource Consumption

  • Broken Function Level Authorization

  • Unrestricted Access to Sensitive Business Flows

  • Server-Side Request Forgery

  • Security Misconfiguration

  • Improper Inventory Management

  • Unsafe Consumption of APIs

Broken Authentication

APIs that fail to correctly validate tokens or credentials may allow unauthorized access. For example, consider a Node.js API using JWT for authentication but failing to verify the token properly:

// INSECURE: Token is extracted but not verified
app.get('/secure-data', (req, res) => {
  const token = req.headers['authorization'];
  const decoded = jwt.decode(token); // decode() does not verify signature
  if (!decoded) return res.status(401).send('Unauthorized');
  res.send('Sensitive data');
});

In this scenario, any user could tamper with or forge a token and gain access to protected routes because the server does not verify the signature of the JWT.

Solution:

Use jwt.verify() to ensure the token's integrity and authenticity:

const jwt = require('jsonwebtoken');

app.get('/secure-data', (req, res) => {
  const token = req.headers['authorization']?.split(' ')[1];
  if (!token) return res.status(401).send('Token missing');

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    res.send('Sensitive data');
  } catch (err) {
    res.status(403).send('Invalid token');
  }
});

This ensures that the token was not tampered with and that only authenticated users can access protected endpoints.

Excessive Data Exposure

Sending too much data in API responses can reveal sensitive or internal information, especially if the backend inadvertently sends entire database records or fields that should be hidden. This issue is covered under OWASP API Security Top 10: API3 – Excessive Data Exposure.

Consider this insecure Node.js/Express example:

// INSECURE: returns all user fields including sensitive data
app.get('/user/:id', async (req, res) => {
  const user = await db.User.findById(req.params.id);
  res.json(user); // Sends password hash, tokens, internal flags, etc.
});

In this code, sensitive information such as password hashes, tokens, or internal flags might be leaked in the API response.

Solution:

Use selective field projection or response filtering to return only what’s needed:

// SECURE: Sends only public-facing user fields
app.get('/user/:id', async (req, res) => {
  const user = await db.User.findById(req.params.id);
  if (!user) return res.status(404).send('User not found');

  const safeResponse = {
    id: user.id,
    name: user.name,
    email: user.email
  };

  res.json(safeResponse);
});

Alternatively, many ORMs like Mongoose offer built-in projection:

const user = await User.findById(req.params.id).select('id name email');

By explicitly defining the fields returned in API responses, developers can avoid leaking sensitive internal data and ensure better adherence to the principle of least privilege.

Lack of Rate Limiting

Without usage limits, APIs are vulnerable to brute-force attacks and abuse. Attackers can exploit endpoints by sending repeated requests to guess credentials, flood the system with traffic, or scrape data uncontrollably.

Here’s a Node.js/Express example that lacks rate limiting:

// INSECURE: No rate limiting middleware
app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const user = await db.User.findOne({ username });
  if (!user || user.password !== password) return res.status(401).send('Invalid credentials');
  res.send('Logged in');
});

In this case, a malicious actor could automate requests to brute-force user credentials, overwhelming the system or gaining unauthorized access.

Solution:

Implement rate-limiting middleware using express-rate-limit 

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

const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 10, // Limit each IP to 10 login requests per windowMs
  message: 'Too many login attempts from this IP, please try again later.'
});

app.post('/login', loginLimiter, async (req, res) => {
  const { username, password } = req.body;
  const user = await db.User.findOne({ username });
  if (!user || user.password !== password) return res.status(401).send('Invalid credentials');
  res.send('Logged in');
});

This effectively mitigates brute-force attempts and protects your authentication endpoint by throttling repeated access from the same IP address.

Injection Attacks

Improperly validated inputs may lead to SQL, command, or script injection. This vulnerability is listed as OWASP API Security Top 10: API8 – Injection.

Suppose we have a Node.js/Express API that takes user input and constructs a raw SQL query without any sanitization:

// INSECURE: Raw SQL query vulnerable to injection
app.get('/search', async (req, res) => {
  const { term } = req.query;
  const results = await db.query(`SELECT * FROM products WHERE name LIKE '%${term}%'`);
  res.json(results);
});

If a user enters something like %' OR '1'='1, this could result in the query:

SELECT * FROM products WHERE name LIKE '%%' OR '1'='1%'

This would return all products, allowing attackers to extract unintended data.

Solution:

Use parameterized queries or an ORM that automatically escapes user input:

// SECURE: Parameterized query using query placeholders
app.get('/search', async (req, res) => {
  const { term } = req.query;
  const results = await db.query('SELECT * FROM products WHERE name LIKE ?', [`%${term}%`]);
  res.json(results);
});

Alternatively, if using an ORM like Sequelize:

const results = await Product.findAll({
  where: {
    name: {
      [Op.like]: `%${term}%`
    }
  }
});

Always validate and sanitize user input. Never directly inject raw input into database queries, command shells, or other interpreters.

That will be all for this newsletter issue. However, in the next one, we will cover the remaining 6 from the OWASP Top 10.

Key Principles of API Security

  • Authentication: Ensure that only verified users or services can access the API. Use robust mechanisms such as OAuth 2.0, API keys, or JWT-based auth.

  • Authorization: After authentication, verify what actions the user or client is permitted to perform. Implement role-based access control (RBAC) or attribute-based access control (ABAC).

  • Input Validation: Sanitize and validate all input to prevent injection attacks and ensure data integrity.

  • Rate Limiting & Throttling: Protect resources from abuse by capping the number of requests a client can make.

  • Data Encryption: Use HTTPS/TLS to encrypt data in transit. For highly sensitive data, consider encrypting at rest as well.

  • Logging & Monitoring: Track API access, failed logins, and anomalies. Use tools like Prometheus, Grafana, or ELK stack.

  • Versioning & Deprecation: Avoid breaking changes by versioning APIs. Remove unused endpoints to reduce attack surface

APIs are essential to the architecture of modern software systems, but they also introduce new security risks. API security must be integrated from the earliest stages of design and remain a continuous practice throughout development and operation.

From authentication and authorization to input validation and traffic monitoring, a comprehensive API security strategy not only protects data and services—it also ensures trust, reliability, and compliance.

As APIs grow in number and complexity, so do the threats. Prioritize security, implement best practices, and choose the right tools to safeguard your API ecosystem.

Did you learn any new things from this newsletter this week? Please reply to this email and let me know. Feedback like this encourages me to keep going.

Remember to start learning backend engineering from our courses:

Get a 50% discount on any of these courses. Reach out to me (Reply to this mail)

Backend Engineering Resources

Whenever you're ready

There are 4 ways I can help you become a great backend engineer:

1. The MB Platform: Join 1000+ backend engineers learning backend engineering on the MB platform. Build real-world backend projects, track your learnings and set schedules, learn from expert-vetted courses and roadmaps, and solve backend engineering tasks, exercises, and challenges.

2. ​The MB Academy:​ The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

3. MB Video-Based Courses: Join 1000+ backend engineers who learn from our meticulously crafted courses designed to empower you with the knowledge and skills you need to excel in backend development.

4. GetBackendJobs: Access 1000+ tailored backend engineering jobs, manage and track all your job applications, create a job streak, and never miss applying. Lastly, you can hire backend engineers anywhere in the world.

LAST WORD đź‘‹ 

How am I doing?

I love hearing from readers, and I'm always looking for feedback. How am I doing with The Backend Weekly? Is there anything you'd like to see more or less of? Which aspects of the newsletter do you enjoy the most?

Hit reply and say hello - I'd love to hear from you!

Stay awesome,
Solomon

I moved my newsletter from Substack to Beehiiv, and it's been an amazing journey. Start yours here.

Reply

or to participate.