UniApp Example

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 autoapi2. Initialize Configuration
bash
autoapi init -l uniappThis 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 generate4. 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
- Environment Configuration: Use different API endpoints for development, staging, and production
- Error Handling: Implement global error handling for consistent user experience
- Loading States: Show loading indicators during API calls
- Caching: Implement appropriate caching strategies for better performance
- Type Safety: Leverage TypeScript for better code quality and developer experience