# API Management and Gateway

## Introduction

insureMO's API Management platform and API Gateway work together to help API providers like insurance companies to manage, protect and monitor their APIs. 

On the API Management platform,

* Different product factories' APIs can follow the same standard so that they can be managed systematically.

* A unified API management process includes API registration, publishing, monitoring, deprecation, etc.

* All the APIs with unified tenant management are hosted. In this way, the channel can leverage the APIs to do business innovation like cross-selling or up-selling among different LOBs.

* A unified API authorization and authentication mechanism is implemented. In this way, API providers can focus on producing APIs.

* The APIs can still run smoothly even under a peak volume of requests with the rate limit.

* Trace monitor to see the complete steps caused by an API call and to identify the "problem" steps with performance and exception.

* API requests statistics and dashboard in terms of time frame, API provider, and API consumer – a good input to analyze the API quality and improve the APIs.

* insureMO provides common APIs for reuse.

This guide will help you get started quickly on managing registered APIs on the insureMO platform, including access control and administration.

```mermaid
graph LR
    AM(["API Management"])

    P["API Provider"]
    C["API Consumer"]
    M["Monitor APIs"]

    AM --> P
    AM --> C
    AM --> M

    P --> P1["Register API"]
    P1 --> P1a["Import a Swagger file<br>(Routes: Import / Export)"]
    P1 --> P1b["Create a route directly<br>(Routes: Create)"]

    P --> P2["Maintain API metadata<br>(APIs page)"]
    P2 --> P2a["Input / Output Schema"]
    P2 --> P2b["Parameters"]
    P2 --> P2c["Test cases"]

    P --> P3["Manage routes<br>(Routes page)"]
    P3 --> P3a["Gateway settings<br>(CORS / AuthN / AuthZ)"]
    P3 --> P3b["Publish / Unpublish"]
    P3 --> P3c["Download / Delete"]
    P3 --> P3d["Migrate Static Routes"]

    P --> P4["Grant API access to tenants"]
    P4 --> P4a["Grant a role to the tenant"]
    P4 --> P4b["Tenant admin assigns<br>the role to users"]

    C --> C1["View API cards & API docs"]
    C --> C3["Subscribed APIs"]
    C --> C5["Apply to SiteOps<br>when no API permission"]
    C --> C4["Call APIs"]
    C4 --> C4a["Personal Access Token"]
    C4 --> C4b["OAuth2"]
    C4 --> C4c["JWT"]
    C4 --> C4d["Presigned URL"]

    M --> M1["All API Activity"]
    M --> M2["Per API Activity"]
    M --> M3["Detailed API Statistics"]
    M1 --> M4["Data Explorer<br>(drill-down analysis)"]
    M2 --> M4

    classDef root fill:#4CAF50,stroke:#388E3C,color:#FFFFFF,font-weight:bold
    classDef provider fill:#2196F3,stroke:#1976D2,color:#FFFFFF,font-weight:bold
    classDef consumer fill:#FF9800,stroke:#F57C00,color:#FFFFFF,font-weight:bold
    classDef monitor fill:#26A69A,stroke:#00897B,color:#FFFFFF,font-weight:bold
    classDef providerLeaf fill:#E3F2FD,stroke:#64B5F6,color:#0D47A1
    classDef consumerLeaf fill:#FFF3E0,stroke:#FFB74D,color:#E65100
    classDef monitorLeaf fill:#E0F2F1,stroke:#4DB6AC,color:#004D40

    class AM root
    class P provider
    class C consumer
    class M monitor
    class P1,P1a,P1b,P2,P2a,P2b,P2c,P3,P3a,P3b,P3c,P3d,P4,P4a,P4b providerLeaf
    class C1,C3,C5,C4,C4a,C4b,C4c,C4d consumerLeaf
    class M1,M2,M3,M4 monitorLeaf
```
![Data Explorer overview](./image/api_management/API_Management_Data_Explorer_overview.png)
**API provider can manage all APIs**

API provider can manage all APIs through the following items:

- Routes - list all the routes published in the platform by the logged-in user of a particular tenant.
- Subscribed APIs - provide the number of subscribed APIs for a particular tenant.


**On the access control side (authorization control)**

