Advanced Usage Examples
Explore the platform's advanced capabilities with these in-depth examples. You will learn how to run requests in parallel, focus an analysis, and use specialized modes.
Each example below shows two things: the code you want to analyze and the API request that sends it. Read the explanation card at the bottom of each example to see what the AI found.
Parallel Requests
Here is how you can send several functions in parallel and collect the results. This saves time when you need to understand an entire module.
Code to Analyze
Source Code
interface User {
id: string;
name: string;
email: string;
role: 'admin' | 'user';
}
const processUsers = async (users: User[]) => {
const results = await Promise.all(
users.map(async user => {
try {
await validateUser(user);
await updateUserRole(user);
return { success: true, user };
} catch (error) {
return { success: false, error, user };
}
})
);
return {
successful: results.filter(r => r.success),
failed: results.filter(r => !r.success),
};
};Advanced API Usage
API usage
const snippets = [
{ code: validateUser.toString(), context: 'User validation' },
{ code: updateUserRole.toString(), context: 'Role update' },
{ code: processUsers.toString(), context: 'Main process' },
];
// The API explains one snippet per request, so send them in parallel
const explanations = await Promise.all(
snippets.map(async ({ code }) => {
const response = await fetch('https://explainthiscode.ai/api/explain', {
method: 'POST',
headers: {
'X-API-Key': process.env.EXPLAINTHIS_API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({ code, mode: 'performance', language: 'typescript' }),
});
return response.json();
})
);
explanations.forEach((exp, i) => {
console.log(`Explanation for ${snippets[i].context}:`);
console.log(exp);
});Analysis Details
This example shows batch processing of user data with TypeScript. It runs all operations at once using Promise.all and handles errors for each user. The result splits into successes and failures. The API explains one snippet per request, so the example sends the related functions in parallel.
Custom Analysis with Context
Narrow the analysis to what you care about. In this example, performance mode plus a focus area points the explanation at a data-analysis class.
Code to Analyze
Source Code
from typing import List, Dict, Optional
from datetime import datetime
import pandas as pd
class DataAnalyzer:
def __init__(self, config: Dict[str, any]):
self.config = config
self.cache: Dict[str, pd.DataFrame] = {}
def analyze_time_series(
self,
data: pd.DataFrame,
metrics: List[str],
window: Optional[int] = None
) -> Dict[str, pd.Series]:
"""
Analyze time series data with rolling windows and custom metrics.
Args:
data: Time series data
metrics: List of metrics to calculate
window: Rolling window size
"""
results = {}
for metric in metrics:
if window:
result = data.rolling(window).agg(metric)
else:
result = data.agg(metric)
results[metric] = result
return resultsAdvanced API Usage
API usage
import os
import requests
response = requests.post(
"https://explainthiscode.ai/api/explain",
headers={"X-API-Key": os.environ["EXPLAINTHIS_API_KEY"]},
json={
"code": code,
"mode": "performance",
"language": "python",
"focus": ["performance"],
},
)
print(response.json())Analysis Details
This example shows a data analysis class that uses pandas for time series work. The code includes type hints, docstrings, and flexible config. Performance mode with a focus area points the analysis at how the pandas operations affect speed.
Security Analysis Mode
Want to find security holes before they reach production? This example runs a full security scan on an authentication endpoint, checking for common mistakes.
Code to Analyze
Source Code
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const app = express();
app.use(express.json());
app.post('/api/auth', async (req, res) => {
const { username, password } = req.body;
try {
// Get user from database
const user = await db.collection('users')
.findOne({ username });
if (!user) {
return res.status(401).json({
error: 'Invalid credentials'
});
}
// Verify password
const valid = await bcrypt.compare(
password,
user.password
);
if (!valid) {
return res.status(401).json({
error: 'Invalid credentials'
});
}
// Generate token
const token = jwt.sign(
{ userId: user._id },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
res.json({ token });
} catch (error) {
res.status(500).json({
error: 'Internal server error'
});
}
});Advanced API Usage
API usage
const response = await fetch('https://explainthiscode.ai/api/explain', {
method: 'POST',
headers: {
'X-API-Key': process.env.EXPLAINTHIS_API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({ code, mode: 'security', language: 'javascript' }),
});
console.log(await response.json());Analysis Details
This authentication endpoint covers several security topics. The security mode checks for: proper password hashing with bcrypt, JWT token creation, error messages that don't leak info, and use of environment variables for secrets.
Advanced Features
Here is a quick summary of what you can do beyond the basics:
- Batch processing: Send several snippets at once and get all the results back in a single response.
- Context-aware analysis: Attach related files and dependency info so the AI gives more accurate results.
- Security scanning: Ask the AI to hunt for vulnerabilities and suggest fixes before you ship.
- Custom options: Fine-tune the analysis by choosing focus areas, audience level, and output detail.
- Performance mode: Get tips on how to make your code run faster and use less memory.