Redis 企业软件 REST API 快速入门

Redis 企业版软件 REST API 快速入门

Redis 企业版软件包含一个 REST API,允许您自动化某些任务。本文向您展示如何向 Redis 企业版软件 REST API 发送请求。

基础

无论您使用哪种方法发送API请求,都有一些常见的概念需要记住。

类型 描述
Authentication 使用Basic Auth与您的集群用户名(电子邮件)和密码
Ports 默认情况下,所有调用都通过端口9443进行
Versions 在请求URI中指定版本
Headers AcceptContent-Type 应为 application/json
响应类型和错误代码 响应为200 OK表示成功;否则,请求因错误而失败

欲了解更多信息,请参阅Redis Enterprise Software REST API

cURL 示例请求

cURL 是一个命令行工具,允许你从终端发送 HTTP 请求。

您可以使用以下选项来构建一个cURL请求:

选项 描述
-X 方法 (GET, PUT, PATCH, POST, 或 DELETE)
-H 请求头,可以多次指定
-u 用户名和密码信息
-d 用于PUT或POST请求的JSON数据
-F 用于PUT或POST请求的表单数据,例如用于POST /v1/modulesPOST /v2/modules端点的请求
-k 关闭SSL验证
-i 显示头部和状态码以及响应体

请参阅cURL文档以获取更多信息。

GET 请求

使用以下cURL命令通过GET /v1/bdbs/端点获取数据库列表。

$ curl -X GET -H "accept: application/json" \
              -u "[username]:[password]" \
              https://[host][:port]/v1/bdbs -k -i

HTTP/1.1 200 OK
server: envoy
date: Tue, 14 Jun 2022 19:24:30 GMT
content-type: application/json
content-length: 2833
cluster-state-id: 42
x-envoy-upstream-service-time: 25

[
    {
        ...
        "name": "tr01",
        ...
        "uid": 1,
        "version": "6.0.16",
        "wait_command": true
    }
]

在响应体中,uid 是数据库的ID。您可以使用数据库ID通过API查看或更新数据库。

有关GET /v1/bdbs/返回字段的更多信息,请参阅bdbs对象

PUT 请求

一旦你有了数据库ID,你可以使用PUT /v1/bdbs/来更新数据库的配置。

例如,您可以在发送请求时将数据库uid 1作为URL参数传递,并使用-d选项指定新的name。这将数据库的nametr01更改为database1

$ curl -X PUT -H "accept: application/json" \
            -H "content-type: application/json" \
            -u "cameron.bates@redis.com:test123" \
            https://[host]:[port]/v1/bdbs/1 \
            -d '{ "name": "database1" }' -k -i
HTTP/1.1 200 OK
server: envoy
date: Tue, 14 Jun 2022 20:00:25 GMT
content-type: application/json
content-length: 2933
cluster-state-id: 43
x-envoy-upstream-service-time: 159

{
    ...
    "name" : "database1",
    ...
    "uid" : 1,
    "version" : "6.0.16",
    "wait_command" : true
}

有关可以使用PUT /v1/bdbs/更新的字段的更多信息,请参阅bdbs对象

客户端示例

您也可以使用客户端库以您偏好的语言进行API请求。

要跟随这些示例,你需要:

Python

import json
import requests

# Required connection information - replace with your host, port, username, and password
host = "[host]"
port = "[port]"
username = "[username]"
password = "[password]"

# Get the list of databases using GET /v1/bdbs
bdbs_uri = "https://{}:{}/v1/bdbs".format(host, port)

print("GET {}".format(bdbs_uri))
get_resp = requests.get(bdbs_uri,
        auth = (username, password),
        headers = { "accept" : "application/json" },
        verify = False)

print("{} {}".format(get_resp.status_code, get_resp.reason))
for header in get_resp.headers.keys():
    print("{}: {}".format(header, get_resp.headers[header]))

print("\n" + json.dumps(get_resp.json(), indent=4))

