# 查询弹性公网IP资源实例 - ListPublicipsByTags
#### 功能介绍
使用标签过滤实例
#### 调试
您可以在[API Explorer](https://console.huaweicloud.com/apiexplorer/#/openapi/EIP/doc?api=ListPublicipsByTags&version=v2)中调试该接口，支持自动认证鉴权。
#### 授权信息
账号具备所有API的调用权限，如果使用账号下的IAM用户调用当前API，该IAM用户需具备调用API所需的权限。
- 如果使用角色与策略授权，具体权限要求请参见[权限和授权项](https://support.huaweicloud.com/api-eip/eip_apipermission_0000.html)。
- 如果使用身份策略授权，需具备如下身份策略权限。
  
  | 授权项                    | 访问级别 | 资源类型（\*为必须） | 条件键 | 别名                   | 依赖的授权项 |
  |:---|:---|:---|:---|:---|:---|
  | eip:publicIps:listTags | List | publicip \* | -   | vpc:publicipTags:get | -      |
     
  
 
#### URI
GET /v2.0/{project_id}/publicips/resource_instances/action
表1路径参数 
| 参数         | 是否必选 | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
|:---|:---|:---|:---|
| project_id | 是    | String | **参数解释：** 项目ID [参见获取项目ID](https://support.huaweicloud.com/api-eip/eip_api06_0004.html)。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 |
   
#### 请求参数
表2请求Body参数 
| 参数      | 是否必选 | 参数类型                                                                                         | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
|:---|:---|:---|:---|
| tags    | 否    | Array of [TagReq] objects     | **参数解释：** 标签对象，最多包含10个key。 **约束限制：** - 每个key下面的value最多10个，结构体不能缺失，key不能为空或者空字符串。   - Key不能重复，同一个key中values不能重复。   - 默认取值：不涉及。    **取值范围：** 不涉及。 **默认取值：** 不涉及。 |
| limit   | 否    | Integer                                                                                      | **参数解释：** 查询记录数（action为count时无此参数）如果action为filter默认为1000，limit最多为1000，不能为负数，最小值为1。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 最小值：**1** 最大值：**1000**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| offset  | 否    | Integer                                                                                      | **参数解释：** 索引位置，从offset指定的下一条数据开始查询。查询第一页数据时，不需要传入此参数，查询后续页码数据时，将查询前一页数据时响应体中的值带入此参数（action为count时无此参数）如果action为filter默认为0，必须为数字，不能为负数。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 最小值：**0**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| action  | 是    | String                                                                                       | **参数解释：** 操作标识（仅限于filter，count）：filter（过滤），count（查询总条数）。 如果是filter就是分页查询，如果是count只需按照条件将总条数返回即可。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| matches | 否    | Array of [MatchReq] objects | **参数解释：** 搜索字段，key为要匹配的字段，当前仅支持resource_name。value为匹配的值。此字段为固定字典值。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
   
 表3TagReq 
| 参数     | 是否必选 | 参数类型             | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
|:---|:---|:---|:---|
| key    | 是    | String           | **参数解释：** 键。最大长度128个unicode字符。 key不能为空。（搜索时不对此参数做校验）。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。                      |
| values | 是    | Array of strings | **参数解释：** 值列表。每个值最大长度255个unicode字符，如果values为空列表，则表示any_value。value之间为或的关系。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 |
   
 表4MatchReq 
| 参数    | 是否必选 | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
|:---|:---|:---|:---|
| key   | 是    | String | **参数解释：** 键。当前仅限定为resource_name。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 |
| value | 是    | String | **参数解释：** 值。当前仅限定为EIP地址。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。         |
   
#### 响应参数
**状态码：200**
表5响应Body参数 
| 参数          | 参数类型                                                                                                          | 描述                                                                                                                                                                                                                                     |
|:---|:---|:---|
| resources   | Array of [ListResourceResp] objects | **参数解释：** resource对象列表。 **取值范围：** 不涉及。 |
| total_count | Integer                                                                                                       | **参数解释：** 总记录数。 **取值范围：** 不涉及。         |
   
 表6ListResourceResp 
| 参数              | 参数类型                                                                                                                | 描述                                                                                                                                                                                                                                             |
|:---|:---|:---|
| resource_detail | Object                                                                                                              | **参数解释：** 资源详情。 资源对象，用于扩展。默认为空。 **取值范围：** 不涉及。 |
| resource_id     | String                                                                                                              | **参数解释：** 资源ID。 **取值范围：** 0-36个字符。             |
| resource_name   | String                                                                                                              | **参数解释：** 资源名称，没有默认为空字符串。 **取值范围：** 0-256个字符。  |
| tags            | Array of [ListResourceTagResp] objects | **参数解释：** 标签列表，没有标签默认为空数组。 **取值范围：** 不涉及。      |
   
 表7ListResourceTagResp 
| 参数    | 参数类型   | 描述                                                                                                                                                                                                                                                                                    |
|:---|:---|:---|
| key   | String | **参数解释：** 键。 **取值范围：** 最大长度128个unicode字符。 key不能为空。(搜索时不对此参数做校验)。                      |
| value | String | **参数解释：** 值列表。如果values为空列表，则表示any_value、value之间为或的关系。 **取值范围：** 每个值最大长度255个unicode字符。 |
   
#### 请求示例
- action为filter时请求体。
  ```
  {
    "offset" : 0,
    "limit" : 100,
    "action" : "filter",
    "matches" : [ {
      "key" : "resource_name",
      "value" : "resource1"
    } ],
    "tags" : [ {
      "key" : "key1",
      "values" : [ "value1", "value2" ]
    } ]
  }
  ```
  
- action为count时请求体。
  ```
  {
    "action" : "count",
    "tags" : [ {
      "key" : "key1",
      "values" : [ "value1", "value2" ]
    }, {
      "key" : "key2",
      "values" : [ "value1", "value2" ]
    } ],
    "matches" : [ {
      "key" : "resource_name",
      "value" : "resource1"
    } ]
  }
  ```
  
 
#### 响应示例
**状态码：200**
```
{
  "total_count" : 1000,
  "resources" : [ {
    "resource_detail" : null,
    "resource_id" : "cdfs_cefs_wesas_12_dsad",
    "resource_name" : "resouece1",
    "tags" : [ {
      "value" : "value1",
      "key" : "key1"
    }, {
      "value" : "value1",
      "key" : "key2"
    } ]
  } ]
}
```
#### SDK代码示例
SDK代码示例如下。
- [Java]
  - action为filter时请求体。
    ```
    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.eip.v2.region.EipRegion;
    import com.huaweicloud.sdk.eip.v2.*;
    import com.huaweicloud.sdk.eip.v2.model.*;
    import java.util.List;
    import java.util.ArrayList;
    public class ListPublicipsByTagsSolution {
        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);
            EipClient client = EipClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(EipRegion.valueOf("<YOUR REGION>"))
                    .build();
            ListPublicipsByTagsRequest request = new ListPublicipsByTagsRequest();
            ListPublicipsByTagsRequestBody body = new ListPublicipsByTagsRequestBody();
            List<MatchReq> listbodyMatches = new ArrayList<>();
            listbodyMatches.add(
                new MatchReq()
                    .withKey(MatchReq.KeyEnum.fromValue("resource_name"))
                    .withValue("resource1")
            );
            List<String> listTagsValues = new ArrayList<>();
            listTagsValues.add("value1");
            listTagsValues.add("value2");
            List<TagReq> listbodyTags = new ArrayList<>();
            listbodyTags.add(
                new TagReq()
                    .withKey("key1")
                    .withValues(listTagsValues)
            );
            body.withMatches(listbodyMatches);
            body.withAction(ListPublicipsByTagsRequestBody.ListPublicipsByTagsRequestBody.fromValue("filter"));
            body.withOffset(0);
            body.withLimit(100);
            body.withTags(listbodyTags);
            request.withBody(body);
            try {
                ListPublicipsByTagsResponse response = client.listPublicipsByTags(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());
            }
        }
    }
    ```
    
  
  - action为count时请求体。
    ```
    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.eip.v2.region.EipRegion;
    import com.huaweicloud.sdk.eip.v2.*;
    import com.huaweicloud.sdk.eip.v2.model.*;
    import java.util.List;
    import java.util.ArrayList;
    public class ListPublicipsByTagsSolution {
        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);
            EipClient client = EipClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(EipRegion.valueOf("<YOUR REGION>"))
                    .build();
            ListPublicipsByTagsRequest request = new ListPublicipsByTagsRequest();
            ListPublicipsByTagsRequestBody body = new ListPublicipsByTagsRequestBody();
            List<MatchReq> listbodyMatches = new ArrayList<>();
            listbodyMatches.add(
                new MatchReq()
                    .withKey(MatchReq.KeyEnum.fromValue("resource_name"))
                    .withValue("resource1")
            );
            List<String> listTagsValues = new ArrayList<>();
            listTagsValues.add("value1");
            listTagsValues.add("value2");
            List<String> listTagsValues1 = new ArrayList<>();
            listTagsValues1.add("value1");
            listTagsValues1.add("value2");
            List<TagReq> listbodyTags = new ArrayList<>();
            listbodyTags.add(
                new TagReq()
                    .withKey("key1")
                    .withValues(listTagsValues1)
            );
            listbodyTags.add(
                new TagReq()
                    .withKey("key2")
                    .withValues(listTagsValues)
            );
            body.withMatches(listbodyMatches);
            body.withAction(ListPublicipsByTagsRequestBody.ListPublicipsByTagsRequestBody.fromValue("count"));
            body.withTags(listbodyTags);
            request.withBody(body);
            try {
                ListPublicipsByTagsResponse response = client.listPublicipsByTags(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]
  - action为filter时请求体。
    ```
    # coding: utf-8
    import os
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkeip.v2.region.eip_region import EipRegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkeip.v2 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 = EipClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(EipRegion.value_of("<YOUR REGION>")) \
            .build()
        try:
            request = ListPublicipsByTagsRequest()
            listMatchesbody = [
                MatchReq(
                    key="resource_name",
                    value="resource1"
                )
            ]
            listValuesTags = [
                "value1",
                "value2"
            ]
            listTagsbody = [
                TagReq(
                    key="key1",
                    values=listValuesTags
                )
            ]
            request.body = ListPublicipsByTagsRequestBody(
                matches=listMatchesbody,
                action="filter",
                offset=0,
                limit=100,
                tags=listTagsbody
            )
            response = client.list_publicips_by_tags(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    ```
    
  
  - action为count时请求体。
    ```
    # coding: utf-8
    import os
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkeip.v2.region.eip_region import EipRegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkeip.v2 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 = EipClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(EipRegion.value_of("<YOUR REGION>")) \
            .build()
        try:
            request = ListPublicipsByTagsRequest()
            listMatchesbody = [
                MatchReq(
                    key="resource_name",
                    value="resource1"
                )
            ]
            listValuesTags = [
                "value1",
                "value2"
            ]
            listValuesTags1 = [
                "value1",
                "value2"
            ]
            listTagsbody = [
                TagReq(
                    key="key1",
                    values=listValuesTags1
                ),
                TagReq(
                    key="key2",
                    values=listValuesTags
                )
            ]
            request.body = ListPublicipsByTagsRequestBody(
                matches=listMatchesbody,
                action="count",
                tags=listTagsbody
            )
            response = client.list_publicips_by_tags(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]
  - action为filter时请求体。
    ```
    package main
    import (
    "fmt"
    "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        eip "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/eip/v2"
    "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/eip/v2/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/eip/v2/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 := eip.EipClientBuilder().
             WithRegion(region.ValueOf("<YOUR REGION>")).
             WithCredential(auth).
             SafeBuild()
        if err != nil {
            fmt.Println(err)
            return
        }
        client := eip.NewEipClient(hcClient)
        request := &model.ListPublicipsByTagsRequest{}
    var listMatchesbody = []model.MatchReq{
            {
                Key: model.GetMatchReqKeyEnum().RESOURCE_NAME,
                Value: "resource1",
            },
        }
    var listValuesTags = []string{
            "value1",
        "value2",
        }
    var listTagsbody = []model.TagReq{
            {
                Key: "key1",
                Values: listValuesTags,
            },
        }
    offsetListPublicipsByTagsRequestBody:= int32(0)
    limitListPublicipsByTagsRequestBody:= int32(100)
    request.Body = &model.ListPublicipsByTagsRequestBody{
    Matches: &listMatchesbody,
    Action: model.GetListPublicipsByTagsRequestBodyActionEnum().FILTER,
    Offset: &offsetListPublicipsByTagsRequestBody,
    Limit: &limitListPublicipsByTagsRequestBody,
    Tags: &listTagsbody,
    }
    response, err := client.ListPublicipsByTags(request)
    if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    ```
    
  
  - action为count时请求体。
    ```
    package main
    import (
    "fmt"
    "github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        eip "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/eip/v2"
    "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/eip/v2/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/eip/v2/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 := eip.EipClientBuilder().
             WithRegion(region.ValueOf("<YOUR REGION>")).
             WithCredential(auth).
             SafeBuild()
        if err != nil {
            fmt.Println(err)
            return
        }
        client := eip.NewEipClient(hcClient)
        request := &model.ListPublicipsByTagsRequest{}
    var listMatchesbody = []model.MatchReq{
            {
                Key: model.GetMatchReqKeyEnum().RESOURCE_NAME,
                Value: "resource1",
            },
        }
    var listValuesTags = []string{
            "value1",
        "value2",
        }
    var listValuesTags1 = []string{
            "value1",
        "value2",
        }
    var listTagsbody = []model.TagReq{
            {
                Key: "key1",
                Values: listValuesTags1,
            },
            {
                Key: "key2",
                Values: listValuesTags,
            },
        }
    request.Body = &model.ListPublicipsByTagsRequestBody{
    Matches: &listMatchesbody,
    Action: model.GetListPublicipsByTagsRequestBodyActionEnum().COUNT,
    Tags: &listTagsbody,
    }
    response, err := client.ListPublicipsByTags(request)
    if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    ```
    
   
- [更多]
  更多编程语言的SDK代码示例，请参见[API Explorer](https://console.huaweicloud.com/apiexplorer/#/openapi/EIP/sdk?api=ListPublicipsByTags&version=v2)的代码示例页签，可生成自动对应的SDK代码示例。
#### 状态码
| 状态码 | 描述        |
|:---|:---|
| 200 | GET操作正常返回 |
   
#### 错误码
请参见[错误码](https://support.huaweicloud.com/api-eip/ErrorCode.html)。
