How to Create a Proxy in MuleSoft: A Step-by-Step Guide
The modern digital landscape is an intricate web of interconnected services, constantly exchanging data to power applications, enhance user experiences, and drive business innovation. At the heart of this interconnectedness lie Application Programming Interfaces, or APIs. These digital contracts define how different software components should interact, becoming the fundamental building blocks of almost every software system today. However, as the number of APIs consumed and exposed by an organization grows, so does the complexity of managing, securing, and optimizing them. This is where the concept of an API proxy becomes not just beneficial, but essential.
An API proxy acts as an intermediary, sitting between the client applications and the backend services they need to access. It intercepts requests, applies policies, and forwards them to the appropriate backend, then receives responses, applies further policies, and sends them back to the client. This seemingly simple role unlocks a multitude of advantages, from bolstering security and improving performance to simplifying integration and gaining deep insights into API usage. It essentially transforms raw backend services into managed, secure, and resilient APIs.
MuleSoft, with its powerful Anypoint Platform, stands out as a leading solution for enterprise integration, offering comprehensive capabilities for building, managing, and securing APIs, including the robust creation and deployment of API proxies. Its unified platform provides a complete lifecycle management solution for APIs, making it an invaluable tool for organizations navigating the complexities of modern digital ecosystems. Whether you're looking to protect sensitive backend systems, enforce strict access controls, optimize response times, or simply gain better visibility into your API traffic, understanding how to leverage MuleSoft for API proxy creation is a critical skill.
This exhaustive guide is designed to take you on a deep dive into the world of MuleSoft API proxies. We will embark on a step-by-step journey, starting from the foundational understanding of what an API proxy is and why it's indispensable, moving through the practical details of setting up your MuleSoft environment, creating your first proxy application in Anypoint Studio, deploying it, and crucially, managing it with Anypoint API Manager to enforce critical policies. We will also explore advanced configurations, best practices, and real-world use cases, ensuring you gain a holistic and practical understanding. By the end of this article, you will not only be equipped to build and manage powerful API proxies using MuleSoft but also appreciate their strategic importance in your organization's digital strategy. Let's begin the journey to master API proxy creation with MuleSoft.
Chapter 1: Understanding API Proxies and Their Indispensable Role
The concept of an API proxy is fundamental to modern API architecture, serving as an intelligent gatekeeper positioned between API consumers and the actual backend services. Far more than a simple passthrough mechanism, a proxy is a powerful abstraction layer that adds significant value without requiring any modifications to the underlying service. It acts as a single point of entry for clients, handling a multitude of concerns that would otherwise need to be managed by each client or embedded within the backend service itself, leading to redundancy and increased complexity.
What Exactly is an API Proxy?
At its core, an API proxy is a server application that intermediates client requests to another server. When a client makes a request to an API, it doesn't directly call the backend service; instead, it calls the proxy. The proxy then processes this request, applies various rules and policies, and forwards it to the intended backend API. Once the backend service responds, the proxy intercepts the response, applies any post-processing rules, and then delivers it back to the client. This "man-in-the-middle" position grants it immense power and flexibility. It effectively creates a façade for the backend service, abstracting its location, implementation details, and even its specific data formats from the consumers. Think of it as a specialized switchboard operator for your digital services, directing calls, enforcing rules, and ensuring smooth communication.
The Multifaceted "Why" Behind API Proxies
The decision to implement an API proxy is rarely driven by a single factor; rather, it's a strategic move that delivers a wide array of benefits across security, performance, management, and architectural agility. Understanding these advantages is key to appreciating the indispensable role proxies play in a robust API gateway ecosystem.
1. Enhanced Security: The First Line of Defense
Security is paramount in any networked system, and APIs are frequently targeted vectors for cyberattacks. An API proxy acts as the initial barrier against malicious actors, shielding your sensitive backend systems from direct exposure to the public internet.
- Authentication and Authorization: Proxies can enforce strict access controls. They can validate API keys, OAuth tokens, JWTs (JSON Web Tokens), or other authentication credentials before any request even reaches the backend. This offloads the security burden from individual backend services, centralizing control and ensuring consistent application of policies. For instance, a proxy can reject requests lacking a valid client ID or an expired access token, preventing unauthorized access at the perimeter.
- Threat Protection: Proxies are adept at identifying and mitigating various types of threats. They can implement IP whitelisting/blacklisting to block known malicious sources or only allow access from trusted networks. They can also perform payload validation to detect malformed requests, SQL injection attempts, or cross-site scripting (XSS) attacks before they penetrate deeper into your infrastructure.
- Data Masking and Encryption: For responses containing sensitive information, a proxy can mask or redact specific fields before sending them back to the client, ensuring that only authorized data is exposed. It can also manage SSL/TLS encryption, securing data in transit between clients and the proxy, and often between the proxy and the backend, creating an end-to-end secure channel.
2. Optimized Performance and Scalability: Delivering Speed and Reliability
Performance is a critical determinant of user experience and system reliability. API proxies offer several mechanisms to boost the speed and resilience of your API ecosystem.
- Caching: One of the most significant performance enhancements a proxy offers is caching. Frequently requested data can be stored at the proxy level, allowing subsequent requests for the same data to be served directly from the cache without hitting the backend. This dramatically reduces backend load and response times, especially for static or semi-static data.
- Rate Limiting and Throttling: To prevent abuse, manage resource consumption, and ensure fair usage, proxies can enforce rate limits, restricting the number of requests a client can make within a specified timeframe. Throttling can also be implemented to smooth out traffic spikes, protecting backend services from being overwhelmed during peak loads, thereby ensuring service continuity and stability.
- Load Balancing: When multiple instances of a backend service are available, a proxy can intelligently distribute incoming requests among them. This load balancing capability improves resource utilization, prevents any single server from becoming a bottleneck, and enhances the overall availability and responsiveness of the api.
3. Streamlined Management and Governance: Order Amidst Complexity
As organizations expand their API footprint, managing them effectively becomes increasingly challenging. Proxies bring much-needed order and control.
- Centralized Policy Enforcement: All policies—security, QoS, transformation—can be applied and managed from a single point, the proxy. This ensures consistency across all API consumers and simplifies policy updates and audits.
- Monitoring and Analytics: Proxies provide a choke point for all API traffic, making them ideal for collecting detailed telemetry data. This includes request counts, response times, error rates, and client usage patterns. This data is invaluable for performance monitoring, capacity planning, identifying issues, and understanding API adoption.
- Versioning and Deprecation: Proxies facilitate seamless API versioning. When a new version of a backend API is deployed, the proxy can route traffic accordingly, allowing older versions to coexist or gracefully deprecate. This means clients consuming older versions can continue to operate without immediate changes, while new clients can leverage the latest capabilities.
- Developer Portal Integration: Often, proxies are integrated with developer portals, providing documentation, SDKs, and a self-service experience for API consumers to discover, subscribe to, and test APIs.
4. Architectural Abstraction and Flexibility: Decoupling and Agility
Proxies introduce a crucial layer of abstraction, fostering greater architectural flexibility and agility.
- Decoupling Clients from Backends: Clients interact with the stable proxy endpoint, not the potentially volatile backend service. This means backend services can be refactored, migrated, scaled, or even replaced without impacting client applications, as long as the proxy maintains its contract.
- Protocol Translation: Proxies can bridge disparate technologies. For instance, they can expose a legacy SOAP service as a modern RESTful API, allowing new applications to consume it easily without understanding the complexities of SOAP. This is incredibly valuable for modernizing legacy systems.
- Message Transformation: Incoming requests or outgoing responses can be transformed by the proxy to meet specific requirements. This could involve converting data formats (e.g., XML to JSON), adding or removing headers, or restructuring payloads, making the api more consumable for diverse clients.
API Proxies vs. Direct API Calls vs. Traditional Proxies
It's important to distinguish API proxies from related concepts:
- Direct API Calls: Without a proxy, clients directly access backend services. This is simpler to set up initially but quickly becomes unmanageable as the number of APIs and clients grows, lacking centralized security, governance, and performance optimization.
- Traditional Proxies (e.g., HTTP Proxy Servers): These are generally network-level components that forward HTTP requests for various purposes like internet access, caching, or security for outbound traffic from a network. An API proxy, on the other hand, is specifically designed for inbound API traffic, understanding the semantics of API requests and responses, and offering API-specific management features as part of an API gateway solution. The core difference lies in their scope and intelligence: API proxies are application-aware and policy-driven for API traffic.
The Role of an API Gateway in the API Economy
An API gateway is essentially a collection of API proxies and their associated management infrastructure, offering a comprehensive solution for managing the entire API lifecycle. It consolidates many of the functions of individual API proxies into a single, unified platform. Think of the API gateway as the orchestrator and central control plane for all your API proxies. It provides a consistent way to apply security, rate limiting, caching, monitoring, and other policies across all your APIs. For large enterprises with hundreds or thousands of APIs, an API gateway is not just an option; it's a necessity for maintaining control, ensuring security, and driving efficient API consumption and production. MuleSoft's Anypoint Platform exemplifies a robust API gateway solution, offering all these capabilities and more.
By leveraging an API proxy, and by extension an API gateway, organizations can transform their backend services into robust, secure, and easily consumable APIs, accelerating digital transformation and fostering innovation within the API economy.
Chapter 2: Introduction to MuleSoft and the Anypoint Platform
In the complex ecosystem of enterprise integration, MuleSoft has emerged as a dominant force, providing a comprehensive platform that simplifies the arduous task of connecting applications, data, and devices. At its core, MuleSoft is an integration platform designed to unlock data from various systems and expose it as consumable APIs, fostering a composable enterprise where systems can be easily connected and recombined to meet evolving business needs. Its Anypoint Platform is a unified, full-lifecycle API gateway and integration platform that enables organizations to design, build, deploy, manage, and secure APIs and integrations.
What is MuleSoft?
MuleSoft is a vendor of an integration platform that facilitates the connection of disparate applications, data sources, and devices. It provides a lightweight enterprise service bus (ESB) called Mule Runtime, which is the engine that executes integration logic. What sets MuleSoft apart is its API-led connectivity approach. Instead of traditional point-to-point integrations that become brittle and unmanageable over time, MuleSoft champions the idea of exposing reusable services as APIs. This allows organizations to create a network of applications and data that is agile, scalable, and resilient. By transforming data and services into accessible APIs, MuleSoft empowers businesses to innovate faster, leveraging existing assets more effectively.
Key Components of the Anypoint Platform
The Anypoint Platform is a central hub for all MuleSoft operations, offering a suite of interconnected tools that cover the entire API and integration lifecycle. Understanding these components is crucial for effectively creating and managing API proxies.
1. Anypoint Design Center
This is where the API journey often begins. Design Center provides a web-based interface for designing, documenting, and testing APIs using industry-standard specifications like RAML (RESTful API Modeling Language) and OpenAPI Specification (OAS/Swagger). It allows developers to create clear, contract-first API definitions, collaborate on designs, and simulate API behavior even before any backend implementation exists. This contract-first approach ensures consistency and clarity, defining how the API should behave before it's built, which is essential for proxy creation.
2. Anypoint Exchange
Anypoint Exchange serves as a central repository for all reusable API assets within an organization. Once an API specification is designed in Design Center, it can be published to Exchange. This acts as an internal marketplace where developers can discover, reuse, and share APIs, connectors, templates, and examples. For API proxies, Exchange is vital because you often start by importing an existing API definition from Exchange to generate the proxy structure, ensuring the proxy adheres to the agreed-upon API contract. It enhances discoverability and promotes standardization across the organization's API landscape.
3. Anypoint Studio
Anypoint Studio is the integrated development environment (IDE) that developers use to build Mule applications. It's an Eclipse-based tool that provides a graphical interface for dragging and dropping components to create complex integration flows, along with a powerful data transformation language called DataWeave. For API proxies, Anypoint Studio is where the actual Mule application that is the proxy is built, configured, and tested locally before deployment. It allows for fine-grained control over how requests are processed, how errors are handled, and how data is transformed.
4. Anypoint Runtime Manager
Once a Mule application (including an API proxy) is developed, it needs to be deployed and managed. Anypoint Runtime Manager is the operational center of the platform. It provides a centralized interface for deploying, monitoring, and managing Mule applications running on various environments: CloudHub (MuleSoft's cloud platform), customer-hosted runtimes (on-premises or private cloud), or hybrid deployments. From Runtime Manager, you can scale applications, view logs, restart services, and perform health checks, ensuring the continuous availability and performance of your API proxies.
5. Anypoint API Manager
This component is arguably the most critical for API proxy management. Anypoint API Manager is where you enforce runtime policies on your APIs, register API instances, and gain control over their lifecycle. After deploying an API proxy application, you register it with API Manager, turning it into a managed API. Here, you can apply out-of-the-box or custom policies for security (e.g., client ID enforcement, OAuth 2.0), quality of service (e.g., rate limiting, caching), and transformation. It acts as the operational API gateway for your managed APIs, ensuring that all incoming requests are subject to the defined rules and regulations, providing centralized governance and visibility.
6. Anypoint Monitoring
Complementing API Manager, Anypoint Monitoring provides deep insights into the performance and health of your Mule applications and APIs. It offers real-time dashboards, custom alerts, and detailed metrics on API traffic, response times, error rates, and resource utilization. This powerful tool helps identify bottlenecks, troubleshoot issues proactively, and ensure the optimal functioning of your API proxies, allowing you to make data-driven decisions about your API landscape.
Why MuleSoft for API Proxies?
MuleSoft's Anypoint Platform is exceptionally well-suited for creating and managing API proxies due to several compelling reasons:
- Unified, Full-Lifecycle Platform: Unlike fragmented solutions that require stitching together different tools for design, implementation, deployment, and management, MuleSoft offers a single, integrated platform. This streamlines the entire API lifecycle, from conception to retirement, reducing overhead and complexity.
- Robust API Gateway Capabilities: Anypoint API Manager serves as an enterprise-grade API gateway, providing powerful policy enforcement mechanisms. It allows organizations to centrally apply security, QoS, and custom policies across all their APIs, ensuring consistent governance and control.
- API-Led Connectivity: MuleSoft's core philosophy encourages exposing services as reusable APIs. This naturally aligns with the concept of proxies, which are fundamental to abstracting backend services and presenting them as managed APIs.
- Flexible Deployment Options: Whether your applications run in the cloud (CloudHub), on-premises, or in a hybrid model, MuleSoft provides flexible deployment options through Runtime Manager, giving you the freedom to deploy your proxies where they make the most sense for your infrastructure.
- Powerful Data Transformation: DataWeave, MuleSoft's expression language, is incredibly powerful for complex data transformations. This is crucial for proxies that might need to convert data formats, restructure payloads, or mask sensitive information between client and backend.
- Extensibility and Customization: While the platform offers many out-of-the-box features, it also allows for extensive customization through custom policies, connectors, and integration flows, enabling you to tailor your API proxies to very specific business requirements.
In essence, MuleSoft provides a mature and comprehensive environment for building not just API proxies, but an entire network of interconnected, managed, and secure APIs, positioning it as a strategic partner for organizations undergoing digital transformation. The gateway functionality within Anypoint Platform is a key differentiator, empowering businesses to exert granular control over their API landscape.
Chapter 3: Pre-requisites and Initial Setup for Building a MuleSoft API Proxy
Before we dive into the practical steps of creating an API proxy in MuleSoft, it's crucial to ensure your development environment is correctly set up and you have access to the necessary resources. This foundational preparation will streamline the entire process and prevent common hurdles.
1. MuleSoft Anypoint Platform Account
The Anypoint Platform is the central hub for all MuleSoft activities, including API design, management, and deployment. You will need an active account to access its web-based components like Design Center, Exchange, API Manager, and Runtime Manager.
- Account Creation: If you don't already have one, you can sign up for a free trial account on the MuleSoft website. This trial typically offers sufficient resources to follow along with this guide, including access to CloudHub for deployment.
- Understanding Roles and Permissions: Ensure your Anypoint Platform account has the necessary permissions to:
- Create and publish API specifications in Design Center and Exchange.
- Deploy applications to CloudHub (or your target runtime).
- Manage APIs in API Manager (register APIs, apply policies).
- Access Anypoint Studio credentials (if you plan to deploy from Studio).
2. Anypoint Studio Installation
Anypoint Studio is your primary development environment for building the Mule application that will serve as your API proxy.
- Download: Download the latest stable version of Anypoint Studio from the MuleSoft website (Anypoint Platform > Help > Download Anypoint Studio).
- System Requirements: Ensure your development machine meets the minimum system requirements for Anypoint Studio, particularly regarding RAM (8GB+ recommended) and disk space.
- Installation: Anypoint Studio is typically a standalone application that you simply extract to a directory of your choice. No complex installation wizard is usually required.
- Workspace: Upon launching Studio, you'll be prompted to select a workspace. Choose a clear, accessible location on your hard drive. This is where your Mule projects will be stored.
- Runtime Version: Anypoint Studio comes bundled with a Mule Runtime, but it's good practice to ensure it matches or is compatible with the runtime version you plan to use for deployment (e.g., CloudHub defaults to the latest stable runtime).
3. Basic Understanding of API Concepts
While this guide provides detailed instructions, a fundamental grasp of core API concepts will greatly aid your understanding and troubleshooting.
- REST (Representational State Transfer): Understand that REST APIs are stateless, client-server architectures that use standard HTTP methods (GET, POST, PUT, DELETE) for resource manipulation.
- HTTP (Hypertext Transfer Protocol): Familiarity with HTTP methods, status codes (200 OK, 400 Bad Request, 401 Unauthorized, 500 Internal Server Error), headers (Content-Type, Authorization), and request/response structures is essential.
- JSON/XML: APIs commonly exchange data in JSON (JavaScript Object Notation) or XML formats. Knowing how these structures work will be helpful for understanding API specifications and potential data transformations.
- URL Structure and Path Parameters/Query Parameters: Understand how endpoints are defined and how data can be passed through URLs.
4. A Sample Backend API to Proxy
To create an API proxy, you need an existing backend service that the proxy will front. For the purpose of this guide, having a simple, accessible RESTful API is sufficient.
- Option 1: Public Test API: You can use a publicly available test API like JSONPlaceholder (
https://jsonplaceholder.typicode.com/posts) or ReqRes (https://reqres.in/api/users). These are excellent for basic pass-through proxy testing. - Option 2: Mock API: You can set up a simple mock API using tools like Mockoon, Postman Mock Servers, or even a basic Node.js/Python script that returns static JSON. This gives you more control over the data.
- Option 3: Your Own Backend Service: If you have an existing internal service you wish to protect or manage, that's ideal.
- Key Requirement: The backend API should be accessible from wherever your MuleSoft proxy will be deployed (e.g., if deploying to CloudHub, the backend needs to be publicly accessible or accessible via a VPN/VPC connection). For simplicity, we'll assume a publicly accessible REST API for this guide.
5. Backend API Details We'll Use (Example)
For consistency throughout this guide, let's assume our target backend API is a simple service that provides user details. * Base URL: https://api.example.com/users (replace with an actual URL for your testing) * Endpoint: * GET /users - retrieves a list of users * GET /users/{id} - retrieves a specific user by ID * POST /users - creates a new user
Ensure you have these details handy, as they will be crucial for configuring the HTTP Requestor in your Mule application. With all these prerequisites in place, you are now ready to embark on the practical journey of building your MuleSoft API proxy.
Chapter 4: Core Steps to Create an API Proxy in MuleSoft
This chapter is the heart of our guide, detailing the step-by-step process of constructing an API proxy using MuleSoft. We'll leverage Anypoint Design Center for API definition, Anypoint Studio for the proxy implementation, and Anypoint Platform for deployment and initial registration.
Step 1: Define Your API using RAML/OAS in Anypoint Design Center
The first and often most critical step in building a robust API proxy is to define the API's contract clearly. MuleSoft promotes a "design-first" approach, where you specify the API's behavior before writing any code. This ensures consistency and forms the basis for your proxy.
Why API Specifications are Crucial
An API specification (like RAML or OpenAPI Specification - OAS) acts as a blueprint or a contract between the API provider (your backend service, fronted by the proxy) and the API consumers. It describes: * Endpoints and Resources: What paths are available (e.g., /users, /products/{id}). * HTTP Methods: Which operations are supported on each resource (GET, POST, PUT, DELETE). * Request Parameters: What data clients can send (query parameters, URI parameters, headers, body schemas). * Response Structures: What data clients can expect to receive, including status codes and body schemas. * Security Schemes: How clients authenticate.
Defining this contract first provides several benefits: * Clear Communication: All stakeholders (backend developers, frontend developers, testers, technical writers) have a single source of truth for the API's behavior. * Client Mocking: Frontend teams can start building their applications against a mocked API based on the spec, even before the backend is fully implemented. * Automated Testing and Documentation: Tools can automatically generate test cases and interactive documentation (like Swagger UI) from the specification. * Proxy Generation: For MuleSoft, the specification is used to generate the basic structure of the API proxy application, ensuring it adheres to the defined contract.
Using Design Center to Create a New API Specification
- Log in to Anypoint Platform: Navigate to
anypoint.mulesoft.comand log in with your credentials. - Access Design Center: From the left-hand navigation pane, click on "Design Center".
- Create New API Specification: Click on the "Create New" button, then select "API specification".
- Name and Type:
- Give your API a meaningful title, e.g., "User Management API".
- Choose a preferred language: RAML 1.0 or OpenAPI 3.0 (OAS 3.0 is more widely adopted currently). For this guide, we'll use OAS 3.0 for its broader industry recognition.
- Click "Create API specification".
- Define the API Contract: You'll be presented with a web-based editor. Let's define a simple API for managing users, as discussed in the prerequisites.
yaml openapi: 3.0.0 info: title: User Management API version: 1.0.0 description: A simple API to manage user resources. servers: - url: http://localhost:8081/api # This will be our proxy's base path description: Local development server paths: /users: get: summary: Get all users operationId: getAllUsers responses: '200': description: A list of users. content: application/json: schema: type: array items: $ref: '#/components/schemas/User' post: summary: Create a new user operationId: createUser requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/NewUser' responses: '201': description: User created successfully. content: application/json: schema: $ref: '#/components/schemas/User' '400': description: Invalid input. /users/{id}: get: summary: Get user by ID operationId: getUserById parameters: - name: id in: path required: true schema: type: integer format: int64 description: ID of the user to retrieve. responses: '200': description: User details. content: application/json: schema: $ref: '#/components/schemas/User' '404': description: User not found. put: summary: Update user by ID operationId: updateUser parameters: - name: id in: path required: true schema: type: integer format: int64 description: ID of the user to update. requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/NewUser' # Reusing schema for update payload responses: '200': description: User updated successfully. content: application/json: schema: $ref: '#/components/schemas/User' '400': description: Invalid input. '404': description: User not found. delete: summary: Delete user by ID operationId: deleteUser parameters: - name: id in: path required: true schema: type: integer format: int64 description: ID of the user to delete. responses: '204': description: User deleted successfully. '404': description: User not found. components: schemas: User: type: object properties: id: type: integer format: int64 readOnly: true firstName: type: string lastName: type: string email: type: string format: email required: - id - firstName - lastName - email NewUser: type: object properties: firstName: type: string lastName: type: string email: type: string format: email required: - firstName - lastName - email* Note: TheserversURLhttp://localhost:8081/apispecifies the expected base path for your API. This is important for how the proxy will expose the API. - Save and Publish to Exchange:
- Click "Save" (or Ctrl+S).
- Once saved, click the "Publish" button at the top right.
- Select "Publish to Exchange". This makes your API specification discoverable and available for consumption by other developers and for generating proxy applications.
- Ensure "Asset version" is set (e.g.,
1.0.0). - Click "Publish to Exchange".
You have now successfully defined your API contract and published it. This is the foundation upon which your API proxy will be built.
Step 2: Create the API Proxy Application in Anypoint Studio
Now that your API specification is in Anypoint Exchange, we can use Anypoint Studio to generate a new Mule project that acts as the API proxy. This process kickstarts the proxy creation by configuring much of the necessary routing logic based on your API definition.
- Open Anypoint Studio: Launch Anypoint Studio.
- Create a New Mule Project:
- Go to
File > New > Mule Project. - Give your project a name, e.g.,
user-management-api-proxy. - Crucially, in the "API definition" section, click "Browse Anypoint Exchange".
- Log in to Anypoint Exchange if prompted, using your Anypoint Platform credentials.
- Search for your "User Management API" (the one you just published). Select it and click "Finish".
- Ensure "API Sync" is checked. This keeps your project in sync with any updates to the API definition in Exchange.
- Under "Mule Runtime", select the latest available runtime (e.g., Mule 4.4.0).
- Click "Finish".
- Go to
- Understanding the Generated Flow: Studio will generate a new Mule project containing several files, most importantly
user-management-api-proxy.xml(ormule-app.xmlif you used an older Studio version) in thesrc/main/mulefolder.api.ramlorapi.json/api.yaml: This is a local copy of your API specification.global.xml: Contains global configurations.user-management-api-proxy.xml(Main Flow): Open this file. You'll see a pre-built flow (often nameduser-management-api-main) that handles incoming requests.- HTTP Listener: This component
(http://0.0.0.0:8081/api/*)listens for incoming HTTP requests on a specific port and path.- Path: By default, it will likely be
/api/*. This/*is important as it tells the listener to accept any path segments after/api. - Port: The default port is usually 8081.
- Path: By default, it will likely be
- API Gateway Policy (APIKIT Router): The heart of the generated proxy. This component (
APIKIT Router) reads your API specification (api.yamlin our case) and intelligently routes incoming requests to the correct backend flows based on the defined paths and methods. It also performs basic validation against the API contract. - HTTP Requestor: This is the component you need to configure to point to your actual backend API**. This is currently missing or needs configuration.
- HTTP Listener: This component
- Configuring the HTTP Requestor (Connecting to Backend): The generated project provides a basic
api-mainflow and separateapi-config(orglobal.xml).- Identify the
HTTP_Request_configuration: Inglobal.xml(orapi-config.xml), you'll find a configuration namedHTTP_Request_configuration. This is what the proxy uses to call your backend.- For our example backend
https://api.example.com/users, you would configure:- Host:
api.example.com - Port:
443(for HTTPS) - Protocol:
HTTPS - Base Path:
/users(This is crucial. The proxy will prepend this to the incoming API path segments before calling the backend.)
- Host:
- For our example backend
- Identify the
- Test Locally (Optional but Recommended):
- Right-click on your
user-management-api-proxy.xmlin Package Explorer. - Select
Run project user-management-api-proxy. - Studio will deploy the application to its embedded Mule Runtime.
- Once deployed, you should see "Deployed app
user-management-api-proxy" in the console. - Open your web browser or use a tool like Postman to test:
GET http://localhost:8081/api/usersGET http://localhost:8081/api/users/1POST http://localhost:8081/api/users(with a JSON body like{"firstName": "John", "lastName": "Doe", "email": "john.doe@example.com"})
- You should see responses from your backend API being proxied through your local Mule application. If there are errors, check the Studio console for logs.
- Right-click on your
Update Host and Port: Modify this configuration to point to your backend API's base URL.Here's how to do it: 1. In src/main/mule, open global.xml. 2. Locate the <http:request-config> element (it might be commented out or set to localhost). 3. Update its properties: xml <http:request-config name="HTTP_Request_configuration" doc:name="HTTP Request configuration" doc:id="YOUR_DOC_ID"> <http:request-connection host="api.example.com" port="443" protocol="HTTPS"> <!-- If your backend has a common base path, add it here. For 'https://api.example.com/users', the base path is '/users'. The APIKIT router handles path segments, so usually you only need the base path here. --> <http:uri-params><![CDATA[#{"path": "/techblog/en/users"}]]></http:uri-params> </http:request-connection> </http:request-config> Correction for Base Path: The http:uri-params for base path is usually not set directly on request-connection for proxies. Instead, the APIKIT Router effectively routes /{path} to your backend by dynamically constructing the path. So, host="api.example.com" and port="443" are sufficient. The APIKIT Router then dynamically appends the matched URI parts from the incoming request (e.g., /users, /users/1) to this base.
A more typical `http:request-config` for a proxy would look like this, letting the router handle the path:
```xml
<http:request-config name="HTTP_Request_configuration" doc:name="HTTP Request configuration" doc:id="YOUR_DOC_ID">
<http:request-connection host="api.example.com" port="443" protocol="HTTPS" />
</http:request-config>
```
Then, in your main flow (`user-management-api-proxy.xml`), within the `api-main` flow that processes incoming requests, the `HTTP Request` connector will use this configuration and dynamically construct the request path to the backend. The APIKIT router takes care of mapping the incoming path (`/api/users` or `/api/users/{id}`) to the *correct* path for the backend (`/users` or `/users/{id}`). The generated project's `api-main` flow usually has an `<apikit:router>` followed by an `<http:request>` which already handles this dynamic path construction. The `<http:request>` should be configured to use `HTTP_Request_configuration` and likely will have a `path` attribute set to `#[attributes.relativePath]`.
So, your main flow's `HTTP Request` would look something like:
```xml
<http:request-connector config-ref="HTTP_Request_configuration" method="#[attributes.method]" path="#[attributes.relativePath]" doc:name="Call Backend API" doc:id="YOUR_DOC_ID"/techblog/en/>
```
This `#[attributes.relativePath]` is key; the APIKIT router populates this with the path segments *after* the base path of your proxy (e.g., if proxy listens on `/api/*` and client calls `/api/users`, `relativePath` becomes `/users`).
This completes the creation of the basic pass-through API proxy application in Anypoint Studio.
Step 3: Deploy the Proxy Application
Once your API proxy application is working locally, the next step is to deploy it to a runtime environment where it can be publicly accessible. MuleSoft offers several deployment options, with CloudHub being the most common for cloud-native deployments.
Deployment Options:
- CloudHub: MuleSoft's fully managed, multi-tenant cloud platform. Simplest and most common.
- On-Premise (Mule Runtime): Deploy to your own servers running Mule Runtime. Requires more infrastructure management.
- Hybrid: A combination of CloudHub and on-premise runtimes, managed centrally.
For this guide, we'll focus on deploying to CloudHub.
Deploying to CloudHub from Anypoint Studio
- Prepare for Deployment: Ensure your project is saved and no errors are present in Studio.
- Right-click on Project and Deploy:
- In Anypoint Studio's Package Explorer, right-click on your
user-management-api-proxyproject. - Select
Anypoint Platform > Deploy to CloudHub.
- In Anypoint Studio's Package Explorer, right-click on your
- Configure Deployment Settings: A "Deploy to CloudHub" dialog will appear.
- Account: Ensure you're logged into the correct Anypoint Platform account.
- Target: Select "CloudHub".
- Deployment Target: Choose the appropriate environment (e.g.,
Sandbox,Development,Production). - Application Name: This must be globally unique across CloudHub. Studio usually pre-fills it from your project name. If it shows an error (name already taken), append a unique identifier (e.g.,
user-management-api-proxy-yourname). - Worker Size: Select a worker size (e.g.,
0.1 vCoreis usually sufficient for testing). - Workers: Keep
1worker for testing. For production, you might increase this for high availability and load balancing. - Runtime Version: Select a compatible Mule Runtime version (e.g.,
4.4.0or later). - Object Store V2: Check this box (recommended for persistence and state management across workers).
- Properties: This is where you can define environment-specific properties (e.g.,
backend.host,backend.port) if you want to externalize them. For our simple example, we hardcoded the backend inglobal.xmlfor now, but in real-world scenarios, you would use properties for flexibility. - Click "Deploy Application".
- Monitor Deployment:
- The deployment process will start. You can monitor its progress in the Studio console.
- Alternatively, log in to Anypoint Platform, navigate to "Runtime Manager", and you'll see your application being deployed.
- Deployment can take a few minutes. Wait for the status to change to "Started".
- Verify Deployment and Get Endpoint URL:
- Once your application is "Started" in Runtime Manager, click on its name (
user-management-api-proxy-yourname). - On the application details page, you'll find the "Application URL". This is the public endpoint of your API proxy. It will typically look like
http://user-management-api-proxy-yourname.us-e2.cloudhub.io/api. - Test this URL using Postman or your browser:
GET http://user-management-api-proxy-yourname.us-e2.cloudhub.io/api/users- You should receive responses from your backend API, confirming that your proxy is successfully deployed and routing traffic.
- Once your application is "Started" in Runtime Manager, click on its name (
Congratulations! Your API proxy is now live and accessible in the cloud. However, it's currently a simple pass-through. To unlock the full potential of an API gateway, we need to register and manage it.
Step 4: Register the Proxy in API Manager
Deploying the Mule application makes it accessible, but it's not yet a managed API in the Anypoint Platform ecosystem. To apply runtime policies (like security, rate limiting, caching) and gain centralized governance, you must register your deployed proxy with Anypoint API Manager. This step transforms your deployed Mule application into a fully managed API gateway asset.
Purpose of API Manager
Anypoint API Manager is the control plane for your APIs. It allows you to: * Apply Policies: Enforce security, quality of service, and transformation policies without modifying the underlying Mule application code. * Manage Access: Control who can access your API and under what conditions. * Monitor Usage: Track API calls, performance metrics, and error rates (though detailed analytics are in Anypoint Monitoring). * Version APIs: Manage multiple versions of an API seamlessly. * Lifecycle Management: Define and manage the API's status (e.g., published, deprecated, retired).
Adding a New API Instance (Registering the Proxy)
- Log in to Anypoint Platform: Navigate to
anypoint.mulesoft.com. - Access API Manager: From the left-hand navigation pane, click on "API Manager".
- Add API: Click on the "Add API" button, then select "From Exchange".
- Select API from Exchange:
- Search for your "User Management API" (the API specification you published in Step 1).
- Select it and click "Next".
- Configure API Instance:Important Note on
Public API Base Path: If your original API specification (User Management APIin Exchange) hasserversdefined ashttp://localhost:8081/api, then when you register the API, thePublic API Base Pathin API Manager should also typically be/api. This base path aligns the URL clients use (https://your-cloudhub-app.cloudhub.io/api/...) with how your API is defined.- API Version: Select the version you published (e.g.,
1.0.0). - API instance label: (Optional) Give it a descriptive name, e.g.,
User Management API - Proxy Instance. - Asset Type: Choose
Mule Gateway. This indicates that a Mule application (your proxy) will be acting as the API gateway. - Deployment Type: Select
CloudHub(since we deployed to CloudHub). - Target: Select the runtime instance. This should automatically list your deployed CloudHub application, e.g.,
user-management-api-proxy-yourname. If it's not listed, refresh the page or ensure your application is fully "Started" in Runtime Manager. - Proxy Status: Set to "Active".
- Inbound URL: This will be automatically populated with your CloudHub application's URL. This is the URL clients will use to access your managed API.
- Public API Base Path: This should match the base path you defined in your OAS spec (
/api). The API manager will enforce that all requests to the inbound URL must start with this path. - Apply policies directly to: Keep as
API instances(default). - Click "Save & Deploy".
- API Version: Select the version you published (e.g.,
- Verify Registration:
- After saving, you'll be redirected to the API instance details page.
- The "Status" should eventually show "Active". This means API Manager has successfully detected and is now managing your deployed proxy.
- You'll see a green "Managed" badge next to your API instance, confirming it's under API Manager's control.
Now, your API proxy is not just running; it's being actively managed by the Anypoint API Gateway. This opens the door to applying powerful runtime policies, which is the subject of our next chapter. You have successfully established the foundational structure of your MuleSoft API proxy, preparing it for sophisticated policy enforcement and governance.
APIPark is a high-performance AI gateway that allows you to securely access the most comprehensive LLM APIs globally on the APIPark platform, including OpenAI, Anthropic, Mistral, Llama2, Google Gemini, and more.Try APIPark now! 👇👇👇
Chapter 5: Enhancing Your API Proxy with Policies in API Manager
With your API proxy deployed and registered in Anypoint API Manager, you've established the conduit between your clients and backend. However, its true power lies in the ability to enforce policies. Policies are runtime rules that API Manager applies to incoming requests and outgoing responses without requiring any modifications to your core Mule application code. They are the backbone of your API gateway functionality, providing centralized control over security, quality of service, and various operational aspects.
Introduction to Policies: What They Are and Why They Are Used
Policies in MuleSoft's API Manager are pre-built or custom rules that dictate how your API behaves at runtime. They are applied at the API gateway level, which means they intercept requests before they reach your proxy application and responses before they reach the client. This interception point is ideal for:
- Centralized Governance: Ensure consistent application of rules across all your APIs.
- Separation of Concerns: Keep your core integration logic clean and focused, letting the API gateway handle cross-cutting concerns.
- Agility: Apply, remove, or modify policies dynamically without redeploying the underlying API proxy application.
- Security: Protect your backend systems from unauthorized access and malicious attacks.
- Performance: Optimize API performance through caching and traffic management.
- Compliance: Meet regulatory requirements by logging requests, restricting access, or transforming data.
API Manager offers a wide array of out-of-the-box policies, categorized for different purposes. You can also develop custom policies if your requirements are not met by the standard offerings.
Common Policy Categories
Let's explore some of the most frequently used policy categories and how they enhance your API proxy.
1. Security Policies
These policies are critical for protecting your APIs from unauthorized access and ensuring data integrity. They represent the first line of defense at your API gateway.
- Client ID Enforcement:
- Purpose: Ensures that only authorized client applications can access your API. Each client application is assigned a unique
Client IDandClient Secret. These credentials are sent with each request, and the policy validates them against the registered applications in Anypoint Platform. - How it works: When a request comes in, the policy extracts the
Client ID(usually from a header or query parameter) and validates it. If valid, the request proceeds; otherwise, it's rejected with anHTTP 401 Unauthorizedor403 Forbiddenstatus. - Setup:
- In API Manager, navigate to your API instance.
- Click on "Policies" tab.
- Click "Apply New Policy".
- Select "Client ID Enforcement" and click "Configure Policy".
- Configure the "Client ID Expression" and "Client Secret Expression". By default, these are often
#[attributes.headers['client_id']]and#[attributes.headers['client_secret']]respectively, meaning the policy expects these in the HTTP headers. You can change them to query parameters if needed. - Click "Apply".
- Testing: After applying, you'll need to create a "Client Application" in Anypoint Platform (Exchange > Applications > Create Application). Once created, you'll get a Client ID and Client Secret. Use these in your request headers (
client_id,client_secret) when calling your proxy. Without them, your requests will be denied.
- Purpose: Ensures that only authorized client applications can access your API. Each client application is assigned a unique
- Basic Authentication:
- Purpose: Enforces basic HTTP authentication (
username:passwordencoded in Base64) to restrict access to the API. - Setup: Configure accepted usernames and passwords.
- Use Case: Simple authentication for internal APIs or testing environments.
- Purpose: Enforces basic HTTP authentication (
- OAuth 2.0 Access Token Enforcement:
- Purpose: Integrates with an OAuth 2.0 provider to validate access tokens. This is the industry-standard for securing REST APIs.
- How it works: The policy extracts the bearer token from the
Authorizationheader, sends it to an OAuth 2.0 provider (e.g., Okta, Auth0, or MuleSoft's Access Management) for introspection (validation), and allows the request only if the token is valid and active. - Setup: Requires configuring the OAuth provider's introspection endpoint and client credentials.
- Use Case: Securing public or third-party APIs with robust, delegated authorization.
- JWT Validation:
- Purpose: Validates JSON Web Tokens (JWTs) presented in requests. JWTs are a compact, URL-safe means of representing claims to be transferred between two parties.
- How it works: The policy verifies the JWT's signature (using a public key or secret), checks for expiration, and ensures required claims are present, without needing to call an external introspection endpoint like OAuth.
- Setup: Configure the expected JWT issuer, audience, and the JWKS (JSON Web Key Set) URL or public key to verify signatures.
- Use Case: Securing microservices architectures, where identity information can be securely passed between services.
- IP Whitelisting/Blacklisting:
- Purpose: Controls access based on the source IP address of the client.
- How it works: Allows or denies requests based on a configured list of IP addresses or IP ranges.
- Setup: Provide a comma-separated list of allowed or blocked IP addresses/CIDR ranges.
- Use Case: Restricting API access to specific corporate networks or trusted partners, or blocking known malicious IPs.
2. Quality of Service (QoS) Policies
QoS policies are designed to manage API traffic, optimize performance, and ensure fair resource allocation.
- Rate Limiting:
- Purpose: Limits the number of requests a client can make to an API within a defined time window. Prevents abuse and ensures service stability.
- How it works: Each incoming request consumes a "token." If no tokens are available for the client within the window, the request is rejected (typically with
HTTP 429 Too Many Requests). Tokens are replenished after the window expires. - Setup:
- In API Manager, "Apply New Policy".
- Select "Rate Limiting" and "Configure Policy".
- Specify the "Maximum requests" (e.g., 100).
- Specify the "Time period" (e.g., 60000 milliseconds for 1 minute).
- (Optional but Recommended) "Group by": Use
#[attributes.headers['client_id']]or#[attributes.remoteAddress]to apply limits per client or per IP address, rather than for the entire API globally. This is crucial for fair usage. - Click "Apply".
- Testing: Make numerous rapid requests to your API. You should observe requests failing with a 429 status code once the limit is exceeded.
- Spike Arrest:
- Purpose: Protects backend services from sudden, massive bursts of traffic (spikes) by smoothing out the request rate. Unlike rate limiting, which hard-stops after a count, spike arrest attempts to evenly distribute requests over a short period.
- How it works: Similar to rate limiting but focuses on preventing a sudden deluge. If a spike is detected, excess requests are typically throttled or dropped temporarily.
- Setup: Configure the "Allow Requests" per time period.
- Use Case: Preventing backend overloads during unexpected traffic surges (e.g., flash sales, viral content).
- Caching:
- Purpose: Improves API response times and reduces backend load by storing responses to frequent requests at the API gateway.
- How it works: When a GET request arrives, the policy first checks if a valid response exists in its cache. If yes, it serves from cache; otherwise, it forwards to the backend, stores the backend's response, and then returns it. Subsequent identical requests within the cache expiry period are served directly from the cache.
- Setup:
- "Apply New Policy" > "Caching".
- Configure "Cache Key Expression" (e.g.,
#[attributes.uriParams.'id']for/users/{id}). This defines what uniquely identifies a cached item. - Set "Time To Live" (e.g., 300 seconds for 5 minutes).
- (Optional) "Scope":
API(default, shared across all API instances) orAPI Instance(per deployed proxy). - Click "Apply".
- Testing: Make a request, observe the response time. Make the exact same request shortly after. The response should be significantly faster (served from cache), and your backend logs should show fewer hits.
3. Transformation Policies
These policies modify the structure or content of requests and responses.
- Header Injection/Removal/Transformation:
- Purpose: Add, remove, or modify HTTP headers in requests or responses.
- Use Case: Adding a
X-Proxy-IDheader to backend requests for traceability, removing sensitive headers from responses, or injecting CORS headers for client-side applications.
- Message Transformation:
- Purpose: Transform the body of requests or responses (e.g., JSON to XML, or changing payload structure).
- Use Case: Adapting an existing API to a new consumer's expected format, or masking sensitive data in the response body before sending it back to the client.
4. Traffic Management Policies
- Message Filtering:
- Purpose: Allows or denies requests based on specific content within the request header, query parameters, or payload.
- How it works: You define rules (e.g., "if header
X-Special-Valueistrue, allow; else deny"). - Use Case: Implementing custom routing or access control logic based on request content.
Applying and Managing Policies: Step-by-Step Example for Rate Limiting
Let's walk through applying the Rate Limiting policy in detail, as it's a very common requirement.
- Navigate to API Manager: Log in to Anypoint Platform and go to "API Manager".
- Select Your API Instance: Find your "User Management API - Proxy Instance" and click on it.
- Go to Policies Tab: Click on the "Policies" tab.
- Apply New Policy: Click the "Apply New Policy" button.
- Choose Rate Limiting: From the list of available policies, select "Rate Limiting" and click "Configure Policy".
- Configure Policy Details:
- Maximum requests: Enter
5(for testing, a small number is good). - Time period: Enter
60000milliseconds (which is 1 minute). - Group by: This is crucial. If you want to limit requests per client, you should group by an identifier that uniquely identifies the client. A common practice is to use the
client_idheader if you're also using Client ID Enforcement. For simplicity in initial testing, you could use#[attributes.remoteAddress]to group by the client's IP address. Let's use#[attributes.remoteAddress]for this example. - Warning: Do not group by
#[true]unless you want a global limit for the entire API for all clients combined, which is usually not desired. - Action for requests that exceed the limit: Keep "Reject requests".
- Response Code for rejected requests:
429(Too Many Requests) is the standard. - Response Message for rejected requests: (Optional) Add a custom message, e.g., "You have exceeded your API usage limit. Please try again later."
- Click "Apply".
- Maximum requests: Enter
- Policy Status: The policy will now be listed under your API instance. It should show a "Status" of "Active". This indicates that the policy has been successfully deployed to your API gateway.
Testing the Rate Limiting Policy
- Obtain your API Proxy URL: From Runtime Manager or API Manager, get the "Inbound URL" of your deployed proxy (e.g.,
http://user-management-api-proxy-yourname.us-e2.cloudhub.io/api). - Make Requests: Use a tool like Postman, curl, or a simple script to make more than 5
GETrequests toYOUR_PROXY_URL/userswithin a 1-minute window from the same IP address.- The first 5 requests should succeed (HTTP 200 OK).
- The 6th request (and subsequent requests within that minute) should fail with
HTTP 429 Too Many Requestsand your custom message.
- Wait and Retest: After 1 minute, the counter will reset, and your requests should start succeeding again.
This practical exercise demonstrates the immediate and powerful impact of applying policies via Anypoint API Manager. It highlights how the API gateway acts as an intelligent enforcement point, adding critical functionality without touching the underlying service code.
The Role of the API Gateway in Enforcing Policies
The API gateway (Anypoint API Manager in this context) is the central nervous system for policy enforcement. When an API is registered and policies are applied, the gateway intercepts every single request and response. For each transaction, it evaluates the applied policies in a defined order. This order can be crucial, for example, typically security policies (like Client ID Enforcement) are applied before QoS policies (like Rate Limiting), to prevent unauthorized users from even consuming rate limit tokens. This centralized, dynamic policy engine is what transforms a simple API proxy into a powerful, governed, and resilient API gateway. It ensures that your APIs are consistently secure, performant, and compliant across your entire organization, irrespective of the underlying backend implementations.
Chapter 6: Advanced Proxy Configurations and Best Practices in MuleSoft
While a basic pass-through proxy with fundamental policies is a great start, the true power of MuleSoft lies in its ability to handle complex scenarios. This chapter delves into advanced configurations and best practices that elevate your API proxies from simple intermediaries to intelligent, robust, and resilient components of your enterprise architecture. These techniques often involve deeper configuration within Anypoint Studio and strategic thinking around your API design.
1. Request and Response Transformations: The DataWeave Advantage
One of the most common and powerful use cases for an API proxy is to transform messages between client and backend. This capability allows you to decouple clients from backend specifics, modernize legacy APIs, or consolidate multiple services. MuleSoft's DataWeave is an incredibly powerful, functional, and declarative language specifically designed for data transformation, making it ideal for this task.
Why Transform?
- Backend Abstraction: Shield clients from backend-specific data formats or structures.
- API Modernization: Expose legacy (e.g., SOAP XML) services as modern RESTful JSON APIs.
- Data Masking: Remove or obfuscate sensitive fields from responses before sending to clients.
- Data Aggregation/Composition: Combine data from multiple backend services into a single, unified response.
- Input Normalization: Standardize incoming client requests to match backend expectations.
Using DataWeave for Transformations
DataWeave transformers are typically implemented using the Transform Message component in Anypoint Studio.
Example: Masking Sensitive Data in a Response Let's say your backend /users API returns a full user object, including a ssn (Social Security Number) or password field that you don't want to expose to all clients.
- Identify the Target Flow: In your
user-management-api-proxy.xml, locate the flow that handles theGET /usersresponse. This would typically be after theHTTP Requestconnector that calls the backend. - Add
Transform Message: Drag and drop a "Transform Message" component from the Mule Palette into the response processing part of your flow (i.e., after theHTTP Requestthat calls the backend, but before the finalresponsecomponent).- In the
Transform Messagecomponent, you'll see input and output panes. - In the output pane (which defines the payload sent back to the client), write a DataWeave script to transform the
payloadreceived from the backend.
- In the
Write DataWeave Expression:```dw %dw 2.0 output application/json
payload map ((user) -> { id: user.id, firstName: user.firstName, lastName: user.lastName, email: user.email, // Mask or omit sensitive fields // ssn: "MASKED" // Example: Masking // Alternatively, omit entirely: // if (user.address) address: user.address }) `` This example iterates over a list of users (payload map) and constructs a new object for each, explicitly excludingssnorpasswordif they were present in the originalpayload`.
Example: Transforming Request Body (XML to JSON) If a client sends XML but your backend expects JSON, DataWeave can perform the conversion. 1. Identify the Target Flow: For POST or PUT requests, after the HTTP Listener but before the HTTP Request to the backend. 2. Add Transform Message: Place it in the request processing part of the flow. 3. Write DataWeave: dw %dw 2.0 output application/json // Output JSON for the backend input application/xml // Assume input is XML --- { firstName: payload.User.FirstName, lastName: payload.User.LastName, email: payload.User.Email } This script converts an incoming XML structure <User><FirstName>...</FirstName>...</User> to a JSON object.
DataWeave's powerful capabilities extend to complex conditional logic, data aggregation, and integration with external functions, making it an indispensable tool for advanced proxy configurations.
2. Error Handling and Fault Tolerance
Robust API proxies must gracefully handle errors, whether they originate from the backend, the network, or within the proxy itself. Poor error handling can lead to poor user experience, security vulnerabilities, and system instability. MuleSoft provides comprehensive error handling mechanisms.
- Try Scope: Encapsulates a sequence of components where errors might occur. If an error happens within a
Tryscope, it can be caught by associatedOn Errorscopes. - On Error Propagate: When an error is caught by
On Error Propagate, it executes its internal flow and then re-throws the error to the calling flow. This is useful for propagating errors up the chain. - On Error Continue: When an error is caught by
On Error Continue, it executes its internal flow, and then the original flow continues as if no error occurred (the error is consumed). This is useful for logging errors without stopping the main flow or for providing a fallback mechanism. - Global Error Handler: Defines default error handling logic for the entire application, catching errors not specifically handled by local
On Errorscopes.
Example: Custom Error Responses Instead of just propagating a generic 500 Internal Server Error from the backend, you might want to return a standardized, client-friendly error message.
- Add
TryScope: Wrap yourHTTP Requestto the backend within aTryscope. - Add
On Error Propagate: Inside theTryscope, add anOn Error Propagatecomponent. - Configure Error Type: In the
On Error Propagate, set the "Error Type" toHTTP:BAD_REQUESTorHTTP:CONNECTIVITYorANYto catch relevant backend errors.- Use a
Set PayloadorTransform Messagecomponent to create a custom error response. ```dw %dw 2.0 output application/json
- Use a
- Circuit Breaker Pattern: For more advanced fault tolerance, consider implementing the Circuit Breaker pattern. This prevents an API proxy from repeatedly attempting to invoke a failing backend service. While MuleSoft doesn't have a direct "Circuit Breaker" component out-of-the-box, it can be implemented using combinations of Object Store, custom logic, and error handling. Third-party modules or custom components can also provide this functionality.
Transform Error Message: Inside the On Error Propagate flow:
{ "code": error.errorCode, "message": "An unexpected error occurred while processing your request. Please try again later.", "details": "Internal service error, contact support with correlation ID: " ++ correlationId } `` * Use aSet Eventcomponent to set the HTTP status code (e.g.,#[500]`). * This ensures clients receive consistent, structured error messages instead of raw backend errors.
3. Load Balancing and High Availability
For production-grade API proxies, ensuring high availability and handling large traffic volumes are paramount.
- Multiple CloudHub Workers: When deploying to CloudHub, you can provision multiple "workers" (instances) of your Mule application. CloudHub automatically load balances traffic across these workers, providing both scalability and high availability. If one worker fails, others can continue processing requests.
- External Load Balancers: For on-premise deployments or more complex hybrid setups, you can deploy your Mule applications behind external load balancers (e.g., Nginx, F5, AWS ELB). These external balancers distribute traffic and perform health checks on your Mule Runtime instances.
- Object Store V2 for State Management: If your proxy needs to maintain any state across multiple worker instances (e.g., custom rate limits not handled by API Manager, complex caching logic, temporary session data), use Object Store V2. This is a distributed, persistent key-value store accessible by all workers, ensuring consistency.
4. Versioning APIs
Managing different versions of an API is crucial for evolving your services without breaking existing client applications. An API proxy is an excellent tool for versioning.
- URL-based Versioning: (e.g.,
/v1/users,/v2/users).- Implementation: Define different base paths in your API specification (e.g.,
/v1,/v2). Each version can be handled by a separate proxy application or by conditional routing within a single proxy using DataWeave orChoicerouters based onattributes.relativePath.
- Implementation: Define different base paths in your API specification (e.g.,
- Header-based Versioning: (e.g.,
Accept: application/vnd.myapi.v1+json).- Implementation: The proxy inspects a custom header (e.g.,
X-API-Version) or theAcceptheader. AChoicerouter in your Mule flow can then route the request to the appropriate backend service or apply version-specific transformations using DataWeave.
- Implementation: The proxy inspects a custom header (e.g.,
By placing versioning logic within the proxy, you shield clients from the complexities of backend service versioning and provide a consistent public interface.
5. Monitoring and Analytics
Understanding how your APIs are being used and how they are performing is critical. MuleSoft provides robust tools for this.
- Anypoint Monitoring:
- Provides real-time dashboards for API performance (response times, throughput, error rates).
- Allows creation of custom dashboards and alerts for specific metrics.
- Essential for proactive issue detection and performance optimization.
- Custom Logging Strategies:
- Enhance your Mule application with custom
Loggercomponents to log specific events, payloads, or correlation IDs. - Use a structured logging format (e.g., JSON) to facilitate analysis with external log management tools (Splunk, ELK stack).
- Ensure logs contain sufficient detail for debugging without exposing sensitive information.
- Enhance your Mule application with custom
6. DevOps and CI/CD for API Proxies
For enterprise environments, automating the build, test, and deployment of API proxies is essential.
- Maven Integration: Mule projects are Maven-based. You can use Maven commands (
mvn clean package) to build deployable artifacts (.jarfiles). - Anypoint Platform CLI/APIs: MuleSoft provides command-line interface tools and REST APIs to interact with the Anypoint Platform programmatically. This allows you to automate tasks like deploying applications, creating API instances, and applying policies.
- Integrating with CI/CD Tools:
- Continuous Integration (CI): Integrate your Mule project with CI tools like Jenkins, GitLab CI, GitHub Actions, or Azure DevOps. On every code commit, the CI pipeline can automatically build the project, run unit tests, and potentially run integration tests against a test backend.
- Continuous Deployment (CD): Once CI passes, the CD pipeline can use Maven (
deploygoal) or Anypoint Platform APIs to automatically deploy the.jarartifact to CloudHub or other environments. This ensures consistent and rapid deployments.
- Configuration Management: Externalize environment-specific configurations (backend URLs, credentials, policy parameters) using properties files or secure properties, and manage them through your CI/CD pipeline. Never hardcode sensitive information.
By adopting these advanced configurations and best practices, your MuleSoft API proxy becomes more than just a simple pass-through. It evolves into an intelligent, resilient, and manageable component, capable of handling the demands of complex enterprise integrations and the ever-growing API economy. This strategic use of the API gateway ensures your services are secure, performant, and future-proof.
Chapter 7: Practical Use Cases and Scenarios for MuleSoft API Proxies
The theoretical understanding of API proxies translates into tangible value when applied to real-world challenges. MuleSoft's Anypoint Platform, acting as a robust API gateway, empowers organizations to address a myriad of integration and governance needs through its proxy capabilities. Here, we explore several compelling practical use cases.
1. Securing and Modernizing Legacy Systems
One of the most common and impactful applications of an API proxy is to bring legacy systems into the modern API economy. Many enterprises operate critical backend systems (e.g., mainframes, older databases, SOAP web services) that are highly stable but lack modern API interfaces, robust security, or RESTful communication patterns.
- Scenario: A large financial institution has a legacy SOAP-based service that handles customer account details. Modern mobile and web applications need to access this data via a RESTful JSON API. Directly exposing the SOAP service is undesirable due to its complexity, security limitations, and performance characteristics.
- MuleSoft Proxy Solution:
- An API proxy is deployed to front the SOAP service.
- The proxy consumes the SOAP request (perhaps generated by a MuleSoft SOAP connector or a simple HTTP request with an XML payload).
- DataWeave transformations within the proxy convert the incoming RESTful JSON request payload into the SOAP XML format expected by the backend, and then transform the SOAP XML response back into a RESTful JSON format for the client.
- API Manager policies are applied to the proxy to:
- Enforce modern security (e.g., OAuth 2.0 or JWT validation) instead of relying on outdated or proprietary SOAP security mechanisms.
- Implement rate limiting to protect the often resource-constrained legacy system from being overwhelmed.
- Cache frequently requested data to reduce calls to the slow backend.
- Benefits: Modern applications can seamlessly consume data from the legacy system using familiar REST principles, without needing to understand SOAP intricacies. The legacy system remains untouched, while the proxy provides a secure, performant, and modern API facade. This significantly extends the lifespan and utility of valuable legacy assets.
2. Microservices Orchestration and Aggregation
In microservices architectures, an application's functionality is broken down into many small, independent services. While beneficial for agility, clients often need to aggregate data from multiple microservices to display a complete view. An API proxy can act as an aggregation layer.
- Scenario: An e-commerce application needs to display a product page that includes product details (from a Product Service), customer reviews (from a Review Service), and inventory levels (from an Inventory Service). Making three separate calls from the client leads to increased latency and client-side complexity.
- MuleSoft Proxy Solution:
- A single API proxy (
/product/{id}) is exposed to the client. - Within the Mule flow of this proxy:
- It makes parallel or sequential calls to the Product Service, Review Service, and Inventory Service (using multiple
HTTP Requestconnectors). - DataWeave is used to combine the responses from these three microservices into a single, cohesive JSON response structure that is optimized for the client application.
- Policies like client ID enforcement secure access to this aggregated API.
- It makes parallel or sequential calls to the Product Service, Review Service, and Inventory Service (using multiple
- This is often referred to as a "Backend for Frontend" (BFF) pattern, where the proxy is specifically tailored to the needs of a particular client application.
- A single API proxy (
- Benefits: Reduces the number of network round-trips for the client, simplifies client-side development, and abstracts the underlying microservice architecture from the client, making future changes to microservices less impactful on frontend applications. The API gateway effectively becomes an orchestration layer.
3. Third-Party API Integration and Governance
Organizations frequently consume third-party APIs (e.g., payment gateways, shipping services, weather data APIs). While these APIs are external, you still need to govern their usage, add resilience, and potentially transform their data for internal consumption.
- Scenario: A logistics company integrates with various shipping carrier APIs, each with different authentication mechanisms, rate limits, and response formats. The internal order management system needs a unified way to interact with these carriers.
- MuleSoft Proxy Solution:
- An API proxy is created for each third-party API.
- For each proxy:
- API Manager policies are applied to enforce internal rate limits (even if the third-party API has its own, you might want to cap usage), log all requests for auditing, and transform authentication credentials.
- DataWeave is used to normalize the varied third-party API responses into a consistent internal format, simplifying integration for downstream systems.
- Error handling within the proxy can provide fallback mechanisms or standardized error messages in case a third-party API experiences downtime.
- Benefits: Centralizes external API management, enhances security by controlling access to third-party API keys, normalizes data for easier internal consumption, provides a single point for monitoring external API usage and performance, and adds a layer of resilience to external service dependencies.
4. API Monetization and Tiered Access
For businesses looking to offer their APIs as a product, API proxies with granular policy control are indispensable for implementing monetization strategies and tiered access.
- Scenario: A data provider offers access to its analytics API with different subscription tiers: a free tier with low rate limits, a premium tier with higher limits, and an enterprise tier with virtually unlimited access.
- MuleSoft Proxy Solution:
- The core analytics backend service is fronted by an API proxy.
- API Manager is configured with Client ID Enforcement.
- Rate Limiting policies are applied, but instead of grouping by IP, they are grouped by the Client ID of the subscriber.
- Different "Client Applications" (representing different subscription tiers) are created in Anypoint Platform, each with its own
Client ID. When developers subscribe to an API, they receive theClient IDcorresponding to their tier. - The rate limit policy is dynamically applied based on the authenticated Client ID. For example, Client IDs from the free tier get a limit of 100 requests/minute, while premium clients get 1000 requests/minute.
- This setup can be further extended with custom policies to track usage for billing purposes.
- Benefits: Enables flexible pricing models, enforces fair usage policies, ensures different customer segments receive the appropriate service level, and provides the foundation for accurate usage-based billing.
5. Hybrid Deployments and Network Bridging
Many enterprises operate in hybrid environments, with some services in the cloud and others on-premises. API proxies can effectively bridge these environments.
- Scenario: An organization has sensitive customer data in an on-premise database accessible only within their corporate network. A new cloud-native application needs to securely retrieve and update this data.
- MuleSoft Proxy Solution:
- A MuleSoft API proxy application is deployed to CloudHub, but it is configured to securely connect to the on-premise network via a CloudHub VPN or VPC (Virtual Private Cloud) connection.
- The CloudHub proxy exposes a public, secure endpoint to the cloud-native application.
- The proxy then securely forwards requests over the VPN/VPC to the on-premise backend service.
- API Manager policies (e.g., OAuth 2.0, IP Whitelisting from cloud-native app IPs) are applied to the CloudHub proxy to provide robust security at the perimeter.
- Benefits: Enables secure and controlled access to on-premise resources from cloud applications, without exposing the internal network directly to the internet. This facilitates hybrid cloud strategies and secure data exchange across distributed environments.
These practical examples illustrate the versatility and strategic importance of MuleSoft API proxies in building agile, secure, and scalable enterprise architectures. By leveraging the comprehensive capabilities of the Anypoint Platform, organizations can address complex integration challenges, drive innovation, and unlock the full potential of their digital assets.
Chapter 8: MuleSoft Proxy Alternatives and Complementary Tools
While MuleSoft offers a robust and comprehensive solution for API proxy creation and management as part of its API gateway capabilities, the landscape of API management is diverse. Depending on specific organizational needs, scale, technical stack, and existing infrastructure, other solutions might be considered alternatives or even complementary tools. Understanding this broader ecosystem is crucial for making informed architectural decisions.
Other Prominent API Gateway Solutions
MuleSoft's Anypoint Platform is a leader in the integration and API gateway space, particularly strong for complex enterprise integrations and the API-led connectivity approach. However, several other powerful API gateway solutions cater to different niches and requirements:
- Kong Gateway: An open-source, cloud-native API gateway that's known for its extensibility (plugins) and performance. It can be deployed anywhere and offers both open-source and enterprise versions. Kong is particularly popular in microservices architectures and for developers who prefer a lightweight, highly configurable gateway.
- Apigee API Management (Google Cloud): A full-lifecycle API management platform offering robust features for design, security, analytics, and developer portals. Apigee is typically favored by large enterprises for its comprehensive feature set, scalability, and deep analytics capabilities.
- AWS API Gateway: A fully managed service provided by Amazon Web Services that allows developers to create, publish, maintain, monitor, and secure APIs at any scale. It integrates seamlessly with other AWS services and is a strong choice for organizations heavily invested in the AWS ecosystem.
- Azure API Management: Microsoft's counterpart to AWS API Gateway, offering similar capabilities for managing and securing APIs within the Azure cloud. It integrates well with other Azure services and is preferred by organizations with a Microsoft-centric infrastructure.
- Tyk Open Source API Gateway: Another open-source API gateway and management platform known for its ease of use, performance, and extensive feature set, including an integrated developer portal and analytics.
Each of these solutions has its strengths and weaknesses, often related to their deployment model, extensibility, feature set, and target user base. MuleSoft typically shines when deep enterprise integration and complex data orchestration are paramount, while others might offer more lightweight, developer-centric, or cloud-native specialized approaches.
Introducing APIPark: An Open Source AI Gateway & API Management Platform
In the evolving landscape of API management, where Artificial Intelligence (AI) is increasingly becoming a critical component of applications, specialized API gateway solutions are emerging. This is where APIPark carves out a unique and significant niche.
APIPark is an all-in-one AI gateway and API developer portal that stands out primarily for its open-source nature (Apache 2.0 license) and its focused approach on AI integration. While MuleSoft provides powerful general-purpose API proxy capabilities, APIPark specifically targets the challenges of managing, integrating, and deploying both AI and traditional REST services with ease, making it a valuable tool, especially for organizations building AI-powered applications.
Key Features of APIPark that Complement or Offer an Alternative Perspective:
- Quick Integration of 100+ AI Models: One of APIPark's standout features is its ability to quickly integrate a vast array of AI models, providing a unified management system for authentication and cost tracking across these models. This is a crucial differentiator if your primary concern is managing and deploying AI-centric APIs.
- Unified API Format for AI Invocation: APIPark addresses a common challenge in AI integration by standardizing the request data format across different AI models. This means changes in underlying AI models or prompts don't necessitate changes in your application or microservices, simplifying AI usage and significantly reducing maintenance costs – a benefit that traditional API gateways might not natively offer for the specific intricacies of AI models.
- Prompt Encapsulation into REST API: This powerful feature allows users to combine AI models with custom prompts to create new, specialized REST APIs on the fly. For instance, you could quickly create an API for sentiment analysis, language translation, or custom data analysis by leveraging existing AI models and specific prompts. This extends the notion of an API proxy to dynamically generate AI-driven APIs.
- End-to-End API Lifecycle Management: Like MuleSoft and other full-fledged API gateway solutions, APIPark also assists with managing the entire lifecycle of APIs, from design and publication to invocation and decommissioning. It helps regulate API management processes, manage traffic forwarding, load balancing, and versioning, demonstrating its comprehensive API management platform capabilities.
- API Service Sharing within Teams & Independent Tenant Management: APIPark promotes collaboration and multi-tenancy by allowing centralized display of API services for teams and enabling independent API and access permissions for each tenant. This is crucial for larger organizations and service providers.
- Performance Rivaling Nginx & Detailed API Call Logging: APIPark boasts impressive performance, claiming over 20,000 TPS with modest hardware, supporting cluster deployment for large-scale traffic. Coupled with comprehensive logging capabilities that record every detail of API calls, it provides the operational stability and observability expected from a high-quality API gateway.
- Open Source & Commercial Support: As an open-source product, APIPark provides a transparent and community-driven solution for basic API resource needs. For enterprises requiring advanced features and professional technical support, a commercial version is available.
Where APIPark Fits In
While MuleSoft excels at complex system integrations and providing a holistic enterprise API gateway solution for diverse types of services (REST, SOAP, databases, queues, ERPs), APIPark offers a compelling alternative or a specialized complementary tool, particularly when:
- AI Integration is a primary concern: If your organization heavily relies on integrating and managing a multitude of AI models, APIPark's specific features for AI model integration, unified invocation formats, and prompt encapsulation offer significant advantages.
- Open-source preference: For teams prioritizing open-source solutions for their API gateway infrastructure, APIPark provides a robust, Apache 2.0 licensed option.
- Developer experience for AI services: APIPark's focus on simplifying AI usage and maintenance costs, coupled with its developer portal, can provide a streamlined experience for developers working with AI APIs.
In a scenario where an organization uses MuleSoft for its core enterprise integrations and traditional REST API management, they might consider using APIPark in conjunction for its specialized AI gateway capabilities. For instance, MuleSoft could expose high-level business APIs, which in turn call AI-powered services managed and exposed by APIPark. This demonstrates how different API gateway solutions can co-exist and complement each other, each playing to its strengths within a complex enterprise architecture. Ultimately, the choice depends on balancing generic integration needs with specific domain requirements, such as the rapidly growing demand for efficient AI API governance.
Conclusion: Mastering MuleSoft API Proxies for the Digital Age
The journey through creating and managing API proxies in MuleSoft has revealed a critical component for building robust, secure, and scalable digital ecosystems. In an era where organizations rely on a dynamic web of interconnected services, the ability to effectively govern these interactions is no longer a luxury but a fundamental necessity. MuleSoft's Anypoint Platform, with its comprehensive suite of tools, provides an unparalleled environment for achieving this mastery.
We embarked on this exploration by understanding the foundational concept of an API proxy – an intelligent intermediary that shields backend services while adding immense value. From bolstering security through centralized authentication and threat protection to optimizing performance with caching and rate limiting, and streamlining management via unified policy enforcement, the "why" behind API proxies became abundantly clear. They act as the strategic chokepepoint, transforming raw backend capabilities into managed, resilient, and consumable API assets.
Our step-by-step guide walked you through the practicalities, starting with the crucial design-first approach in Anypoint Design Center, where an API contract is meticulously defined using OpenAPI Specification. We then transitioned to Anypoint Studio, the development hub, to craft the Mule application that serves as the proxy, connecting to your backend API. Deployment to CloudHub and, critically, registration with Anypoint API Manager were the subsequent milestones, transforming a simple deployed application into a fully managed API gateway asset.
The true power of the Anypoint API gateway was then unleashed through the application of policies. We delved into various categories, from stringent security policies like Client ID Enforcement and OAuth 2.0 validation, to performance-enhancing QoS policies like Rate Limiting and Caching. These policies, applied dynamically and centrally through API Manager, showcased how granular control can be exerted over API behavior without altering the underlying code. Furthermore, advanced configurations in MuleSoft Studio, such as sophisticated DataWeave transformations, robust error handling, high availability strategies, and thoughtful API versioning, demonstrated how to build truly enterprise-grade proxies.
We also explored compelling real-world use cases, illustrating how MuleSoft API proxies can modernize legacy systems, orchestrate complex microservices, govern third-party API consumption, enable API monetization, and facilitate secure hybrid cloud deployments. Each scenario underscored the versatility and strategic advantage of leveraging a powerful API gateway solution like MuleSoft.
Finally, we broadened our perspective to acknowledge the diverse API gateway landscape, recognizing alternatives and complementary tools like APIPark. APIPark, with its specialized focus as an Open Source AI Gateway & API Management Platform, highlights the evolving needs in the API economy, particularly in managing AI-driven services. Its capabilities for unified AI model integration and prompt encapsulation demonstrate how specialized gateways can address unique domain challenges, potentially working alongside general-purpose solutions like MuleSoft to create a truly comprehensive digital fabric.
Mastering API proxy creation in MuleSoft equips you with an invaluable skill set for architecting secure, high-performing, and manageable API solutions. It empowers your organization to embrace the full potential of its digital assets, accelerate innovation, and confidently navigate the complexities of the modern digital landscape. Start building your MuleSoft API proxies today, and unlock the future of enterprise connectivity.
Frequently Asked Questions (FAQ)
1. What is the fundamental difference between an API proxy and an API gateway in MuleSoft? In MuleSoft, an API proxy is essentially a specific Mule application designed to front a backend service, forwarding requests and responses. It's the "runtime" component. An API gateway, specifically MuleSoft's Anypoint API Manager, is the "control plane" that manages these deployed proxies. It allows you to register your proxy, apply runtime policies (like security, rate limiting, caching) to it without code changes, monitor its behavior, and govern its lifecycle. So, while a proxy is the mechanism, the API gateway provides the overarching management and policy enforcement capabilities.
2. Why should I use an API proxy instead of directly exposing my backend services? Using an API proxy (as part of an API gateway) offers significant advantages: * Security: Centralized authentication, authorization, and threat protection, shielding backend services. * Performance: Caching, rate limiting, and traffic management improve response times and prevent backend overload. * Management: Centralized policy enforcement, monitoring, versioning, and abstraction from backend changes. * Flexibility: Enables data transformation, protocol mediation, and allows backend services to be refactored or replaced without affecting client applications.
3. Can I apply custom policies to my MuleSoft API proxy, or am I limited to out-of-the-box policies? No, you are not limited to out-of-the-box policies. MuleSoft's Anypoint Platform allows you to develop and deploy custom policies using Mule SDK. This is particularly useful when your governance requirements are unique and cannot be met by the standard policy offerings. Custom policies can perform specific logic, integrate with external systems for validation, or implement specialized business rules at the API gateway level.
4. How does MuleSoft handle API versioning with proxies? MuleSoft API proxies are highly effective for API versioning. You can implement versioning in several ways: * URL-based: Define different base paths (e.g., /v1/users, /v2/users) within your API specification. You can then route requests to different backend services or apply version-specific transformations based on the incoming URL path. * Header-based: Use a custom HTTP header (e.g., X-API-Version: 2) to indicate the desired API version. The proxy can read this header and route requests accordingly using conditional logic within its Mule flow. By externalizing versioning logic in the proxy, you ensure that client applications interact with a stable public interface, while your backend services can evolve independently.
5. How does APIPark complement MuleSoft's API proxy capabilities, especially for AI-driven services? MuleSoft provides a powerful and generic API gateway solution for all types of integrations. APIPark, on the other hand, specializes as an Open Source AI Gateway & API Management Platform. It complements MuleSoft by offering: * AI-specific Integration: Rapid integration of 100+ AI models with unified management, which MuleSoft's general-purpose tools might require more configuration to achieve for complex AI ecosystems. * Unified AI API Format: Standardizes request formats across diverse AI models, simplifying AI consumption and reducing maintenance, a unique challenge in AI API integration. * Prompt Encapsulation: Easily create new APIs by combining AI models with custom prompts. Organizations could use MuleSoft for their primary enterprise integrations and traditional REST API management, while leveraging APIPark for its specialized, efficient handling and governance of AI-powered services. This allows each platform to focus on its strengths, creating a hybrid, optimized API gateway architecture.
🚀You can securely and efficiently call the OpenAI API on APIPark in just two steps:
Step 1: Deploy the APIPark AI gateway in 5 minutes.
APIPark is developed based on Golang, offering strong product performance and low development and maintenance costs. You can deploy APIPark with a single command line.
curl -sSO https://download.apipark.com/install/quick-start.sh; bash quick-start.sh

In my experience, you can see the successful deployment interface within 5 to 10 minutes. Then, you can log in to APIPark using your account.

Step 2: Call the OpenAI API.

