“In-depth Analysis of ”API Shield": Building a More Secure Cloudflare API Protection System
This article was last updated 287 days ago. The information within may have evolved or changed; if anything is outdated or broken, please feel free to leave a message in the comments section.
Article Abstract
To address the security protection needs of self-built APIs, Cloudflare API Shield achieves precise protection by defining endpoint paths, methods, and schema validation. The setup process includes manually adding API interfaces, uploading OpenAPI specification files for schema validation, and combining with WAF failure rules to block illegal requests. Validation shows that this solution can effectively block unexpected PUT/DELETE requests, while remaining compatible with the protection of key interfaces such as admin-ajax.php in scenarios like WordPress. In addition to basic configurations, multi-layered protection systems can be built by combining rate limiting, Bot Management, and other means, while F5's Distributed Cloud Bot Defense solution provides more complex protection expansion options for high-security demand scenarios.
Qwen3-14B · 2026-06-18

1 Introduction

Under the ”Security” tab of the Cloudflare dashboard, there is an ”API Shield” feature:

image.png

This feature is obviously designed specifically to protect APIs, but previously I didn't have any self-built APIs that needed protection, so I didn't have the opportunity totry it out for free andstudy this feature.

However, as I have recently written two articles involving self-built APIs (seeHome Data Center Series: Building an Efficient and Secure Random Image API: Cloudflare Worker + R2 + KV Practical Guide和Home Data Center Series: Cloudflare Worker + KV: Creating WordPress Cloud Article Reading Statistics), I suddenly realized that I already have the materials to study this feature. This week's research goal will be ”API Shield”.

Note: Cloudflare has recently launched a new dashboard, and the functional layout has changed significantly. For example, this ”API Shield” feature is called ”Web Assets” in the new dashboard:

image.png

However, to maintain compatibility with the Cloudflare-related articles I wrote previously, I am still using screenshots from the old dashboard.

2 Setup Steps

1 Add Endpoints

1.1 What is an Endpoint and the Purpose of Creating Endpoints

In Cloudflare's API protection, an ”endpoint” refers to a specific access entry point and access method of an API. For example, when I previously set up cloud article reading statistics, I used ”/views-track” as the API entry point for recording and querying article reading counts.

The core of an endpoint lies in defining the normal access scope of the API, including allowed request paths, request methods (such as GET, POST, etc.), sources (such as specific IPs or domains), and expected access patterns. By defining these rules, Cloudflare can identify which requests are normal and conform to business logic, and which may be abnormal or malicious traffic, thereby establishing a clear access boundary and laying the foundation for subsequent traffic monitoring, abuse detection, and protection policies. For example, if an endpoint is supposed to only accept POST requests but receives a large number of GET requests, this could be a potential abuse behavior.

1.2 Three Ways to Add Endpoints

In the ”Endpoint Management” - “Add Endpoint” section, you can add endpoints:

image.png

Cloudflare provides 3 ways to add endpoints: manual addition, uploading schema, and selecting from Discover:
image.png

  • “Manual addition” is suitable for situations where the API endpoint needs to be precisely defined, allowing users to enter information such as paths and request methods (excluding request details) on their own;
  • “Uploading schema” supports importing standardized API specification files such as OpenAPI (Swagger), making batch management of multiple endpoints more efficient;
  • “Selecting from Discover” is only available to ”Enterprise users”. This method can automatically discover active APIs and generate endpoint recommendations based on actual traffic analysis, helping users manage API protection rules more easily.

Since I am not a distinguished ”Enterprise user”, this article only covers two ways of adding endpoints: ”manual addition” and ”uploading schema”.

1.3 Practical Guide to “Manually Adding” Endpoints

This section will use myHome Data Center Series: Cloudflare Worker + KV: Creating WordPress Cloud Article Reading StatisticsAPI implemented by the Worker code in the article as an example for addition. The specific Worker code is as follows:

export default {
  async fetch(request, env) {
    const url = new URL(request.url);

    // 处理 GET 请求 -> 查询阅读次数
    if (request.method === "GET" && url.pathname === "/views-track") {
      return await handleGetRequest(url, env);
    }

    // 处理 POST 请求 -> 记录并返回最新阅读次数
    if (request.method === "POST" && url.pathname === "/views-track") {
      return await handlePostRequest(request, env);
    }

    return new Response("Invalid request", { status: 405 });
  }
};

// 处理 GET 请求 -> 查询 KV 获取阅读量
async function handleGetRequest(url, env) {
  const slug = url.searchParams.get("slug");

  if (!isValidSlug(slug)) {
    return new Response("Invalid slug format", { status: 400 });
  }

  const kvKey = `views:{slug}`;
  const currentViews = parseInt(await env.views_kv.get(kvKey)) || 0;

  return new Response(JSON.stringify({ success: true, views: currentViews }), {
    headers: jsonHeaders(),
  });
}

// 处理 POST 请求 -> 记录阅读量
async function handlePostRequest(request, env) {
  try {
    const { slug } = await request.json();

    if (!isValidSlug(slug)) {
      return new Response("Invalid slug format", { status: 400 });
    }

    const kvKey = `views:{slug}`;
    const currentViews = parseInt(await env.views_kv.get(kvKey)) || 0;
    await env.views_kv.put(kvKey, (currentViews + 1).toString());

    return new Response(JSON.stringify({ success: true, views: currentViews + 1 }), {
      headers: jsonHeaders(),
    });
  } catch (error) {
    console.error("Worker Error:", error);
    return new Response("Internal Server Error", { status: 500 });
  }
}

// 校验 slug 格式
function isValidSlug(slug) {
  return slug && /^[a-z0-9-]{1,100}$/.test(slug);
}

// 统一 JSON 响应头
function jsonHeaders() {
  return {
    "Content-Type": "application/json",
    "Cache-Control": "no-store",
    "CF-Cache-Status": "BYPASS",
  };
}

From the code above, we can see that the access path of this API is ”/views-track”, with methods including GET requests (used to query article reading counts) and POST requests (used to record reading counts). The hostname is determined by the Worker's URL routing entry, which is my blog's domain name: ”blog.tangwudi.com”. Therefore, the final configuration of the endpoint is as follows:

image.png

Then, you can see the access status of the created endpoint:
image.png

You can also view the detailed content further:
image.png

Note 1: API Shield's endpoints are mainly used to define known requests of the API (method + path + hostname). However, it does not automatically block unmatched request methods by itself. For example, even if an endpoint only has GET requests added, POST requests will still not be directly blocked by API Shield. They must be restricted using the WAF custom rules associated with the subsequent “Failure Settings”.

Note 2: ”Manually added” endpoints currently only define the API's request methods (such as GET/POST) and paths, but do not restrict the specific request content format, so there is still a certain risk of abuse. For example, in a GET request, the expected format of the API is /views-track?slug=xxx, but an attacker might send /views-track?slug=some_random_garbage_data, causing the system to process invalid data or waste resources. In a POST request, the expected request body structure of the API is { “slug”: “xxx” }, but an attacker might submit { “slug”: 123 }, { “random_field”: “hacker” }, or even an empty body, which might trigger errors or attempt to bypass restrictions. Therefore, relying solely on ”manually added” endpoints is not enough to define fully compliant API request formats. To be rigorous, you also need to restrict request content through ”schema validation” or WAF custom rules.

Note 3: For users building websites with WordPress, it is recommended to also add the path ”/wp-admin/admin-ajax.php” (with POST as the request method) to the API Shield endpoints, because many themes and plugins (such as Rank Math SEO, WooCommerce, Lazy Load image plugins, etc.) rely on this interface for AJAX interactions. In addition, if the website involves front-end interactions, such as liking, comment loading, form submission, or asynchronous data retrieval, admin-ajax.php is also essential, and the vast majority of these operations use the POST request method.

