首页 > 其他分享 >使用 typed-rest-client 进行 REST API 调用

使用 typed-rest-client 进行 REST API 调用

时间:2024-09-23 20:49:03浏览次数:3  
标签:console name typed REST API kongxx password email log

typed-rest-client 是一个用于 Node.js 的库,它提供了一种类型安全的方式来与 RESTful API 进行交互。其主要功能包括:

安装 typed-rest-client

要使用 typed-rest-client,首先需要安装它,可以通过 npm 来安装:

$ npm install typed-rest-client

使用 typed-rest-client

这里假定有个 express 的 server 提供了两个 REST API,一个是获取用户列表,一个是获取用户信息。

index.ts

import express, { Express, Request, Response } from "express";

const app: Express = express();
const port = process.env.PORT || 3000;

app.get("/", (req: Request, res: Response) => {
    res.send("Express + TypeScript Server");
});

app.get("/users", (req: Request, res: Response) => {
    const users = [
        {
            name: 'kongxx',
            password: 'password',
            email: '[email protected]'
        },
        {
            name: 'Mandy',
            password: 'password',
            email: '[email protected]'
        }
    ]
    res.json(users);
});

app.get("/users/:id", (req: Request, res: Response) => {
    const user = {
        name: 'kongxx',
        password: 'password',
        email: '[email protected]'
    }
    res.json(user);
});

app.listen(port, () => {
    console.log(`[server]: Server is running at http://localhost:${port}`);
});

下面是测试程序

test.ts

import {RestClient, IRestResponse} from 'typed-rest-client/RestClient';

interface User {
    name: string;
    password: string;
    email: string;
}

async function test() {
    const rc: RestClient = new RestClient('test', 'http://localhost:3000');

    const resUsers: IRestResponse<User[]> = await rc.get<User[]>('/users');
    console.log('get users ...');
    console.log('response: ', resUsers);
    console.log('statusCode: ', resUsers.statusCode);
    console.log('name: ', resUsers.result[0]?.name);
    console.log('email: ', resUsers.result[0]?.email);

    const resUser: IRestResponse<User> = await rc.get<User>('/users/1');
    console.log('get user ...');
    console.log('response: ', resUser);
    console.log('statusCode: ', resUser.statusCode);
    console.log('name: ', resUser.result?.name);
    console.log('email: ', resUser.result?.email);
}

test();
  • 这里首先定义了一个 interface,描述了 REST API 返回使用的数据结构。
  • 调用 RestClientget 方法,传入 URL 和返回的数据类型,返回一个 IRestResponse 对象,IRestResponse 对象包含了 HTTP 响应的状态码、响应头和响应体。
  • 通过 statusCode 属性可以获取到 HTTP 响应的状态码。
  • 通过 headers 属性可以获取到 HTTP 响应头。
  • 通过 result 属性可以获取到响应体中的数据。

测试

首先启动express server。

$ npm run dev

运行测试程序

$ npm install -g typescript
$ tsc src/test.ts  && node src/test.js

get users ...
response:  {
  statusCode: 200,
  result: [
    {
      name: 'kongxx',
      password: 'password',
      email: '[email protected]'
    },
    {
      name: 'Mandy',
      password: 'password',
      email: '[email protected]'
    }
  ],
  headers: {
    'x-powered-by': 'Express',
    'content-type': 'application/json; charset=utf-8',
    'content-length': '137',
    etag: 'W/"89-50ejbxheoPkdk58Nm75VjrVs3YE"',
    date: 'Mon, 23 Sep 2024 01:01:04 GMT',
    connection: 'close'
  }
}
statusCode:  200
name:  kongxx
email:  [email protected]

get user ...
response:  {
  statusCode: 200,
  result: { name: 'kongxx', password: 'password', email: '[email protected]' },
  headers: {
    'x-powered-by': 'Express',
    'content-type': 'application/json; charset=utf-8',
    'content-length': '68',
    etag: 'W/"44-WML8FV1wUhoW//8kQuCB8B/FWaQ"',
    date: 'Mon, 23 Sep 2024 01:01:04 GMT',
    connection: 'close'
  }
}
statusCode:  200
name:  kongxx
email:  [email protected]

