Skip to content

UniApp Example

Demo WebsiteGitHub Source Code

Overview

This example demonstrates how to integrate ApiSorcery with UniApp projects. UniApp is a cross-platform framework that allows you to write once and deploy to multiple platforms including iOS, Android, Web, and various mini-programs.

Features

  • Cross-platform compatibility: Works seamlessly across all UniApp supported platforms
  • TypeScript support: Full TypeScript integration for better development experience
  • Auto-generated API clients: Generate type-safe API clients from Swagger/OpenAPI specifications
  • Request/Response interceptors: Built-in support for request and response handling
  • Error handling: Comprehensive error handling with proper error types

Quick Setup

1. Install ApiSorcery

bash
npm install -g autoapi

2. Initialize Configuration

bash
autoapi init -l uniapp

This creates a .autoapirc.json configuration file:

json
{
  "application": {
    "language": "uniapp",
    "outputDir": "./src/api/auto"
  },
  "services": [
    {
      "code": "demo",
      "token": "72735b33815c4e5c9c2a924a8f4907ef",
      "version": 3,
      "enabled": true,
      "source": "https://your-api.com/swagger.json"
    }
  ]
}

3. Generate API Client

bash
autoapi generate

4. Use in UniApp

typescript
import * as ApiUser from '@/apis/auto/demo/ApiUser.ts';

// In your page or component
export default {
  data() {
    return {
      users: [],
    };
  },
  async onLoad() {
    try {
      const res = await ApiUser.getUserPaged({
        pagination: {
          page: 1,
          limit: 10,
        },
      });
      this.users = res.results || [];
    } catch (error) {
      console.error('Failed to fetch users:', error);
    }
  },
};

Platform-specific Considerations

Mini-programs

When targeting mini-programs (WeChat, Alipay, etc.), ensure your API endpoints are added to the whitelist in the respective platform's configuration.

H5/Web

For H5 deployment, configure CORS properly on your backend server to allow cross-origin requests.

App (iOS/Android)

Native app builds work out of the box with no additional configuration needed.

Best Practices

  1. Environment Configuration: Use different API endpoints for development, staging, and production
  2. Error Handling: Implement global error handling for consistent user experience
  3. Loading States: Show loading indicators during API calls
  4. Caching: Implement appropriate caching strategies for better performance
  5. Type Safety: Leverage TypeScript for better code quality and developer experience