1.4 “Schema Validation” + “Upload Schema” (Optional but Highly Recommended)

1.4.1 Advantages of Schema Validation

Schema validation is not a mandatory option for API Shield, but when adopting “uploading schema” to import standardized API specification files such as OpenAPI (Swagger), it can provide more manually adding endpoints granular API protection.

As I mentioned earlier, manually added endpoints only define the API's allowed path + method, but do not restrict specific request parameters, request body structures, and data types, which means attackers can still send malformed data, thereby affecting system stability or consuming resources.

Schema validation, on the other hand, strictly validates whether API requests comply with Expected format, such as the “slug” field must be a string and cannot be an integer; required fields cannot be missing, and irrelevant fields cannot be included. If both the API provider and caller follow the OpenAPI specification, schema validation can also ensure consistent data structures, avoiding compatibility issues caused by incorrect parameter formats, and improving API stability and maintainability.

In addition, schema validation can be combined with API Shield's “Fallback Behavior” and WAF rules to not only restrict request paths and methods, but also validate requests at the field, data type, and structure levels: if “Fallback Behavior” is enabled, unregistered API requests will be blocked by WAF rules, while schema validation ensures that the request format of registered APIs meets expectations, thereby further enhancing API protection.

Therefore, if the API adopts the standardized OpenAPI specification and you wish to strictly validate the request format, enabling schema validation will greatly enhance security; however, if the API does not use standard specifications, schema validation is not a necessary step, and you can filter request content through WAF custom rules instead.


To use schema validation, an API schema description file that complies with the OpenAPI specification is required. Taking my cloud article statistics API ”/views-track” as an example, the content of its schema description file in yml format is as follows for your reference:

openapi: 3.0.3"".

Save the above content as a ”views-track.yml” file, which will be used in the practical operation later.

In addition, Umami's server-side API and random image API can both be protected using schema validation. Taking Umami as an example, according to the description of the API in its official documentation, the content of its corresponding API schema file is as follows (yml), which can be used directly by those who need it (the URL in the servers section needs to be modified according to your own website):

openapi: 3.0.1
info:
  title: Umami Tracking API
  description: API definition for Umami event tracking.
  version: 1.0.0
servers:
  - url: https://umami.tangwudi.com/api
paths:
  /send:
    options:
      summary: Preflight request for CORS
      description: This allows browsers to check allowed methods before sending data.
      responses:
        "204":
          description: No content, preflight request successful.
    post:
      summary: Send tracking data
      description: Send analytics events and page views to Umami.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                type:
                  type: string
                  enum: [event, pageview]
                  description: Type of tracking data.
                payload:
                  type: object
                  description: Tracking payload containing event details.
                  properties:
                    website:
                      type: string
                      description: Website UUID.
                    hostname:
                      type: string
                      description: Hostname of the site.
                    screen:
                      type: string
                      description: Screen resolution of the client.
                    language:
                      type: string
                      description: Language of the client browser.
                    title:
                      type: string
                      description: Page title.
                    url:
                      type: string
                      description: Page URL.
      responses:
        "200":
          description: Tracking data received successfully.
        "400":
          description: Bad request, invalid payload.
        "403":
          description: Forbidden request.
        "500":
          description: Internal server error.

1.4.2 Practical Guide to “Schema Validation” + “Upload Schema”

Enable Schema Validation

Initially, schema validation is disabled by default and needs to be enabled:

image.png

Upload Schema

In ”API Shield” - “Settings”, upload the ”views-track.yml” schema file:

image.png

image.png

image.png

Then, you can already see the uploaded schema in the ”Uploaded Schemas” section:
image.png

At this point, in the schema validation section, you can see that the available schema after ”/views-track” has changed to ”views-track.yml”, and you can also see how many non-compliant requests there have been within 24 hours:
image.png

2 Failure Settings