标签:console,name,typed,REST,API,kongxx,password,email,log
From: https://blog.csdn.net/kongxx/article/details/142468429

相关文章

  • 如何利用 Pronouncing API 创作押韵诗词与歌词
    PronouncingAPI是一个用于音标化单词和生成押韵词的API,常用于语言处理和文本生成任务,尤其是诗歌和歌词创作中。它基于CMUPronouncingDictionary,这是一种广泛使用的英语发音词典。以下是它的主要功能和使用方法:1.获取单词发音PronouncingAPI可以通过提供单词,返回其音标表示......
  • InvalidDataAccessApiUsageException 和 Write operations are not allowed in read-o
    InvalidDataAccessApiUsageException和Writeoperationsarenotallowedinread-onlymode解决方法2016年04月07日12:35:02阅读数:14221这些天写webservice,一直在测接口,get方法都没问题,就从昨晚开始测save方法的时候出现了这个错误Writeoperationsarenotallo......
  • 【Web APIs day02 事件绑定处理和事件对象、网页交互】
    WebAPIs-第二天笔记掌握事件绑定处理和事件对象,完成常见网页交互事件监听事件类型事件对象拓展知识综合案例事件监听以前写的代码都是自动执行的,我们希望一段代码在某个特定的时机才去执行,比如点击按钮可以弹出警示框比如鼠标经过显示下拉菜单等等事件事件是程......
  • Capital许可使用数据分析工具
    在数字化浪潮中,软件已成为企业运营的核心。然而,随着软件种类和数量的激增,如何有效管理、分析和优化软件许可使用,已成为众多企业面临的难题。Capital许可使用数据分析工具,作为一款领先的软件资产管理解决方案,正是为解决这一问题而生。一、Capital许可使用数据分析工具的核心价值C......
  • asp.net core webapi 将两个对象/两个类合并到一起返回给前端
    举例:A,B类publicclassA{publicintid{get;set;}publicstringname{get;set;}publicstringphone{get;set;}}publicclassB{publicintage{get;set;}publicstringsex{get;set;}}publicclassAB{publicAa{get;set;}public......
  • 如何免费调用有道翻译API实现多语言翻译
    前言在全球化的今天,多语言翻译变得越来越重要。无论是个人学习、跨国企业沟通,还是国际学术交流,语言障碍都是一个不可忽视的问题。有道翻译API作为一款免费的翻译工具,提供了便捷的多语言翻译服务。本篇文章将详细介绍如何免费调用有道翻译API,实现多语言翻译。通过阅读本文,您将......
  • 通过openAI的Chat Completions API实现一个支持追问的ChatGPT功能集成
    文章目录前言准备工作代码实现思路完整代码实现备注前言  本文介绍如何通过openAI的ChatCompletionsAPI实现一个支持追问的后台功能,追问打个比方,就是当你问了一句”窗前明月光的下一句是什么?“之后,想再往下问就可以直接问”下一句呢?“,模型也能基......
  • 解读/proc/interrupts中的IR-IO-APIC和fasteoi
    IR-IO-APIC 和 FastEOI 都与中断管理相关,但它们在中断处理流程中的角色和功能有所不同。以下是对这两者的详细解释及其关系:1.IR-IO-APIC(输入/输出高级可编程中断控制器)定义与功能:IO-APIC 是一种用于管理和路由来自各种I/O设备(如键盘、鼠标、网络接口卡、磁盘控制器等)的......
  • 多语言文本 AI 情感分析 API 数据接口
    多语言文本AI情感分析API数据接口AI/文本处理AI模型快速分析文本情感倾向多语言文本/情感分析。1.产品功能支持多语言文本情感分析;基于特定AI模型,快速识别文本情感倾向;适用于评论分析、舆情监控等场景;全接口支持HTTPS(TLSv1.0/v1.1/v1.2/v1.3);全面兼......
  • 多语言文本 AI 纠错格式化 API 数据接口
    多语言文本AI纠错格式化API数据接口AI/文本处理AI模型智能纠正语法纠错/文本格式化。1.产品功能支持多语言文本的语法纠错;自动识别并纠正拼写错误、语法错误和标点符号使用不当;优化文本格式,提高可读性;基于AI模型,持续学习和更新,提高纠错准确率;适用于文档校对......