Help Center/ Domain Name Service/ API Reference/ APIs/ Tag Management/ Querying Resources Using Tags
Updated on 2024-12-20 GMT+08:00

Querying Resources Using Tags

Function

This API is used to query resources using tags.

Calling Method

For details, see Calling APIs.

URI

POST /v2/{project_id}/{resource_type}/resource_instances/action

Table 1 Path Parameters

Parameter

Mandatory

Type

Description

project_id

Yes

String

Project ID

resource_type

Yes

String

Resource type. The value can be DNS-public_zone, DNS-private_zone, DNS-public_recordset, DNS-private_recordset, or DNS-ptr_record.

Request Parameters

Table 2 Request header parameters

Parameter

Mandatory

Type

Description

X-Auth-Token

Yes

String

User token. It can be obtained by calling an IAM API. The value of X-Subject-Token in the response header is the user token.

Table 3 Request body parameters

Parameter

Mandatory

Type

Description

tags

No

Array of tagValues objects

Tags that are included. The structure body is mandatory. A maximum of 10 tag keys are allowed in each query operation. The tag key cannot be left blank or set to the empty string. One tag key can have up to 10 tag values. Each tag key must be unique, and each tag value in a tag must be unique.

tags_any

No

Array of tagValues objects

Each tag contains a maximum of 10 keys, and each key contains a maximum of 10 values. The structure body cannot be missing, and the key cannot be left blank or set to an empty string. Each tag key must be unique, and each tag value in a tag must be unique.

not_tags

No

Array of tagValues objects

The structure body is mandatory. A maximum of 10 tag keys are allowed in each query operation. The tag key cannot be left blank or set to the empty string. One tag key can have up to 10 tag values. Each tag key must be unique, and each tag value in a tag must be unique.

not_tags_any

No

Array of tagValues objects

Each tag contains a maximum of 10 keys, and each key contains a maximum of 10 values. The structure body cannot be missing, and the key cannot be left blank or set to an empty string. Each tag key must be unique, and each tag value in a tag must be unique.

limit

No

Integer

Number of resources on each page. The value ranges from 1 to 1000. If action is set to filter, the default value 1000 is used. If action is set to count, this parameter does not exist.

offset

No

Integer

Start offset of pagination query. The query will start from the next resource of the offset value. The value ranges from 0 to 2147483647, and the default value is 0. This parameter is not required when data on the first page is queried. When you query resources on subsequent pages, set the value of offset to the location returned in the response body for the previous query. If action is set to filter, the default value is 0. The value must be a number and cannot be a negative number. If action is set to count, this parameter does not exist.

action

Yes

String

Operation to be performed.

Value options:

  • filter: Resources are queried in pages by filter condition.

  • count: The total number of resources is queried.

matches

No

Array of match objects

This parameter specifies the key-value pair to be matched in the query. If value is left blank, exact matching will work. Otherwise, fuzzy search will work.

Table 4 tagValues

Parameter

Mandatory

Type

Description

key

No

String

Tag key. A key can contain a maximum of 127 Unicode characters. key must be specified. (This parameter is not verified during search.)

values

No

Array of strings

Tag value. Each value can contain a maximum of 255 Unicode characters. The asterisk () is a reserved character. If the value starts with an asterisk (), fuzzy search is performed based on the value following the asterisk (*). If values is missing, any value is matched. All values of a tag key are in the OR relationship.

Table 5 match

Parameter

Mandatory

Type

Description

key

Yes

String

Tag key. The current value is resource_name.

value

No

String

Tag value. Each value can contain a maximum of 255 Unicode characters. The value cannot contain underscores (_) or percent signs (%).

Response Parameters

Status code: 200

Table 6 Response body parameters

Parameter

Type

Description

resources

Array of resourceItem objects

Resource tag list

total_count

Integer

List of tags added to a resource

Table 7 resourceItem

Parameter

Type

Description

resource_id

String

Resource ID

resource_detail

Object

Resource details. This field is reserved, and its value defaults to an empty string.

tags

Array of tag objects

Tag list. If there is no tag in the list, an empty array is returned.

resource_name

String

Resource name. If no resource name is matched, the value is left blank.

Table 8 tag

Parameter

Type

Description

key

String