As mentioned earlier, the endpoint section merely defines what the API allows in a simple manner path + method, and it does not automatically block unmatched request methods by itself. To block unmatched request methods, you need to rely on the WAF custom rules created in the ”Fallback Behavior” section:

image.png

Follow these steps to associate WAF custom rules in ”Fallback Behavior”:
image.png

image.png

image.png

After adding the rule for ”admin-ajax.php”, it looks like this:
image.png

Note 1: Failure settings are not automatically associated with WAF custom rules by default: if the endpoint is added manually for the first time, you need to manually create the failure rule based on the template; if the endpoint is created by uploading a schema file for the first time, Cloudflare will automatically generate the corresponding failure rule.

Note 2: In WordPress, besides the most commonly used API “/wp-admin/admin-ajax.php”, there is also the “/wp-json/*“ API, which is used to provide a REST-based data interaction interface, allowing plugins, themes, and external applications to access and manipulate WordPress content through standard HTTP requests (such as GET, POST, PUT, DELETE), such as retrieving posts, submitting comments, user authentication, etc.However, compared to “admin-ajax.php”, ”/wp-json” is not very commonly used, because many plugins and themes still rely on traditional AJAX methods for data interaction, while the REST API is mainly used frequently when developing custom applications or external integrations. In addition, some sites may disable “/wp-json” for security reasons to reduce exposed API interfaces (like me), so I did not include this API in the demonstration configuration. For those who need this API, you need to consider the relevant configurations in the endpoints and failure settings.

3 Validation

Use curl commands to construct requests using methods other than GET and POST to verify whether the policy configured in ”API Shield” is effective. If it is, the expected result is403 Forbiddenresponse, and there should be a corresponding blocked request record in the ”Failure Rules” of the Cloudflare dashboard WAF.

Use the PUT request method:

curl -X PUT "https://blog.tangwudi.com/views-track" -i

image.png

Then confirm in the ”Failure Rules” of Cloudflare WAF custom rules whether there are any matched access requests:
image.png

Use the DELETE request method:

curl -X DELETE "https://blog.tangwudi.com/views-track" -i

image.png

Then confirm in the ”Failure Rules” of Cloudflare WAF custom rules whether there are any matched access requests:
image.png

Verification successful.

4 Other Security Configurations

The purpose of Cloudflare launching the “API Shield” feature is to protect existing APIs: predefine legitimate API access methods, and then, by allowing legitimate access, handle illegitimate access in the pre-configured manner (failure rules) to achieve the goal of securing legitimate API access requests.

However, “API Shield” is not the only means of securing API access; there are also methods such as rate limiting and WAF custom rules (via conditions like Referer). Therefore, in practical applications, API protection is often a combination of multiple methods. For example, rate limiting can prevent malicious users from frequently accessing APIs to avoid resource abuse, while WAF custom rules can intercept based on specific request characteristics (such as Referer, User-Agent, IP address, etc.) to block unauthorized or abnormal traffic.

In addition, it can also be combined with Cloudflare's Bot Management feature to identify and block automated scrapers or malicious attack scripts, further reducing the risk of API abuse. Meanwhile, using mTLS (mutual TLS authentication) or API Tokens for authentication can also ensure the compliance of API access at the source.

Therefore, in practical scenarios, using “API Shield” alone cannot cover all API protection needs. Instead, it needs to be combined with other measures to form a complete API security protection system, so as to minimize the risk of API abuse while ensuring stable access for normal business traffic.

3 Extended Knowledge: F5 Distributed Cloud Bot Defense

I accidentally saw that F5 also has a solution to protect users' APIs (the original link is as follows:Protect your Cloudflare CDN deployment with F5 Distributed Cloud Bot Defense), and out of interest, I did some research on it:

image.png

image.png

image.png

Overall, F5's solution utilizes Cloudflare Workers for API protection. It primarily intercepts API requests via the Worker, forwards them to F5's API protection system for analysis and verification, and finally decides whether to allow, block, or challenge the request based on the results returned by the F5 API. The general workflow is as follows:

When an API request enters the Cloudflare Worker, the Worker is responsible for intercepting the traffic and extracting key information such as request headers and request bodies. The purpose of this step is to perform preliminary processing before the request reaches the origin API, enabling subsequent security detection to identify risks more accurately.

Subsequently, the Worker sends the extracted request data to F5's API protection system. F5 is responsible for conducting an in-depth analysis of this data, such as identifying whether the request comes from automated bots, detecting malicious traffic, or verifying whether the token in the request is valid. Through these checks, F5 can determine whether the request meets security standards.

Finally, the Worker decides how to handle the request based on the analysis results returned by F5: if F5 deems the request legitimate, the Worker forwards it normally to the origin API; however, if F5 determines the request is malicious traffic, the Worker will directly return a 403 status code or a specific response based on custom rules to protect the API from attacks.

Simply put, if budget permits, API traffic is high, and AI-level protection is required, you can use Worker + F5; if budget is tight, Cloudflare API Shield is actually barely enough (at best, you can leverage schema validation).


In this solution, Cloudflare Worker is not responsible for complex security analysis but rather acts as a proxy. Its main tasks include intercepting API requests, collecting necessary data, sending it to F5 for security detection, and deciding whether to allow or directly block the request based on F5's judgment. The Worker itself does not perform deep security analysis; instead, it relies on F5's security capabilities to complete this task.

The reason for choosing a Worker-based implementation is that Cloudflare WAF can only block requests based on predefined rules, lacking more flexible decision-making capabilities. Workers, on the other hand, can make more complex judgments, such as identifying bot behavior and analyzing user behavior patterns. Additionally, F5's API protection capabilities are stronger than Cloudflare WAF, but F5 cannot directly protect APIs hosted on Cloudflare. Therefore, the Worker acts as an intermediary layer here, ensuring that the API is protected by F5's security while enabling smarter traffic management on Cloudflare's edge network.


4 Summary

Actually, strictly speaking,API Shield 's core features (such as allowing only specific request methods, specific paths, rate limiting, etc.) can be implemented by combining WAF custom rules and rate limiting features. For example:

• Restricting request methods: WAF rules can match http.request.method to only allow GET or POST.

• Restricting request paths: WAF rules can match http.request.uri.path to ensure API access meets expectations.

• Restrict request sources: Rules can be set based on referer or IP to prevent unauthorized access.

• Rate limiting: Cloudflare also provides WAF's rate limiting, similar to partial protection of API Shield.

The advantage of API Shield is that it makes API protection functionsmodular and visual, for scenarios where a large number of APIs need to be managed, API Shield can reduce the workload of manually maintaining rules, and combine with mTLS (client certificate verification) to further enhance security.

Therefore, if your API protection needs are relatively simple, WAF custom rules are sufficient, but if it is large-scale API protection or has stricter security requirements, API Shield will give you more peace of mind.

View Related Categories · 3 Matches
📌 Content Structure Prompt:
This content is part of the following knowledge map, where you can view the complete content path: Cloudflare Learning Map。
📎 Related Articles
Share this article
The blog content is original, please indicate the source when reposting! The RSS address of the blog is:https://blog.tangwudi.com/feed, welcome to subscribe; if needed, you can join theTelegram Groupto discuss questions together.
No Comments

Send Comment Edit Comment


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗ
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
Kaomoji
Emoji
Little Dinosaur
Flower!
Previous
Next
       

👋 Welcome to “Wudi's Personal Blog”

Here, long-term exploration is mainly carried out around the following directions:

🧱 Personal Digital Infrastructure and Blog System Construction
☁️ Cloudflare and Network Architecture Practice
🧠 AI and Knowledge System Exploration
🛡️ Network Security and Access Optimization
🎵 Music and Sound Cognition
👁️ Cognitive Perspectives and Worldviews