API Reference
uni-app provides a rich set of API interfaces that allow developers to call various device functions and platform services. This section will detail the usage of various types of APIs.
API Categories
Basic APIs
Network Requests
uni.request()
- Make network requestsuni.uploadFile()
- Upload filesuni.downloadFile()
- Download filesuni.connectSocket()
- Create WebSocket connection
Data Storage
uni.setStorage()
- Asynchronously store datauni.setStorageSync()
- Synchronously store datauni.getStorage()
- Asynchronously get datauni.getStorageSync()
- Synchronously get datauni.removeStorage()
- Asynchronously remove datauni.clearStorage()
- Clear local data
Interface APIs
Interactive Feedback
uni.showToast()
- Show message toastuni.showLoading()
- Show loading dialoguni.hideLoading()
- Hide loading dialoguni.showModal()
- Show modal dialoguni.showActionSheet()
- Show action sheet
Navigation Bar
uni.setNavigationBarTitle()
- Set navigation bar titleuni.setNavigationBarColor()
- Set navigation bar coloruni.showNavigationBarLoading()
- Show navigation bar loading animationuni.hideNavigationBarLoading()
- Hide navigation bar loading animation
Background
uni.setBackgroundColor()
- Set window background coloruni.setBackgroundTextStyle()
- Set pull-down background text style
Routing APIs
Page Navigation
uni.navigateTo()
- Keep current page and navigate to a page within the appuni.redirectTo()
- Close current page and navigate to a page within the appuni.reLaunch()
- Close all pages and open a page within the appuni.switchTab()
- Jump to tabBar pageuni.navigateBack()
- Close current page and return to previous page
Device APIs
System Information
uni.getSystemInfo()
- Get system informationuni.getSystemInfoSync()
- Synchronously get system informationuni.canIUse()
- Check if APIs, callbacks, parameters, components are available in current version
Network Status
uni.getNetworkType()
- Get network typeuni.onNetworkStatusChange()
- Listen for network status changes
Accelerometer
uni.onAccelerometerChange()
- Listen for accelerometer datauni.startAccelerometer()
- Start listening for accelerometer datauni.stopAccelerometer()
- Stop listening for accelerometer data
Compass
uni.onCompassChange()
- Listen for compass datauni.startCompass()
- Start listening for compass datauni.stopCompass()
- Stop listening for compass data
Media APIs
Images
uni.chooseImage()
- Choose images from local album or take photos with camerauni.previewImage()
- Preview imagesuni.getImageInfo()
- Get image informationuni.saveImageToPhotosAlbum()
- Save image to system album
Recording
uni.startRecord()
- Start recordinguni.stopRecord()
- Stop recording
Audio Playback Control
uni.playVoice()
- Start playing voiceuni.pauseVoice()
- Pause playing voiceuni.stopVoice()
- Stop playing voice
Music Playback Control
uni.getBackgroundAudioManager()
- Get globally unique background audio manageruni.createAudioContext()
- Create and return audio context audioContext object
Video
uni.chooseVideo()
- Record video or choose video from phone albumuni.saveVideoToPhotosAlbum()
- Save video to system albumuni.createVideoContext()
- Create and return video context videoContext object
Location APIs
Get Location
uni.getLocation()
- Get current geographic location and speeduni.chooseLocation()
- Open map to choose location
View Location
uni.openLocation()
- View location using built-in map
File APIs
File Management
uni.saveFile()
- Save file locallyuni.getSavedFileList()
- Get list of locally saved filesuni.getSavedFileInfo()
- Get file information of local filesuni.removeSavedFile()
- Delete locally stored filesuni.openDocument()
- Open document in new page
Drawing APIs
Canvas
uni.createCanvasContext()
- Create canvas drawing contextuni.canvasToTempFilePath()
- Export specified area of current canvas to generate image of specified sizeuni.canvasGetImageData()
- Return array describing pixel data of canvas areauni.canvasPutImageData()
- Draw pixel data to canvas
Third-party Platform APIs
Login
uni.login()
- Call interface to get login credentialsuni.checkSession()
- Check if login status has expired
Authorization
uni.authorize()
- Request authorization from user in advanceuni.getSetting()
- Get user's current settings
User Information
uni.getUserInfo()
- Get user information
WeChat Payment
uni.requestPayment()
- Initiate WeChat payment
Template Messages
uni.addTemplate()
- Combine template and add to personal template libraryuni.deleteTemplate()
- Delete a template from accountuni.getTemplateLibraryById()
- Get keyword library for template title in template libraryuni.getTemplateLibraryList()
- Get list of mini program template library titlesuni.getTemplateList()
- Get list of existing templates in accountuni.sendTemplateMessage()
- Send template message
API Usage Examples
Network Request Examples
javascript
// Make GET request
uni.request({
url: 'https://api.example.com/data',
method: 'GET',
data: {
id: 1
},
success: (res) => {
console.log('Request successful', res.data)
},
fail: (err) => {
console.error('Request failed', err)
}
})
// Make POST request
uni.request({
url: 'https://api.example.com/submit',
method: 'POST',
data: {
name: 'John Doe',
age: 25
},
header: {
'Content-Type': 'application/json'
},
success: (res) => {
console.log('Submit successful', res.data)
}
})
Data Storage Examples
javascript
// Asynchronously store data
uni.setStorage({
key: 'userInfo',
data: {
name: 'John Doe',
age: 25
},
success: () => {
console.log('Storage successful')
}
})
// Synchronously store data
try {
uni.setStorageSync('token', 'abc123')
console.log('Storage successful')
} catch (e) {
console.error('Storage failed', e)
}
// Asynchronously get data
uni.getStorage({
key: 'userInfo',
success: (res) => {
console.log('Get successful', res.data)
}
})
// Synchronously get data
try {
const token = uni.getStorageSync('token')
console.log('Get successful', token)
} catch (e) {
console.error('Get failed', e)
}
Page Navigation Examples
javascript
// Navigate to new page
uni.navigateTo({
url: '/pages/detail/detail?id=123'
})
// Redirect to new page
uni.redirectTo({
url: '/pages/login/login'
})
// Go back to previous page
uni.navigateBack({
delta: 1
})
// Jump to tabBar page
uni.switchTab({
url: '/pages/index/index'
})
Interactive Feedback Examples
javascript
// Show toast
uni.showToast({
title: 'Operation successful',
icon: 'success',
duration: 2000
})
// Show loading
uni.showLoading({
title: 'Loading...'
})
// Hide loading
setTimeout(() => {
uni.hideLoading()
}, 2000)
// Show modal dialog
uni.showModal({
title: 'Prompt',
content: 'Are you sure you want to delete this record?',
success: (res) => {
if (res.confirm) {
console.log('User clicked confirm')
} else if (res.cancel) {
console.log('User clicked cancel')
}
}
})
System Information Examples
javascript
// Get system information
uni.getSystemInfo({
success: (res) => {
console.log('Device brand:', res.brand)
console.log('Device model:', res.model)
console.log('Operating system:', res.platform)
console.log('System version:', res.system)
console.log('Screen width:', res.screenWidth)
console.log('Screen height:', res.screenHeight)
}
})
// Synchronously get system information
try {
const res = uni.getSystemInfoSync()
console.log('System information:', res)
} catch (e) {
console.error('Failed to get system information', e)
}
Choose Image Examples
javascript
// Choose image
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
const tempFilePaths = res.tempFilePaths
console.log('Selected images:', tempFilePaths)
// Preview image
uni.previewImage({
urls: tempFilePaths
})
}
})
API Compatibility
Different platforms may have different levels of support for APIs. Please check the compatibility notes for specific APIs before use:
API Category | H5 | Mini Program | App |
---|---|---|---|
Network Requests | ✅ | ✅ | ✅ |
Data Storage | ✅ | ✅ | ✅ |
Interface Interaction | ✅ | ✅ | ✅ |
Route Navigation | ✅ | ✅ | ✅ |
Device Information | Partial | ✅ | ✅ |
Media Functions | Partial | ✅ | ✅ |
Location Services | Partial | ✅ | ✅ |
File Operations | Partial | ✅ | ✅ |
Third-party Platform | ❌ | ✅ | Partial |
Important Notes
- Asynchronous APIs: Most APIs are asynchronous and need to handle results through success, fail, and complete callback functions
- Synchronous APIs: Synchronous APIs usually end with Sync and will block the current thread, use with caution
- Platform Differences: Different platforms may have different support for APIs, pay attention to compatibility during development
- Permission Requests: Some APIs require user authorization before use, such as location, camera, microphone, etc.
- Error Handling: It's recommended to add error handling logic for each API call
Related Links
- Getting Started - Learn how to create and run uni-app projects
- Network Requests - Detailed guide on using network requests
- Data Storage - Learn best practices for local data storage
- FAQ - View common questions and solutions for API usage