# Rename all databases using PUT /v1/bdbs
for bdb in get_resp.json():
    uid = bdb["uid"] # Get the database ID from the JSON response

    put_uri = "{}/{}".format(bdbs_uri, uid)
    new_name = "database{}".format(uid)
    put_data = { "name" : new_name }

    print("PUT {} {}".format(put_uri, json.dumps(put_data)))

    put_resp = requests.put(put_uri,
        data = json.dumps(put_data),
        auth = (username, password),
        headers = { "content-type" : "application/json" },
        verify = False)

    print("{} {}".format(put_resp.status_code, put_resp.reason))
    for header in put_resp.headers.keys():
        print("{}: {}".format(header, put_resp.headers[header]))

    print("\n" + json.dumps(put_resp.json(), indent=4))

查看Python requests库文档以获取更多信息。

输出

$ python rs_api.py
python rs_api.py
GET https://[host]:[port]/v1/bdbs
InsecureRequestWarning: Unverified HTTPS request is being made to host '[host]'.
Adding certificate verification is strongly advised.
See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
200 OK
server: envoy
date: Wed, 15 Jun 2022 15:49:43 GMT
content-type: application/json
content-length: 2832
cluster-state-id: 89
x-envoy-upstream-service-time: 27

[
    {
        ...
        "name": "tr01",
        ...
        "uid": 1,
        "version": "6.0.16",
        "wait_command": true
    }
]

PUT https://[host]:[port]/v1/bdbs/1 {"name": "database1"}
InsecureRequestWarning: Unverified HTTPS request is being made to host '[host]'.
Adding certificate verification is strongly advised.
See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
200 OK
server: envoy
date: Wed, 15 Jun 2022 15:49:43 GMT
content-type: application/json
content-length: 2933
cluster-state-id: 90
x-envoy-upstream-service-time: 128

{
    ...
    "name" : "database1",
    ...
    "uid" : 1,
    "version" : "6.0.16",
    "wait_command" : true
}

node.js

import fetch, { Headers } from 'node-fetch';
import * as https from 'https';

const HOST = '[host]';
const PORT = '[port]';
const USERNAME = '[username]';
const PASSWORD = '[password]';

// Get the list of databases using GET /v1/bdbs
const BDBS_URI = `https://${HOST}:${PORT}/v1/bdbs`;
const USER_CREDENTIALS = Buffer.from(`${USERNAME}:${PASSWORD}`).toString('base64');
const AUTH_HEADER = `Basic ${USER_CREDENTIALS}`;

console.log(`GET ${BDBS_URI}`);

const HTTPS_AGENT = new https.Agent({
    rejectUnauthorized: false
});

const response = await fetch(BDBS_URI, {
    method: 'GET',
    headers: {
        'Accept': 'application/json',
        'Authorization': AUTH_HEADER
    },
    agent: HTTPS_AGENT
});

const responseObject = await response.json();
console.log(`${response.status}: ${response.statusText}`);
console.log(responseObject);

// Rename all databases using PUT /v1/bdbs
for (const database of responseObject) {
    const DATABASE_URI = `${BDBS_URI}/${database.uid}`;
    const new_name = `database${database.uid}`;

    console.log(`PUT ${DATABASE_URI}`);

    const response = await fetch(DATABASE_URI, {
        method: 'PUT',
        headers: {
            'Authorization': AUTH_HEADER,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            'name': new_name
        }),
        agent: HTTPS_AGENT
    });

    console.log(`${response.status}: ${response.statusText}`);
    console.log(await(response.json()));
}

查看node-fetch文档以获取更多信息。

输出

$ node rs_api.js
GET https://[host]:[port]/v1/bdbs
200: OK
[
    {
        ...
        "name": "tr01",
        ...
        "slave_ha" : false,
        ...
        "uid": 1,
        "version": "6.0.16",
        "wait_command": true
    }
]
PUT https://[host]:[port]/v1/bdbs/1
200: OK
{
    ...
    "name" : "tr01",
    ...
    "slave_ha" : true,
    ...
    "uid" : 1,
    "version" : "6.0.16",
    "wait_command" : true
}

更多信息

RATE THIS PAGE
Back to top ↑