Tag key. A key can contain up to 36 Unicode characters. It cannot be left blank. A tag value cannot contain special characters (=*<>,|/) or start or end with spaces.

value

String

Tag value. A tag value contains a maximum of 43 Unicode characters and can be left blank. A tag value cannot contain special characters (=*<>,|/) or start or end with spaces.

Example Requests

Querying resources by tag, with the start offset of pagination query set to 100, and the number of resources displayed on each page to 100

POST https://{endpoint}/v2/{project_id}/{resource_type}/resource_instances/action

{
  "offset" : "100",
  "limit" : "100",
  "action" : "filter",
  "matches" : [ {
    "key" : "resource_name",
    "value" : "resource1"
  } ],
  "not_tags" : [ {
    "key" : "key1",
    "values" : [ "*value1", "value2" ]
  } ],
  "tags" : [ {
    "key" : "key1",
    "values" : [ "*value1", "value2" ]
  } ],
  "tags_any" : [ {
    "key" : "key1",
    "values" : [ "value1", "value2" ]
  } ],
  "not_tags_any" : [ {
    "key" : "key1",
    "values" : [ "value1", "value2" ]
  } ]
}

Example Responses

Status code: 200

Response to the request for querying resources by tag

{
  "resources" : [ {
    "resource_detail" : null,
    "resource_id" : "cdfs_cefs_wesas_12_dsad",
    "resource_name" : "resouece1",
    "tags" : [ {
      "key" : "key1",
      "value" : "value1"
    }, {
      "key" : "key2",
      "value" : "value1"
    } ]
  } ],
  "total_count" : 1000
}

SDK Sample Code

The SDK sample code is as follows.

Querying resources by tag, with the start offset of pagination query set to 100, and the number of resources displayed on each page to 100

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
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.dns.v2.region.DnsRegion;
import com.huaweicloud.sdk.dns.v2.*;
import com.huaweicloud.sdk.dns.v2.model.*;

import java.util.List;
import java.util.ArrayList;

public class ListTagSolution {

    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);

        DnsClient client = DnsClient.newBuilder()
                .withCredential(auth)
                .withRegion(DnsRegion.valueOf("<YOUR REGION>"))
                .build();
        ListTagRequest request = new ListTagRequest();
        request.withResourceType("{resource_type}");
        ListTagReq body = new ListTagReq();
        List<Match> listbodyMatches = new ArrayList<>();
        listbodyMatches.add(
            new Match()
                .withKey("resource_name")
                .withValue("resource1")
        );
        List<String> listNotTagsAnyValues = new ArrayList<>();
        listNotTagsAnyValues.add("value1");
        listNotTagsAnyValues.add("value2");
        List<TagValues> listbodyNotTagsAny = new ArrayList<>();
        listbodyNotTagsAny.add(
            new TagValues()
                .withKey("key1")
                .withValues(listNotTagsAnyValues)
        );
        List<String> listNotTagsValues = new ArrayList<>();
        listNotTagsValues.add("*value1");
        listNotTagsValues.add("value2");
        List<TagValues> listbodyNotTags = new ArrayList<>();
        listbodyNotTags.add(
            new TagValues()
                .withKey("key1")
                .withValues(listNotTagsValues)
        );
        List<String> listTagsAnyValues = new ArrayList<>();
        listTagsAnyValues.add("value1");
        listTagsAnyValues.add("value2");
        List<TagValues> listbodyTagsAny = new ArrayList<>();
        listbodyTagsAny.add(
            new TagValues()
                .withKey("key1")
                .withValues(listTagsAnyValues)
        );
        List<String> listTagsValues = new ArrayList<>();
        listTagsValues.add("*value1");
        listTagsValues.add("value2");
        List<TagValues> listbodyTags = new ArrayList<>();
        listbodyTags.add(
            new TagValues()
                .withKey("key1")
                .withValues(listTagsValues)
        );
        body.withMatches(listbodyMatches);
        body.withAction("filter");
        body.withOffset(100);
        body.withLimit(100);
        body.withNotTagsAny(listbodyNotTagsAny);
        body.withNotTags(listbodyNotTags);
        body.withTagsAny(listbodyTagsAny);
        body.withTags(listbodyTags);
        request.withBody(body);
        try {
            ListTagResponse response = client.listTag(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());
        }
    }
}

