API Request

Last Updated on : 2023-09-07 09:20:02download

During project development, if you need to request server-side APIs for data transmission, you can initiate a request to a custom service in the microapp. Tuya microapp provides custom servers and APIs (Mock) to help you speed up data transmission and API simulation. The API mock feature makes your microapp development much easier. You can simulate the data returned by the APIs by configuring a JSON file.

Customize a server

Perform the following steps to customize a server:

  1. Configure a custom server address in the debuggerConfig object under the micro.config.js file.

    debuggerConfig:{
    customApiUrl: 'hppt://localhost:8080'
    }
    
  2. Then, in the page code, you only need to make a request by using the method encapsulated in src/api/index.tx of the microapp. Example:

    import api from '../api';
    import { useEffect, useState } from "react";
    
    const Page = () => {
    const [dataSource, setDataSouce] = useState<never[]>([]);
    
    let initDataSource = () => {
        api.get('/custom-api/demo') // Custom API endpoint
        .then(res => setDataSouce(res.data))
        .catch(e => console.log(e));
    };
    
    useEffect(() => {
        initDataSource();
    }, []);
    
    return (
        <div>
            {dataSource}
        </div>
    );
    };
    
    export default Page;
    

Mock APIs

You can mock the APIs to accelerate your microapp development.

Follow these rules during mocking:

  • The data of mocking APIs is stored in the mock/index.json file.
  • Mocking data is enabled by default. You can edit the examples as needed. Make sure to put all APIs within the api field.
  • A microapp API must start with /custom-api/. The prefix works as an identifier, indicating that the request is sent to the custom server.
  • A parameter must be enclosed with ${}. For example, /custom-api/device-detail/${deviceId} indicates deviceId.
  • The res field is the response that an API returns on receiving a request.
  • Mocking data will not be bundled into your application.

Data format

The mocked data is in JSON format.

Field Type Remarks
mock boolean Specifies whether to enable mocking for all APIs.
api Api[] Stores all the mocked APIs.

API description

Field Type Remarks
path string The request path.
method HTTP request methods The HTTP request method.
res Object The return parameter. The data structure is user-defined. All the content in the res field is returned when you call the corresponding API.
mock boolean Specifies whether to enable mocking for this API.

Sample code

{
  "mock": true,
  "api": [
    {
      "path": "/custom-api/devices/${categoryId}",
      "method": "GET",
      "res": {
        "msg": "",
        "success": true,
        "data": [
          {
            "deviceID": "3342352342***",
            "deviceName": "devicename1"
          },
          {
            "deviceID": "1346456342***",
            "deviceName": "devicename2"
          },
          {
            "deviceID": "1342678742***",
            "deviceName": "devicename3"
          },
          {
            "deviceID": "1342352396***",
            "deviceName": "devicename4"
          },
          {
            "deviceID": "1342352966***",
            "deviceName": "devicename5"
          }
        ]
      },
      "mock": true
    }
  ]
}

Request the mocked APIs

Use the mocked JSON file above as the mock data, and get the device list based on the category ID.

Use in a component:

import { useEffect, useState } from "react";
import { Table } from 'antd';
import api from '../../api';

const DeviceList = () => {

  const [dataSource, setDataSouce] = useState<never[]>([]);

  const columns = [
    {
      title: 'Device ID',
      dataIndex: 'deviceID'
    },
    {
      title: 'Device Name',
      dataIndex: 'deviceName'
    }
  ]

  const getList = (categoryId: number) => {
    api
      .get(`/custom-api/devices/${categoryId}`)
      .then(res => {
        setDataSouce(res.data);
      })
      .catch(e => console.log(e));
  }

  useEffect(() => {
    getList(99);
  }, []);
  return <Table dataSource={dataSource} columns={columns} rowKey={`deviceID`}></Table>
}

export default DeviceList

Open the device list page to see the requested data. Check the dev-tools > Network panel on the browser, and you can see that a request with the path /custom-api/devices/99 is generated.

API Request

Backend service development

The requests for your microapp page are sent to your own backend services. The backend services work across programming languages and development frameworks. You can choose the preferred technology stack. Moreover, your backend services can also access Tuya’s OpenAPI and subscribe to messages. For more information, see the following documentation: