

2slides API Tutorial - Complete Guide to AI Presentation Generation
Welcome to the comprehensive guide for the 2slides API! This tutorial will walk you through everything you need to know to integrate AI-powered presentation generation into your applications.
Overview
The 2slides API allows you to generate professional presentations programmatically using AI. With support for multiple presentation types including timelines, roadmaps, mind maps, and more, you can create stunning slides from simple text input.
Key Features
- AI-Powered Generation: Automatically create professional presentations from text
- Multiple Template Types: Support for timelines, roadmaps, mind maps, pitch decks, infographics and more
- Multi-language Support: Generate content in multiple languages
- Rich Template Library: Access to hundreds of professionally designed templates
- Custom Templates: Upload and use your own custom slide templates
- Search templates: Search template via name, keywords and tags
- Download Options: Get presentations in PowerPoint (.pptx) format
- Real-time Status Tracking: Monitor generation progress with job status endpoints
Featured Presentation Types
All presentation templates are available here: 2slides Templates. Specifically, there are some featured presentation types that works very well for specific purpose and scenario.
- Timeline Slides - Perfect for project timelines and historical events
- Roadmap Slides - Ideal for product roadmaps and project planning
- Mind Map Slides - Great for concept mapping and knowledge structure
Getting Started
Base URL
All API requests should be made to:
https://www.2slides.com
Prerequisites
- Account Setup: Create an account at 2slides.com
- API Key: Generate an API key from your API management page
- Credits: Ensure you have sufficient credits for slide generation (10 credits per slide page)
Quick Start
- Get your API key from the API management page
- Search for a theme using the themes search endpoint, or browse the templates to get the slide theme id
- Generate slides with your content and selected theme id, this is an asynchronous call with job id returned
- Check job status until completion, the generated slides download URL will be provided
- Download your presentation using the provided download URL
Authentication
All API endpoints require authentication using an API key. You can manage your API keys through the API management interface.
API Key Format
API keys follow this format:
sk-2slides-{64-character-hex-string}
Authentication Methods
Authorization Header
Authorization: Bearer sk-2slides-your-api-key-here
API Key Management
- Maximum Keys: Each user can create up to 10 API keys
- Key Naming: Give your keys descriptive names for easy identification
- Security: Keep your API keys secure and never share them publicly
- Rotation: Regularly rotate your API keys for enhanced security
⚠️ Important Security Notice: 2slides platform does NOT store your API keys in plaintext for security reasons. Once generated, you must copy and securely store your API key immediately. If you lose your API key, you will need to generate a new one as the original cannot be recovered.
API Endpoints
1. Generate Slides
Generate slides from text input using a specific theme.
Endpoint: POST /api/v1/slides/generate
Headers:
Authorization: Bearer sk-2slides-your-api-key-here
Content-Type: application/json
Request Body:
{
"userInput": "Your presentation content here...",
"themeId": "theme-uuid-here",
"responseLanguage": "Auto"
}
Parameters:
userInput
(required): The content you want to generate slides forthemeId
(required): ID of the theme to use for slides generation. This can be:- Public themes from the templates gallery
- Your own custom uploaded themes (accessible through your account)
responseLanguage
(optional): Language for the generated slides. Use "Auto" for automatic detection
Available Languages:
Auto
- Auto detect language from input (default)English
- EnglishSimplified Chinese
- 简体中文Traditional Chinese
- 繁體中文Spanish
- EspañolArabic
- العربيةPortuguese
- PortuguêsIndonesian
- Bahasa IndonesiaJapanese
- 日本語Russian
- РусскийHindi
- हिंदीFrench
- FrançaisGerman
- DeutschVietnamese
- Tiếng ViệtTurkish
- TürkçePolish
- PolskiItalian
- ItalianoKorean
- 한국어
Response:
{
"success": true,
"data": {
"jobId": "job-uuid-here",
"status": "processing",
"message": "Slides generation started. Use the jobId to check status.",
"credits": {
"current": 150,
"required": 30
}
}
}
2. Check Job Status
Check the status of a slides generation job and get results when complete.
Endpoint: GET /api/v1/jobs/{jobId}
Headers:
Authorization: Bearer sk-2slides-your-api-key-here
Response Examples:
Processing:
{
"success": true,
"data": {
"jobId": "job-uuid-here",
"status": "processing",
"message": "Slides generation in progress",
"createdAt": 1703123456789,
"updatedAt": 1703123460000
}
}
Success:
{
"success": true,
"data": {
"jobId": "job-uuid-here",
"status": "success",
"message": "Slides generated successfully",
"downloadUrl": "https://presigned-url-here",
"createdAt": 1703123456789,
"updatedAt": 1703123500000,
"duration": 33211,
"slidePageCount": 3
}
}
Failed:
{
"success": true,
"data": {
"jobId": "job-uuid-here",
"status": "failed",
"message": "Slides generation failed",
"errorMessage": "Insufficient credits for generation",
"createdAt": 1703123456789,
"updatedAt": 1703123460000
}
}
3. Search Themes
Search for available slide themes by keyword. This includes both public themes and your own custom uploaded themes.
Endpoint: GET /api/v1/themes/search
Headers:
Authorization: Bearer sk-2slides-your-api-key-here
Query Parameters:
query
(required): Keyword to search in theme name, description, and tagslimit
(optional): Maximum number of results (1-100, default 20)
Example Request:
GET /api/v1/themes/search?query=timeline&limit=10
Response:
{
"success": true,
"data": {
"total": 25,
"themes": [
{
"id": "theme-uuid-1",
"name": "Modern Timeline",
"description": "Clean and modern timeline template for project presentations",
"tags": "timeline, modern, project, clean"
},
{
"id": "theme-uuid-2",
"name": "Business Roadmap",
"description": "Professional roadmap template for business planning",
"tags": "roadmap, business, planning, professional"
}
]
}
}
Rate Limiting
The API implements rate limiting to ensure fair usage and system stability. Different endpoints have different rate limits:
Endpoint | Time Window | Max Requests | Description |
---|---|---|---|
/api/v1/slides/generate | 1 minute | 6 requests | Core generation endpoint |
/api/v1/jobs | 1 minute | 10 requests | Job status checking |
/api/v1/themes/search | 1 minute | 30 requests | Theme search |
Rate Limit Headers
When rate limits are exceeded, the API returns a 429 Too Many Requests
response with these headers:
HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 6
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1703123600
Retry-After: 45
Handling Rate Limits
You need to handle the API call rate limit carefully, here is an example in Javascript.
async function makeApiRequest(url, options) {
try {
const response = await fetch(url, options);
if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After');
console.log(`Rate limited. Retry after ${retryAfter} seconds`);
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
return makeApiRequest(url, options); // Retry
}
return response;
} catch (error) {
console.error('API request failed:', error);
throw error;
}
}
Credit System
2slides uses a credit-based system for slide generation. Each slide page costs 10 credits.
Credit Rules
- New Users: Receive 100 free credits upon registration
- Cost: 10 credits per slide page generated
- Minimum: Users need at least 10 credits to start generation
- Deduction: Credits are deducted only after successful generation
- Refunds: Credits are refunded if generation fails
Checking Credits
You can check your credit balance through the account dashboard or by examining the credit information in API responses.
Purchasing Credits
Additional credits can be purchased through the pricing page using various payment methods.
Examples
Complete Workflow Example
Here's a complete example of generating slides using the 2slides API in Javascript and Python:
const API_KEY = 'sk-2slides-your-api-key-here';
const BASE_URL = 'https://www.2slides.com';
async function generateSlides() {
try {
// Step 1: Search for a theme
const themeResponse = await fetch(
`${BASE_URL}/api/v1/themes/search?query=timeline&limit=5`,
{
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
}
}
);
const themeData = await themeResponse.json();
const themeId = themeData.data.themes[0].id;
// Step 2: Generate slides
const generateResponse = await fetch(
`${BASE_URL}/api/v1/slides/generate`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
userInput: "Create a timeline for our product development: Q1 - Research and planning, Q2 - MVP development, Q3 - Beta testing, Q4 - Public launch",
themeId: themeId,
responseLanguage: "English"
})
}
);
const generateData = await generateResponse.json();
const jobId = generateData.data.jobId;
// Step 3: Poll for completion
let jobStatus;
do {
await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds
const statusResponse = await fetch(
`${BASE_URL}/api/v1/jobs/${jobId}`,
{
headers: {
'Authorization': `Bearer ${API_KEY}`
}
}
);
jobStatus = await statusResponse.json();
console.log(`Status: ${jobStatus.data.status}`);
} while (jobStatus.data.status === 'processing' || jobStatus.data.status === 'pending');
// Step 4: Handle result
if (jobStatus.data.status === 'success') {
console.log('Slides generated successfully!');
console.log('Download URL:', jobStatus.data.downloadUrl);
console.log('Pages generated:', jobStatus.data.slidePageCount);
// Download the file
const downloadResponse = await fetch(jobStatus.data.downloadUrl);
const blob = await downloadResponse.blob();
// Create download link
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'presentation.pptx';
a.click();
window.URL.revokeObjectURL(url);
} else {
console.error('Generation failed:', jobStatus.data.errorMessage);
}
} catch (error) {
console.error('Error:', error);
}
}
// Run the example
generateSlides();
Python Example
import requests
import time
import json
API_KEY = 'sk-2slides-your-api-key-here'
BASE_URL = 'https://www.2slides.com'
def generate_slides():
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
try:
# Step 1: Search for a theme
theme_response = requests.get(
f'{BASE_URL}/api/v1/themes/search',
params={'query': 'roadmap', 'limit': 5},
headers=headers
)
theme_data = theme_response.json()
theme_id = theme_data['data']['themes'][0]['id']
# Step 2: Generate slides
generate_payload = {
'userInput': 'Create a product roadmap for our mobile app: Phase 1 - Core features, Phase 2 - Advanced features, Phase 3 - AI integration',
'themeId': theme_id,
'responseLanguage': 'English'
}
generate_response = requests.post(
f'{BASE_URL}/api/v1/slides/generate',
headers=headers,
json=generate_payload
)
generate_data = generate_response.json()
job_id = generate_data['data']['jobId']
# Step 3: Poll for completion
while True:
time.sleep(2) # Wait 2 seconds
status_response = requests.get(
f'{BASE_URL}/api/v1/jobs/{job_id}',
headers=headers
)
status_data = status_response.json()
status = status_data['data']['status']
print(f'Status: {status}')
if status in ['success', 'failed']:
break
# Step 4: Handle result
if status == 'success':
print('Slides generated successfully!')
print(f'Download URL: {status_data["data"]["downloadUrl"]}')
print(f'Pages generated: {status_data["data"]["slidePageCount"]}')
# Download the file
download_response = requests.get(status_data['data']['downloadUrl'])
with open('presentation.pptx', 'wb') as f:
f.write(download_response.content)
print('File downloaded as presentation.pptx')
else:
print(f'Generation failed: {status_data["data"]["errorMessage"]}')
except Exception as error:
print(f'Error: {error}')
# Run the example
generate_slides()
cURL Examples
Search for themes:
curl -X GET ,[object Object], \
-H ,[object Object], \
-H ,[object Object],
Generate slides:
curl -X POST ,[object Object], \
-H ,[object Object], \
-H ,[object Object], \
-d ,[object Object],
Check job status:
curl -X GET ,[object Object], \
-H ,[object Object],
Error Handling
The API uses standard HTTP status codes and returns detailed error information in JSON format.
Common Error Responses
400 Bad Request:
{
"success": false,
"error": "userInput is required and must be a non-empty string"
}
401 Unauthorized:
{
"success": false,
"error": "Authentication required"
}
403 Forbidden:
{
"success": false,
"error": "Access denied"
}
404 Not Found:
{
"success": false,
"error": "Theme not found"
}
429 Too Many Requests:
{
"success": false,
"error": "Rate limit exceeded"
}
500 Internal Server Error:
{
"success": false,
"error": "Internal server error"
}
Error Handling Best Practices
async function handleApiRequest(url, options) {
try {
const response = await fetch(url, options);
const data = await response.json();
if (!response.ok) {
switch (response.status) {
case 400:
throw new Error(`Bad Request: ${data.error}`);
case 401:
throw new Error('Authentication failed. Please check your API key.');
case 403:
throw new Error('Access denied. You may not have permission for this resource.');
case 404:
throw new Error('Resource not found.');
case 429:
throw new Error('Rate limit exceeded. Please try again later.');
case 500:
throw new Error('Server error. Please try again later.');
default:
throw new Error(`API Error: ${data.error || 'Unknown error'}`);
}
}
return data;
} catch (error) {
if (error.name === 'TypeError' && error.message.includes('fetch')) {
throw new Error('Network error. Please check your internet connection.');
}
throw error;
}
}
Best Practices
1. API Key Security
- Never expose API keys in client-side code or public repositories
- Use environment variables to store API keys securely
- Rotate keys regularly for enhanced security
- Monitor key usage through the API management dashboard
- Store keys securely: Remember that 2slides does not store your API keys, so you must keep them safe
- Backup your keys: Store API keys in a secure password manager or encrypted storage
2. Efficient API Usage
- Cache theme search results to avoid repeated requests
- Implement proper polling intervals for job status checks (2-5 seconds)
- Handle rate limits gracefully with exponential backoff
- Batch operations when possible to reduce API calls
3. Error Handling
- Always check response status codes
- Implement retry logic for transient failures
- Log errors appropriately for debugging
- Provide user-friendly error messages
4. Performance Optimization
- Use appropriate polling intervals to avoid unnecessary requests
- Implement request timeouts to prevent hanging requests
- Cache frequently used data like theme information
- Monitor your credit usage to avoid unexpected charges
5. Content Guidelines
- Provide clear, structured input for better slide generation
- Use appropriate themes for your content type
- Specify language when needed for international content
- Keep content concise for optimal slide layout
Support & Resources
Documentation & Resources
- API Documentation - Interactive API documentation and playground
- Templates Gallery - Browse available slide templates
- Pricing Information - Credit packages and pricing
- Blog - Latest updates and tips
Getting Help
- API Playground: Test your API calls directly in the browser at 2slides.com/api
- Account Dashboard: Manage your credit usage at 2slides.com/account
- Support: Contact support through the main website
Community & Updates
- Feature Updates: Stay updated with new features and improvements
- Template Library: Regular additions of new professional templates
- API Enhancements: Continuous improvements to API performance and features
Conclusion
The 2slides API provides a powerful and flexible way to generate professional presentations programmatically. With its comprehensive feature set, robust error handling, and extensive template library, you can integrate AI-powered slide generation into any application or workflow.
Start building amazing presentations today with the 2slides API! Visit 2slides.com/api to get your API key and begin creating.
About 2Slides
Create stunning AI-powered presentations in seconds. Transform your ideas into professional slides with 2slides AI Agent.
Try For Free