Querying resources by tag, with the start offset of pagination query set to 100, and the number of resources displayed on each page to 100

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# coding: utf-8

import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkdns.v2.region.dns_region import DnsRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkdns.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 = DnsClient.new_builder() \
        .with_credentials(credentials) \
        .with_region(DnsRegion.value_of("<YOUR REGION>")) \
        .build()

    try:
        request = ListTagRequest()
        request.resource_type = "{resource_type}"
        listMatchesbody = [
            Match(
                key="resource_name",
                value="resource1"
            )
        ]
        listValuesNotTagsAny = [
            "value1",
            "value2"
        ]
        listNotTagsAnybody = [
            TagValues(
                key="key1",
                values=listValuesNotTagsAny
            )
        ]
        listValuesNotTags = [
            "*value1",
            "value2"
        ]
        listNotTagsbody = [
            TagValues(
                key="key1",
                values=listValuesNotTags
            )
        ]
        listValuesTagsAny = [
            "value1",
            "value2"
        ]
        listTagsAnybody = [
            TagValues(
                key="key1",
                values=listValuesTagsAny
            )
        ]
        listValuesTags = [
            "*value1",
            "value2"
        ]
        listTagsbody = [
            TagValues(
                key="key1",
                values=listValuesTags
            )
        ]
        request.body = ListTagReq(
            matches=listMatchesbody,
            action="filter",
            offset=100,
            limit=100,
            not_tags_any=listNotTagsAnybody,
            not_tags=listNotTagsbody,
            tags_any=listTagsAnybody,
            tags=listTagsbody
        )
        response = client.list_tag(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

Querying resources by tag, with the start offset of pagination query set to 100, and the number of resources displayed on each page to 100

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
package main

import (
	"fmt"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
    dns "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dns/v2"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dns/v2/model"
    region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dns/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 := basic.NewCredentialsBuilder().
        WithAk(ak).
        WithSk(sk).
        WithProjectId(projectId).
        Build()

    client := dns.NewDnsClient(
        dns.DnsClientBuilder().
            WithRegion(region.ValueOf("<YOUR REGION>")).
            WithCredential(auth).
            Build())

    request := &model.ListTagRequest{}
	request.ResourceType = "{resource_type}"
	valueMatches:= "resource1"
	var listMatchesbody = []model.Match{
        {
            Key: "resource_name",
            Value: &valueMatches,
        },
    }
	var listValuesNotTagsAny = []string{
        "value1",
	    "value2",
    }
	keyNotTagsAny:= "key1"
	var listNotTagsAnybody = []model.TagValues{
        {
            Key: &keyNotTagsAny,
            Values: &listValuesNotTagsAny,
        },
    }
	var listValuesNotTags = []string{
        "*value1",
	    "value2",
    }
	keyNotTags:= "key1"
	var listNotTagsbody = []model.TagValues{
        {
            Key: &keyNotTags,
            Values: &listValuesNotTags,
        },
    }
	var listValuesTagsAny = []string{
        "value1",
	    "value2",
    }
	keyTagsAny:= "key1"
	var listTagsAnybody = []model.TagValues{
        {
            Key: &keyTagsAny,
            Values: &listValuesTagsAny,
        },
    }
	var listValuesTags = []string{
        "*value1",
	    "value2",
    }
	keyTags:= "key1"
	var listTagsbody = []model.TagValues{
        {
            Key: &keyTags,
            Values: &listValuesTags,
        },
    }
	offsetListTagReq:= int32(100)
	limitListTagReq:= int32(100)
	request.Body = &model.ListTagReq{
		Matches: &listMatchesbody,
		Action: "filter",
		Offset: &offsetListTagReq,
		Limit: &limitListTagReq,
		NotTagsAny: &listNotTagsAnybody,
		NotTags: &listNotTagsbody,
		TagsAny: &listTagsAnybody,
		Tags: &listTagsbody,
	}
	response, err := client.ListTag(request)
	if err == nil {
        fmt.Printf("%+v\n", response)
    } else {
        fmt.Println(err)
    }
}

For SDK sample code of more programming languages, see the Sample Code tab in API Explorer. SDK sample code can be automatically generated.

Status Codes

Status Code

Description

200

Response to the request for querying resources by tag

Error Codes

See Error Codes.