
# 查询资源实例数量 - CountResourceInstance
#### 功能介绍
使用标签过滤实例，查询资源实例数量
#### 调用方法
请参见[如何调用API](https://support.huaweicloud.com/api-secmaster/secmaster_03_0008.html)。
#### 授权信息
账号具备所有API的调用权限，如果使用账号下的IAM用户调用当前API，该IAM用户需具备调用API所需的权限，具体权限要求请参见[权限和授权项](https://support.huaweicloud.com/api-secmaster/secmaster_03_0023.html)。
#### URI
POST /v1/{project_id}/{resource_type}/resource-instances/count
表1路径参数 
| 参数            | 是否必选 | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
|:---|:---|:---|:---|
| resource_type | 是    | String | **参数解释:** 资源类型 通过调用IAM服务获取用户Token接口获取（响应消息头中X-Subject-Token的值）。 **约束限制**: 不涉及 **取值范围**: 不涉及 **默认值**: 不涉及                                       |
| project_id    | 是    | String | **参数解释：** 项目ID，用于明确项目归属，配置后可通过该ID查询项目下资产，可以通过调用API获取，也可以从控制台获取。[获取项目ID](https://support.huaweicloud.com/api-secmaster/secmaster_03_0014.html) **约束限制：** 不涉及 **取值范围：** 不涉及 **默认取值：** 不涉及 |
   
#### 请求参数
表2请求Header参数 
| 参数           | 是否必选 | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
|:---|:---|:---|:---|
| Content-type | 是    | String | **参数解释：** 内容类型 - application/json;charset=UTF-8 普通API请求的类型    **约束限制：** 不涉及 **取值范围：** - application/json;charset=UTF-8    **默认取值：** 不涉及 |
| X-Auth-Token | 是    | String | **参数解释:** 用户Token。 通过调用IAM服务获取用户Token接口获取（响应消息头中X-Subject-Token的值）。 **约束限制**: 不涉及 **取值范围**: 不涉及 **默认值**: 不涉及                                                                                                                                                                                                                                                                                                                      |
   
表3请求Body参数 
| 参数              | 是否必选 | 参数类型                                                                          | 描述                                                                                                                                                                                                                                                               |
|:---|:---|:---|:---|
| without_any_tag | 否    | Boolean                                                                       | 不包含任意一个标签，该字段为true时查询所有不带标签的资源，此时忽略 "tags"、"tags_any"、"not_tags"、"not_tags_any"字段。                                                                                                                                                                               |
| tags            | 否    | Array of [WorkspaceTag] objects | 包含标签，最多包含50个key，每个key下面的value最多10个，每个key对应的value可以为空数组但结构体不能缺失 。Key不能重复，同一个key中values不能重复。结果返回包含所有标签的资源列表，key之间是与的关系，key-value结构中value是或的关系。无tag过滤条件时返回全量数据。                                                                                                     |
| sys_tags        | 否    | Array of [WorkspaceTag] objects | 仅op_service权限可以使用此字段做资源实例过滤条件。目前TMS调用时只包含一个tag结构体。key：_sys_enterprise_project_idvalue：企业项目id列表目前TMS调用时，key下面只包含一个value。0表示默认企业项目sys_tags和租户标签过滤条件（without_any_tag 、tags、tags_any、not_tags、not_tags_any）不能同时使用无sys_tags时按照tag接口处理，无tag过滤条件时返回全量数据。                |
| matches         | 否    | Array of [Match] objects               | **参数解释:**搜索字段,key为要匹配的字段，如resource_name等。value为匹配的值。key为固定字典值，不能包含重复的key或不支持的key。根据key的值确认是否需要模糊匹配，如resource_name默认为模糊搜索（不区分大小写），如果value为空字符串精确匹配（多数服务不存在资源名称为空的情况，因此此类情况返回空列表）。resource_id为精确匹配。第一期只做resource_name，后续再扩展。**约束限制** :不涉及 **取值范围**:不涉及**默认值**: 不涉及 |
   
 表4WorkspaceTag 
| 参数     | 是否必选 | 参数类型             | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
|:---|:---|:---|:---|
| key    | 是    | String           | **参数解释:** 键。最大长度128个unicode字符。 key不能为空。(搜索时不对此参数做字符集校验)，key不能为空或者空字符串，不能为空格，校验和使用之前先trim 前后半角空格。 **约束限制**: 不涉及 **取值范围**: 不涉及 **默认值**: 不涉及                                                                                                              |
| values | 是    | Array of strings | **参数解释:** 值列表。每个值最大长度255个unicode字符，校验和使用之前先trim 前后半角空格。 value可为空数组但不可缺省。 如果values为空列表，则表示any_value（查询任意value）。value之间为或的关系。 **约束限制**: 不涉及 **取值范围**: 不涉及 **默认值**: 不涉及 |
   
 表5Match 
| 参数    | 是否必选 | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                            |
|:---|:---|:---|:---|
| key   | 是    | String | **参数解释:** 键。第一期限定为resource_name,后续扩展。 **约束限制**: 不涉及 **取值范围**: 不涉及 **默认值**: 不涉及 |
| value | 是    | String | **参数解释:** 值。每个值最大长度255个unicode字符。 **约束限制**: 不涉及 **取值范围**: 不涉及 **默认值**: 不涉及     |
   
#### 响应参数
**状态码：200**
表6响应Body参数 
| 参数          | 参数类型    | 描述   |
|:---|:---|:---|
| total_count | Integer | 资产总数 |
   
**状态码：400**
表7响应Body参数 
| 参数         | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                 |
|:---|:---|:---|
| error_code | String | **参数解释：** 错误码 **约束限制：** 无 **取值范围：** Secmaster.000000\~Secmaster.99999 **默认取值：** 不涉及 |
| error_msg  | String | **参数解释：** 错误描述 **约束限制：** 无 **取值范围：** 无 **默认取值：** 不涉及                                |
   
**状态码：401**
表8响应Body参数 
| 参数         | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                 |
|:---|:---|:---|
| error_code | String | **参数解释：** 错误码 **约束限制：** 无 **取值范围：** Secmaster.000000\~Secmaster.99999 **默认取值：** 不涉及 |
| error_msg  | String | **参数解释：** 错误描述 **约束限制：** 无 **取值范围：** 无 **默认取值：** 不涉及                                |
   
**状态码：403**
表9响应Body参数 
| 参数         | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                 |
|:---|:---|:---|
| error_code | String | **参数解释：** 错误码 **约束限制：** 无 **取值范围：** Secmaster.000000\~Secmaster.99999 **默认取值：** 不涉及 |
| error_msg  | String | **参数解释：** 错误描述 **约束限制：** 无 **取值范围：** 无 **默认取值：** 不涉及                                |
   
**状态码：404**
表10响应Body参数 
| 参数         | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                 |
|:---|:---|:---|
| error_code | String | **参数解释：** 错误码 **约束限制：** 无 **取值范围：** Secmaster.000000\~Secmaster.99999 **默认取值：** 不涉及 |
| error_msg  | String | **参数解释：** 错误描述 **约束限制：** 无 **取值范围：** 无 **默认取值：** 不涉及                                |
   
**状态码：500**
表11响应Body参数 
| 参数         | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                 |
|:---|:---|:---|
| error_code | String | **参数解释：** 错误码 **约束限制：** 无 **取值范围：** Secmaster.000000\~Secmaster.99999 **默认取值：** 不涉及 |
| error_msg  | String | **参数解释：** 错误描述 **约束限制：** 无 **取值范围：** 无 **默认取值：** 不涉及                                |
   
#### 请求示例
```
https://{endpoint}/v1/{project_id}/{resource_type}/resource-instances/count
{
  "without_any_tag" : true,
  "tags" : [ {
    "key" : "tag_name",
    "values" : [ "tag_value", "tag_value1" ]
  }, {
    "key" : "tag_name1",
    "values" : [ "tag_value", "tag_value1" ]
  } ],
  "sys_tags" : [ {
    "key" : "_sys_enterprise_project_id",
    "values" : [ "5aa119a8-d25b-45a7-8d1b-88e127885635" ]
  } ],
  "matches" : [ {
    "key" : "resource_name",
    "value" : "resource1"
  } ]
}
```
#### 响应示例
**状态码：200**
OK
```
{
  "total_count" : 1000
}
```
#### SDK代码示例
SDK代码示例如下。
- [Java]
  ```
  package com.huaweicloud.sdk.test;
  import com.huaweicloud.sdk.core.auth.ICredential;
  import com.huaweicloud.sdk.core.auth.BasicCredentials;
  import com.huaweicloud.sdk.core.exception.ConnectionException;
  import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
  import com.huaweicloud.sdk.core.exception.ServiceResponseException;
  import com.huaweicloud.sdk.secmaster.v1.region.SecMasterRegion;
  import com.huaweicloud.sdk.secmaster.v1.*;
  import com.huaweicloud.sdk.secmaster.v1.model.*;
  import java.util.List;
  import java.util.ArrayList;
  public class CountResourceInstanceSolution {
      public static void main(String[] args) {
          // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
          // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
          String ak = System.getenv("CLOUD_SDK_AK");
          String sk = System.getenv("CLOUD_SDK_SK");
          String projectId = "{project_id}";
          ICredential auth = new BasicCredentials()
                  .withProjectId(projectId)
                  .withAk(ak)
                  .withSk(sk);
          SecMasterClient client = SecMasterClient.newBuilder()
                  .withCredential(auth)
                  .withRegion(SecMasterRegion.valueOf("<YOUR REGION>"))
                  .build();
          CountResourceInstanceRequest request = new CountResourceInstanceRequest();
          request.withResourceType("{resource_type}");
          QueryResourceInstanceRequestBody body = new QueryResourceInstanceRequestBody();
          List<Match> listbodyMatches = new ArrayList<>();
          listbodyMatches.add(
              new Match()
                  .withKey("resource_name")
                  .withValue("resource1")
          );
          List<String> listSysTagsValues = new ArrayList<>();
          listSysTagsValues.add("5aa119a8-d25b-45a7-8d1b-88e127885635");
          List<WorkspaceTag> listbodySysTags = new ArrayList<>();
          listbodySysTags.add(
              new WorkspaceTag()
                  .withKey("_sys_enterprise_project_id")
                  .withValues(listSysTagsValues)
          );
          List<String> listTagsValues = new ArrayList<>();
          listTagsValues.add("tag_value");
          listTagsValues.add("tag_value1");
          List<String> listTagsValues1 = new ArrayList<>();
          listTagsValues1.add("tag_value");
          listTagsValues1.add("tag_value1");
          List<WorkspaceTag> listbodyTags = new ArrayList<>();
          listbodyTags.add(
              new WorkspaceTag()
                  .withKey("tag_name")
                  .withValues(listTagsValues1)
          );
          listbodyTags.add(
              new WorkspaceTag()
                  .withKey("tag_name1")
                  .withValues(listTagsValues)
          );
          body.withMatches(listbodyMatches);
          body.withSysTags(listbodySysTags);
          body.withTags(listbodyTags);
          body.withWithoutAnyTag(true);
          request.withBody(body);
          try {
              CountResourceInstanceResponse response = client.countResourceInstance(request);
              System.out.println(response.toString());
          } catch (ConnectionException e) {
              e.printStackTrace();
          } catch (RequestTimeoutException e) {
              e.printStackTrace();
          } catch (ServiceResponseException e) {
              e.printStackTrace();
              System.out.println(e.getHttpStatusCode());
              System.out.println(e.getRequestId());
              System.out.println(e.getErrorCode());
              System.out.println(e.getErrorMsg());
          }
      }
  }
  ```
- [Python]
  ```
  # coding: utf-8
  import os
  from huaweicloudsdkcore.auth.credentials import BasicCredentials
  from huaweicloudsdksecmaster.v1.region.secmaster_region import SecMasterRegion
  from huaweicloudsdkcore.exceptions import exceptions
  from huaweicloudsdksecmaster.v1 import *
  if __name__ == "__main__":
      # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
      # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
      ak = os.environ["CLOUD_SDK_AK"]
      sk = os.environ["CLOUD_SDK_SK"]
      projectId = "{project_id}"
      credentials = BasicCredentials(ak, sk, projectId)
      client = SecMasterClient.new_builder() \
          .with_credentials(credentials) \
          .with_region(SecMasterRegion.value_of("<YOUR REGION>")) \
          .build()
      try:
          request = CountResourceInstanceRequest()
          request.resource_type = "{resource_type}"
          listMatchesbody = [
              Match(
                  key="resource_name",
                  value="resource1"
              )
          ]
          listValuesSysTags = [
              "5aa119a8-d25b-45a7-8d1b-88e127885635"
          ]
          listSysTagsbody = [
              WorkspaceTag(
                  key="_sys_enterprise_project_id",
                  values=listValuesSysTags
              )
          ]
          listValuesTags = [
              "tag_value",
              "tag_value1"
          ]
          listValuesTags1 = [
              "tag_value",
              "tag_value1"
          ]
          listTagsbody = [
              WorkspaceTag(
                  key="tag_name",
                  values=listValuesTags1
              ),
              WorkspaceTag(
                  key="tag_name1",
                  values=listValuesTags
              )
          ]
          request.body = QueryResourceInstanceRequestBody(
              matches=listMatchesbody,
              sys_tags=listSysTagsbody,
              tags=listTagsbody,
              without_any_tag=True
          )
          response = client.count_resource_instance(request)
          print(response)
      except exceptions.ClientRequestException as e:
          print(e.status_code)
          print(e.request_id)
          print(e.error_code)
          print(e.error_msg)
  ```
- [Go]
  ```
  package main
  import (
  "fmt"
  "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
      secmaster "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/secmaster/v1"
  "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/secmaster/v1/model"
      region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/secmaster/v1/region"
  )
  func main() {
      // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
      // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
      ak := os.Getenv("CLOUD_SDK_AK")
      sk := os.Getenv("CLOUD_SDK_SK")
      projectId := "{project_id}"
      auth, err := basic.NewCredentialsBuilder().
          WithAk(ak).
          WithSk(sk).
          WithProjectId(projectId).
          SafeBuild()
      if err != nil {
          fmt.Println(err)
          return
      }
      hcClient, err := secmaster.SecMasterClientBuilder().
           WithRegion(region.ValueOf("<YOUR REGION>")).
           WithCredential(auth).
           SafeBuild()
      if err != nil {
          fmt.Println(err)
          return
      }
      client := secmaster.NewSecMasterClient(hcClient)
      request := &model.CountResourceInstanceRequest{}
  request.ResourceType = "{resource_type}"
  var listMatchesbody = []model.Match{
          {
              Key: "resource_name",
              Value: "resource1",
          },
      }
  var listValuesSysTags = []string{
          "5aa119a8-d25b-45a7-8d1b-88e127885635",
      }
  var listSysTagsbody = []model.WorkspaceTag{
          {
              Key: "_sys_enterprise_project_id",
              Values: listValuesSysTags,
          },
      }
  var listValuesTags = []string{
          "tag_value",
      "tag_value1",
      }
  var listValuesTags1 = []string{
          "tag_value",
      "tag_value1",
      }
  var listTagsbody = []model.WorkspaceTag{
          {
              Key: "tag_name",
              Values: listValuesTags1,
          },
          {
              Key: "tag_name1",
              Values: listValuesTags,
          },
      }
  withoutAnyTagQueryResourceInstanceRequestBody:= true
  request.Body = &model.QueryResourceInstanceRequestBody{
  Matches: &listMatchesbody,
  SysTags: &listSysTagsbody,
  Tags: &listTagsbody,
  WithoutAnyTag: &withoutAnyTagQueryResourceInstanceRequestBody,
  }
  response, err := client.CountResourceInstance(request)
  if err == nil {
          fmt.Printf("%+v\n", response)
      } else {
          fmt.Println(err)
      }
  }
  ```
- [更多]
  更多编程语言的SDK代码示例，请参见[API Explorer](https://console.huaweicloud.com/apiexplorer/#/openapi/SecMaster/sdk?api=CountResourceInstance&version=v1)的代码示例页签，可生成自动对应的SDK代码示例。
#### 状态码
| 状态码 | 描述    |
|:---|:---|
| 200 | OK    |
| 400 | 参数非法  |
| 401 | 鉴权失败  |
| 403 | 权限不足  |
| 404 | 资源未找到 |
| 500 | 系统异常  |
   
#### 错误码
请参见[错误码](https://support.huaweicloud.com/api-secmaster/ErrorCode.html)。