- Grant access to Tenant - API provider can proactively grant access to consumers to use the APIs.

- API permission request - When a user has no permission to call an API, the user can apply to **SiteOps** to grant the permission.

**From the authentication control point of view**

- Personal Access Token (PAT) - Allows API consumers to create and download a PAT. Then API consumers can pass in a PAT to call APIs.

- OAUTH2 - Allows API consumers to get a token by using username and password. Then API consumers can pass in the token to call APIs.

- JWT - Allows API consumers to get a token by using user information. The token can then be used to call APIs.

- Presigned URL - Allows an API provider to generate a time-limited URL after the business authorization is passed on the provider side, so that end users without an insureMO account can access the API through the URL directly. For details, see [Presigned URL](#presigned-url).

* When developing an application or initiating a machine-to-machine process, you are advised to use a Personal Access Token (PAT).

**From the runtime API protection point of view**

All API calls to the insureMO platform are via the API gateway. The API gateway will first conduct an authorization check to see if the API consumer has permission to call the related API; then it will conduct an authentication check to see if a valid token or key is passed in. Only when those two validations are passed can the request be routed to the target endpoint where the API is hosted.

**From Monitoring purpose**

Query entry is only available in the portal environment

- All API Activity

- Per API Activity

- Detail API Statistics

## Key Concepts
**Tenant**<br>
Any entity, such as an insurance company, sales channel or FinTech company, that wants to use insureMO will be considered as a tenant.

**Role of tenant**<br>
From an API perspective, the tenant can be classified as API vendor (API provider) and API consumer.

* ***API vendor or API provider***<br>
A tenant that provides APIs is an API vendor or an API provider.
* ***API consumer***<br>
A tenant that calls APIs provided by an API provider is the API consumer. For example, an insurance company ABC provides a flight delay product quotation API. An E-commerce website which helps ABC to sell flight delay insurance will call the quotation API. The E-commerce website is the API consumer.

## API Life Cycle
**API Life Cycle Management**

* The following diagram shows the API life cycle from its creation and registration to consumption, monitoring and upgrading etc.

![APILifeCycle](./image/api_management/API_Management_1.png)

## API Gateway Architecture
The insureMO API gateway provides multiple benefits for anyone looking to build an insurance experience by using APIs.

- The gateway is the only endpoint that your front-end application will ever need to talk to. This means as long as you have all of your APIs registered on insureMO, you will never encounter any CORS issues and your web app will think it is communicating to a single backend.
- The gateway authenticates each request, ensuring that only API requests with valid tokens or keys pass validation. The API itself does not need to implement these complex authentication mechanisms.
- The gateway can provide multiple additional monitoring functions about your APIs. You can monitor and set alerts based on traffic, and keep on the top of any spike in errors in real time.
- The gateway conducts authorization checks against each request. This means as an API vendor, you can assign access to your APIs to other tenants on the platform. And the gateway will provide full access-control to your APIs. This can open new avenues of collaboration with other insurers, vendors, and partners.

![how_api_gateway_works](./image/api_management/API_Management_2.png)

## User Scenario
### How to Implement Access to a Registered API for Specific Users Only?
**Scenario**

As an API provider, I have developed an API for clients and want to register it with a gateway for client access. The client requires that only specific users can access this API. The following is the detailed implementation method.  

Step-by-Step Implementation Guide

##### 1. Register the API

First, go to the Register API module of the gateway to complete the API registration. Ensure that basic information of the API (such as name, path, request method, etc.) is accurately entered.

##### 2. Determine the User Source (URP Service)

The platform provides multiple UserSources (identity management systems). For details, see: https://docs.insuremo.com/common/doc_00000374

**Default UserSources:**  
* Platform URP (insureMO default URP)
* APP URP (GIMO URP)

**Operation Recommendation**: Select a user source based on the client's scenario. Take Platform URP as an example:
* Go to Account Management
* Create new user accounts for clients under the current tenant

##### 3. Manage API Permissions in Platform URP

**Explanation of Default Permissions:**

By default, all users in the current tenant automatically obtain access permissions to all APIs registered under the tenant through roles starting with r_api_sys.
   
**Operation Steps for Restricting Access:**
1. **Remove default role from users**：If you do not want tenant users to inherit default permissions, go to user permission and remove the role starting with `r_api_sys` from this user . 
2. **Create a Custom Role**: Create a new role in `Role Maintain` (e.g., `client_specific_api_access`). 
3. **Define Permissions**: Create a new permission in `Permission Maintain` (e.g., `api_access_permission`). 
4. **Assign permission to role**：Assign the newly created permission to the custom role in Role Maintain. 
5. **Bind the API to the Permission**: Go to API Permission, search for the registered API, and associate it with the newly created permission (`api_access_permission`). 
6. **Assign Roles to Authorized Users**: Assign the custom role (e.g., `client_specific_api_access`) to users who are allowed to access the API. 

**Result**: Access to the API is granted to users with this role, and denied to those without it or the default `r_sys_api-prefixed` roles.
```mermaid
graph TD
    A[Register API] --> B[Select User Source]
    B --> C[Create Users]
    C --> D{Delete Default Roles?}
    D -->|Yes| E[Delete Default Roles]
    D -->|No| F[Create Custom Role]
    E --> F
    F --> G[Define Permissions]
    G --> H[Bind API to Permissions]
    H --> I[Assign Roles to Authorized Users]
    I --> J[Access Granted]
    
    %% Styling
    classDef step fill:#4CAF50,stroke:#fff,color:white,font-weight:bold,border-radius:6px
    classDef decision fill:#6495ED,stroke:#fff,color:white,font-weight:bold,border-radius:6px
    class A,B,C,E,F,G,H,I step
    class D decision
    class J fill:#2196F3,stroke:#fff,color:white,font-weight:bold,border-radius:6px
```
## API Management & Gateway
Entry: open card "non insurance services",search api management,click the card
## APIs
* **APIs** page - focuses on API metadata management: the input/output schemas, parameters, test cases and documentation of the registered APIs. Creating, editing or deleting metadata records has no impact on gateway routes. The **Swagger Import** button on this page batch-initializes API metadata from a Swagger/OpenAPI file.

* This page aim to management the APIS.It including import the API Swagger file,Management the API details.Just create API in this page will not create a directly route.If you want to create a route please go to the route menu.

![Routes page](./image/api_management/API_Management_Routes_page.png)


Maintain the API details including Input and output schema.Parameters and test case.With this API management, there will provide a lot of API detail information, and it will easy for the Application know how to Work with this API.
![APIs page - API metadata management](./image/api_management/API_Management_APIs_metadata.png)

## Register API
### Register an External API

This chapter will explain how to register an existed API on the insureMO API gateway by importing a Swagger file. The import entry is on the **Routes** page now (see [Routes](#routes)).

1. Prepare your Swagger file if you don't have one. You can use the editor on swagger.io to help you prepare the file. In this section, we will use the pet store as the example API from `petstore.swagger.io`. You will need a text editor installed on your local machine and we recommend the VS Code.

![text](./image/api_management/API_Management_3.png)

2. Log in to [insureMO Portal](https://portal.insuremo.com/) with your personal account.  

<div class="docs-tip"><span class="docs-admonitions-text">tip</span>  

If you don't have insureMO personal account, click **Sign Up** to register one. Then log in to the portal.  

</div>  

3. Click **Catalog** at the top of the home page.  

4. In the left panel of the **Catalog** page, navigate to **Utility & AI** > **Development**. Then, find **API Management** card and click it.  

5. In the left panel of the **API Management** home page, navigate to **Manage APIs** > **Routes**, and click the **Import / Export** dropdown button in the toolbar above the route list to import from a file or a URL.

![Routes page - Import / Export entry](./image/api_management/API_Management_Routes_import.png)


6. You need to choose whether you want to upload the swagger file or point to a URL. For file option, you need to upload the swagger json file from your computer. For "Pointing to an existed URL" option, that is, hosting a swagger file which is very common for many external APIs that are publicly available, this approach will be shown in our example. Please enter the following URL:
https://petstore.swagger.io/v2/swagger.json


![text](./image/api_management/API_Management_5.png)

7. Select the environment and tenant from the dropdown list. An API provider can register its own API.


![text](./image/api_management/API_Management_6.png)



8. Click **Submit** and the system will ask you to double-check the “host” where the API is hosted. (The value of the "host" is retrieved from the swagger file). After submission, you can see your APIs on the **Routes** page.


![text](./image/api_management/API_Management_8.png)

## Create a Route Directly
There is another way to create one API, which is to create the route directly on the **Routes** page by clicking the **Create** button in the toolbar.
![APIs page](./image/api_management/API_Management_APIs_page.png)



![Create Route fields](./image/api_management/API_Management_Routes_create_fields.png)
* API Name: The name of the API.
* Vendor Code: The vendor code of the API, which is the first segment of the public API path.
* Route Path: The path of the API. `**` is supported for wildcard matching.
* API Method: The HTTP method of the API, such as `GET`, `POST` or `ANY`.
* Version: The version segment of the public API path.
* Description: The description for the API.
* Route Nodes: The host where the API is hosted. API Gateway will help to route the request to the host.
* Service Path: The path of the API under the context of the host where the API is hosted.

Vendor Code, Version, Route Path and API Method cannot be changed after the route is created.

![Edit Route dialog - publish/unpublish](./image/api_management/API_Management_Route_edit_publish.png)

* In most cases, the route path coincides with the service path.
* The public API path serves as the API endpoint that your API consumers will interact with, in the form of `/{vendor code}/{version}/{route path}`. Once the consumers make a call to this path, the gateway will forward the request to the combination of Route Nodes and the Service Path. In this way, you can manage the backend service without causing any disruption to your API consumers.

In the route edit dialog shown above, the **ROUTE PREVIEW** banner shows the mapping from the gateway entry URL to the backend service URL, together with the status of common gateway settings such as AuthN, AuthZ and CORS. In **Gateway Settings**, common options such as **Enable CORS**, **Enable Auth** and **Enable Authorization** are provided as toggles, and the JSON attributes can be edited directly for advanced configuration.

Publish/ Unpublish API:

  When you click **Unpublish**, the API endpoint is not available to your API consumers. The route still stays in the list on the **Routes** page, with its status changed to **Unpublished**.

![Route edit dialog](./image/api_management/API_Management_Route_edit.png)


## Routes

Route management and API metadata management are two independent lines on the insureMO platform:

* **Routes** page - focuses on gateway route configuration: API routes, route nodes, and gateway routing settings including authentication, CORS, rate limiting and backend routing.

![APIs page](./image/api_management/API_Management_APIs_page.png)



Click **Routes** in the left panel, and you will see that all the APIs that were defined in your swagger file are now imported and listed. These are the routes your tenant has registered on the insureMO platform. API providers can search all registered routes in insureMO. Users can manually edit some attributes:


The following actions are available in the toolbar above the route list:

* **Create** - create a route directly without a Swagger file. See [Create a Route Directly](#create-a-route-directly).
* **Import / Export** - import routes from a Swagger file (see [Register an External API](#register-an-external-api)) or export routes. The import entry that was previously under **Create APIs** on the API Management page has been moved here.
* **Download** / **Delete** - download or delete the selected routes.
* **Migrate Static Routes** - migrate the static routes of the current tenant into routes in one click. See [Migrate Static Routes](#migrate-static-routes).

### Migrate Static Routes

Click **Migrate Static Routes** in the toolbar of the **Routes** page to migrate the static routes of the current tenant into routes in one click.



Notes:

* The migration applies to **all** static routes of the current tenant in the selected environment; the selection in the table is ignored.
* During the migration, the static route path `/{vendor}/{version}/{path}` is split into separate `vendor_code`, `version` and `path` fields, and the gateway attribute keys are renamed to the `x-mo-gateway-*` convention (unknown keys are kept as-is).
* The dialog shows a dry-run preview (total, will migrate, will fail) before you confirm. Click **Re-check** to refresh the preview.
* The original static routes are **deleted** after the migration, and the operation is **irreversible**. Export a backup first if needed.

### Other Considerations for External APIs 
* Ensure your API is accessible on the internet. You may need to whitelist insureMO API Gateway IP addresses to reach the target endpoints.
* We provide two URPs in insureMO now. If you are developing a tool for insureMO, use the insureMO Foundation URP by default. If you are developing a GIMO application and want to use the GIMO URP to Authorization, please select **APP URP** in the **Authentication Service** section of the route edit dialog (see [Create a Route Directly](#create-a-route-directly)).


* Some external APIs may have their own authentication mechanism and do not want insureMO API Gateway to do the authentication. In this case, you can configure to disable the "Enable Auth" option through the following screen.
* By default, insureMO domain do not support the no-auth APIs. If you want to register a no-auth API, please use your domain name with the insureMO like below. When you disable the auth, this `x-mo-gateway-router-domain` key is required and the value should not include `insuremo`.


![Routes list](./image/api_management/API_Management_Routes_list.png)


## Subscribed APIs
If a tenant is an API consumer, it can be granted APIs by an API provider. Is there a centralized place for API consumer to see the APIs that are assigned to it? The answer is through Subscribed APIs menu. By clicking **Subscribed APIs**, users can see the following screen, which lists all API providers that have granted APIs, and the number of APIs that have been granted.

![SubscribedAPI-New-1](./image/api_management/API_Management_24.png)

Click **API vendor**, you will see all the APIs owned by this vendor.
 Then you can see the API DOC provided by the vendor.

![SubscribedAPI-New-2](./image/api_management/API_Management_25.png)
![SubscribedAPI-New-2](./image/api_management/API_Management_26.png)



## How to Use API Management
**Scenario**

An insurance company ABC provides Quotation API and Issuance API to sales channel Bank A and Post Office B. Bank A and Post Office B need to call the APIs.

**Solution**
1. Create a tenant account tenantabc for insurance company ABC on insureMO, and the tenantabc needs to register their APIs on the insureMO.

2. Create a tenant account tenantbanka for Bank A, and create a tenant account tenantpostofficeb for Post Office B.

3. Grant their API access permissions to tenantbanka and tenantpostofficeb by tenantabc.

4. Call the APIs by passing in Personal Access Token or an OAUTH2 token through tenantbanka/tenantpostofficeb. 

<div class="docs-note"><span class="docs-admonitions-text">note</span> 

The Personal Access Token or OAUTH2 token needs to be obtained in advance before calling the APIs. For more details, see [Authentication](#authentication).

</div>

## Authentication
insureMO API Gateway supports the following methods of authentication:


- OAuth2 Token
- JWT
- Personal Access Token (PAT)
- Presigned URL

Personal Access Token (PAT) and OAUTH2 authentication are widely used. For details, see（https://docs.insuremo.com/common/doc_00000359#token)

A presigned URL is a special method that shares an API with users who do not have an insureMO account. For details, see [Presigned URL](#presigned-url).

## Presigned URL

A presigned URL is a time-limited URL generated by the API provider, through which end users who do not have an insureMO account can access the target API directly, similar to the presigned URLs of object storage services.

The typical flow is:

1. The end user logs in to your own application with your own account system.
2. Your backend performs the business authorization check and, if allowed, calls the sign API with your token to get a presigned URL.
3. Your backend returns the URL to the end user, for example, as a link embedded in a page or an email.
4. The end user opens the URL in a browser or with an HTTP client. The API gateway verifies the signature and the expiry automatically and then routes the request to the target API. No login or token is required on the end user side.

### Sign API

```
POST {{insuremo_gw_url}}/mo-fo/v1/gateway/v3/presign/sign
Authorization: Bearer <token>
X-Mo-Target-Tenant: <tenant>
```

Request body:

| Field | Required | Description |
|---|---|---|
| method | Yes | The HTTP method bound to the URL, such as `GET`. |
| path | Yes | The target API path, which must start with the tenant prefix, such as `/mo-fo/v1/policy/query`. |
| resource | Yes | A custom resource descriptor embedded in the URL, such as `policy:12345`. The target API reads it for a secondary check. |
| validity_seconds | Yes | The validity period of the URL in seconds. There is no default value and no upper limit. For example, `604800` stands for 7 days. |
| host | No | Binds the URL to one domain. Requests from other domains are rejected. |
| include_host | No | If `true`, the response returns a full URL including the scheme and host. |

Example:

```bash
curl -X POST "{{insuremo_gw_url}}/mo-fo/v1/gateway/v3/presign/sign" \
  -H "Authorization: Bearer <token>" \
  -H "X-Mo-Target-Tenant: mo-fo" \
  -H "Content-Type: application/json" \
  -d '{
    "method": "GET",
    "path": "/mo-fo/v1/policy/query",
    "resource": "policy:12345",
    "validity_seconds": 604800,
    "include_host": true
  }'
```

Response (simplified):

```json
{
  "data": {
    "url": "https://<gateway>/<path>?x-mo-sig=...&x-mo-exp=...&x-mo-kid=...&x-mo-res=policy%3A12345",
    "expires_at": "2026-09-14T08:00:00Z",
    "kid": "<key id>"
  }
}
```

`data.url` is the presigned URL to distribute to the end user, and `data.expires_at` is the expiry time in RFC3339 UTC format. If the request is invalid, the sign API returns business error codes such as `w_presign_bad_request` and `w_presign_validation` (499); `e_presign_config` (599) indicates a platform configuration problem.

### How to Write the Target API

* **Read-only and idempotent only.** Do not rely on any login state, because the end user does not hold any insureMO token.
* **Do not expect a real user identity.** When the signature is verified, the gateway forwards the request with a virtual identity: the `X-Mo-User-Id` header is `{tenant}.anonymous` and the `X-Mo-Auth-Type` header is `presigned`.
* **Read the `x-mo-res` query parameter for the secondary check.** The signature only proves that the URL was signed by the provider and has not expired; it does not replace business rules. For example, if `resource` is `policy:12345`, the API should make sure the response contains the data of policy 12345 only.
* **Business authorization happens at sign time.** Only call the sign API after the end user passes your own authorization check, because anyone who gets the URL can access the API within its validity.

### Notes

* The URL cannot be modified. The HTTP method, the path and (if set) the host are bound to the signature; any change invalidates the URL.
* Set `validity_seconds` to the shortest period that is enough for the business scenario, for example, 5–30 minutes for one-off download links, 1–24 hours for short-term sharing, and up to 7 days for long-term sharing.
* If the verification service is unavailable, the gateway rejects the request instead of letting it pass (fail-closed).
* Platform key rotation does not invalidate the URLs signed before the rotation.

## User Source 
The `user_source_id` currently supported by the platform is as follows:

1. **mo:** represents the insureMO platform's default URP.

2. **platform:** represents GIMO's APP URP.

3. **member:** represents GIMO member service.

4. **limo:** represents LIMO's URP(dorami).

5. **jpmember:** represents Japan cloud jp-member-service.

（https://docs.insuremo.com/common/doc_00000374)

## How to create Swagger file

### Lesson 2: Building a Swagger file

Swagger is a toolset for the structured API development. Swagger files are a standardized way of defining an API based on the industry-standard Open API Specification. It includes the following key items:

* Endpoints and URLs
* Operations on those endpoints
* Operation parameters Input and Output for each operation
* Contact information, license, terms of use etc.

### Header Fields

![text](./image/api_management/API_Management_29.png)

The header fields contain basic information about identifying the API. The most important field in the header is the 'host', which defines where this API actually runs. In this case, the host is invalid because it has not yet been assigned by the insureMO Portal. When publishing an API generated by the API Factory and selecting the target environment, the host will be automatically populated to the domain name of that environment.

Another interesting field is the "schemes" field, which defines which protocols this API can support. Most RESTful APIs support the http scheme, while certain APIs use other protocols such as SMTP.

insureMO also uses the tags fields to organize registered APIs. These are only for informational purposes. For more details on the header fields, check the documentation on the OpenAPI specification.

### Paths
One of the main parts of a swagger file is the section defining the paths. Each path essentially defines an Endpoint that provides some sort of capability to the API consumers. APIs generated by the API Factory generally only use one path, but you're allowed to define as many paths as you want when creating swagger files. Each path defines a list of HTTP Methods that it supports (POST, GET, PUT, DELETE etc.).

![text](./image/api_management/API_Management_30.png)

Under each method, you can define another layer of Header Fields, including tags, schemes, content types (consumes/produces), etc. You can also define a collection of responses that this method will potentially return in the form of all the possible HTTP Codes. In most cases, you just have to specify the description message which will be returned alongside that code. However, in the case where your API returns a body (i.e. HTTP 200), you must define the schema of the response. As you have seen before, we define the schema as a #ref object. This indicates to the reader of the file that this object is actually defined in another part of the swagger file.

![text](./image/api_management/API_Management_31.png)

### Object Definitions
It is a good idea to define all of your request/response body schemas as 'definition' at the bottom of your swagger file. This enhances reusability and keeps your swagger file clean and concise. Since your API work on the same objects most of the time, it makes sense to only define them once. In our example, we define **RequestBodyInfo** and **ResponseInfo** as definitions.

This concept of definitions is really useful when you are dealing with different types of small objects. You only have to define them once. For instance, things like Policy, Insured Person, Car, House etc, will be used through your API definition for any given insurance API. It makes sense to define them in one place and refer to them when you want to tell the API consumer to expect that object at a given place in the request/response.

![text](./image/api_management/API_Management_32.png)

Every definition defines the type and properties of any given object. It is possible to define any JSON object in this schema format. We recommend you to look at the documentation under the OpenAPI specification to learn how various things can be defined.

### Swagger Builder
Swagger provides a tool that helps you visualize your schema in a very structured format and validate it for you. This is a preferred mechanism to author any swagger file. You can access this tool via the following URL:

http://editor.swagger.io/

## API Monitoring

### All APIs Activities

Monitoring is an important part of daily business because it is related to products, services and APIs you designed and published. It also helps to gain important insights into the trends and behaviors of users.

API monitor provides API registration, publishing, and access statistics through various charts.

Monitoring is a visualization tool through which you can analyze land and check all activities through the logs efficiently.

The API activity dashboard will count API activity by inputting Time Frame, Vendor, and Consumer.

Interval: you can select Minute, Hour, Day, Month. If you change the interval, the X-axis will change as per change is done. Move your mouse on the chart, then you will get the exact value of each point.

Click **Search**, the dashboard will display the Average Response Time, Error hits, and Success hits.

![All API Activity 1-Adv-0211](./image/api_management/API_Management_44.png)

And at the same time, the top 10 API and top 10 Failure APIs path, name, and visit count will be displayed.
The visit count will be grouped by the response code. The response code 200 will be regarded as success hits.

![All API Activity -Pie chart0211](./image/api_management/API_Management_46.png)

### Per API Activities
Per API Activity allows users to check the activities of a specific API. In addition to the search criteria for All API Activity, the dedicated API path is required.

It will count the API activities by inputting Time Frame, Vendor, and Consumer.

Interval: you can select Minute, Hour, Day, Month. If you change the interval, the X-axis will be changed based on your setting.
Move your mouse on the chart, then you will get the exact value of each point.

![Per API Activity Search criteria0211](./image/api_management/API_Management_47.png)

Click **Search**, the dashboard will display the Average Response Time, Error hits, and Success hits

![TEXT](./image/api_management/API_Management_48.png)

![Per API Activity-Pie chart0211](./image/api_management/API_Management_49.png)

## Data Explorer

As an extension of the **All API Activity** and **Per API Activity** pages, **Data Explorer** provides a drill-down analysis on top of the API monitoring data, so that you can locate abnormal requests and performance problems quickly.

In **Data Explorer**, you first narrow down the scope with the filter criteria such as Time Frame, Consumer, Vendor, User Name, Current App and API Path, and then build a drill-down pipeline. Each level of the pipeline aggregates the data by one field and drills into the previous level, for example, User → API Path → Status Code. Quick presets such as **User → API → Status** and **API → Status → User** are provided, and the query result can be exported as a CSV file.

Two typical analysis paths are as follows:

* **User-first view** - Select a user, view all the APIs hit by this user, and then select a specific API to view the HTTP response code split for that user/API combination.

![Data Explorer - user-first view](./image/api_management/API_Management_Data_Explorer_user_first.png)

* **API-first view** - Select an API, view all the HTTP response codes for this endpoint, and then select a specific response code to view the specific users impacted.

![Data Explorer - API-first view](./image/api_management/API_Management_Data_Explorer_api_first.png)

## Detailed API Statistics
In this screen, users can download the API call statistics and check the details of the top 10 APIs.

![Detail API Statistics-Adv Feature0211](./image/api_management/API_Management_50.png)

Click **Search**, the result will display the API Path, Name, Requests hits, Success hits, and Error hits.

![DetailAPI-New-1](./image/api_management/API_Management_51.png)

A button is used to download the form at the bottom of the sheet. Click it and the query result will be downloaded as a CSV file.

![DetailAPI-New-2](./image/api_management/API_Management_52.png)

For each displayed API, the detailed activity information will be displayed by clicking the API path or name.

![DetailAPI-New-3](./image/api_management/API_Management_53.png)

## Common Error Message from gateway:

* 401: Token is not correct.
* 403: Permission denied, you do not have permission to call this API.
* 429: Throttling, exceeding the number of visits.
* 404: Incorrect API path or unpublished API.



## FAQs
**Q : What is Swagger API Spec?**

A: Swagger API Spec defines a standard, programming language-agnostic interface description for REST APIs. Similar to what interface descriptions have done for WSDL, Swagger API can use YAML or JSON format. On January 1st 2016, the Swagger specification was contributed to the OpenAPI Initiative (OAI), and became the basis of the OpenAPI Specification.

**info** : contains API information: title, version.

**title**: Your API name.

**version**: An arbitrary string that specifies the API version.

**host**: The host (name or IP) serving the API.

**basePath**: The base path where the API is served.

**schemes**: API transfer protocol. Values MUST be from the list: "http", "https", "ws", "wss".

**consumes**: A list of MIME types the APIs can consume.

**produces**: A list of MIME types the APIs can produce.

**externalDocs**: Allows referencing an external resource for extended documentation.

**paths**: The available paths and operations for the API including the following parts.

- Summary: A short summary of what the operation does
- Description: A verbose explanation of the operation behavior
- OperationId: Unique string used to identify the operation
- Parameters: A list of parameters that are applicable for this operation
- Responses: The list of possible responses as they are returned from executing this operation
- Tags: A list of tags for API documentation control

**definitions**: The Schema Object enables the definition of input and output data types. These types include objects, primitives and arrays. The following properties are taken directly from the JSON Schema definition and follow the same specifications:

- $ref: As a JSON Reference
- format: Primitive data types in the Swagger Specification are based on the types supported by the JSON-Schema Draft 4.
- Extension Fields: Enables extensions to the Swagger Schema. The field name MUST begin with x-, for example: x-{tenant code}-cors-enabled

Swagger API Spec describes the parameters of request message for every operation of Rest API (Path, Query, Body, Form), the status code of response message and the JSON structure of message body. It can be provided not only by the developers who use the API, but also by the formal abstraction of the Rest API interface.

For more details, see Swagger 2.0 standard

**Q: What API types are supported by insureMO API Gateway?**

A: Currently, we support restful API and SOAP based API.

**Q: What is rate limit control? And how this is implemented here?**

A: Rate limit control ensures the maximum hits allowed within a specific time unit, for example 100 API calls per second. An API call exceeding this criterion will be rejected by the API gateway. The insureMO API gateway allows for the configuration of the rate limit value at both tenant level and user level.

**Q: How the security aspect of the API is implemented in terms of accessing it?**

A: There are two layers of security control. Firstly, the API gateway will check the authorization permission of an API caller and see if it has permission to call the target API; Secondly, the API Gateway helps to validate the access token or key which is a kind of authentication.

**Q: If there are any newly registered APIs that are published, will they be automatically reflected in the service card in API catalog?**

A: If you upload a new swagger file that contains different APIs, it will be automatically shown as a new card in the API catalog.

**Q: How can I make the API I registered accessible only to users from specific user sources?**

A: If you just want your API be accessed by the member user-source users, click **Edit API**, input `{"x-mo-gateway-user-source-id":"member"}` in the attributes textbox. If you want this API be accessed by member users and mo users, use the following configuration:`{"x-mo-gateway-user-source-id":"member,mo"}`.

**Q: How to change the api path?**

A: You can't change the registerd api path,please delete it and reimport or create again.

**Q: Could i limit the access rate base on one api?**
A: We can't support this feature by now, but this feature is in our plan.
