Code Examples
Explore real-world examples and learn how to integrate Adev APIs into your applications with practical code samples.
Learn how to authenticate users using JWT tokens
JavaScript
// Authentication example
const authenticateUser = async (email, password) => {
const response = await fetch('https://api.adev.tech/v1/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email, password })
});
if (response.ok) {
const { token } = await response.json();
localStorage.setItem('authToken', token);
return token;
} else {
throw new Error('Authentication failed');
}
};
Create a new user profile with validation
JavaScript
// Create user profile
const createUserProfile = async (userData) => {
const token = localStorage.getItem('authToken');
const response = await fetch('https://api.adev.tech/v1/users', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: userData.name,
email: userData.email,
preferences: userData.preferences
})
});
return await response.json();
};
Set up webhooks for real-time event notifications
Node.js
// Webhook handler for notifications
const express = require('express');
const app = express();
app.use(express.json());
app.post('/webhook/notifications', (req, res) => {
const { event, data } = req.body;
switch(event) {
case 'user.created':
console.log('New user created:', data.user);
// Send welcome email
break;
case 'payment.completed':
console.log('Payment completed:', data.payment);
// Update user subscription
break;
default:
console.log('Unknown event:', event);
}
res.status(200).json({ received: true });
});
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});
Integrate with external services using our API
Python
# Third-party service integration
import requests
import json
class AdevAPIClient:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = 'https://api.adev.tech/v1'
self.headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
def sync_with_external_service(self, external_data):
"""Sync data from external service to Adev"""
processed_data = self.transform_data(external_data)
response = requests.post(
f'{self.base_url}/sync',
headers=self.headers,
json=processed_data
)
return response.json()
def transform_data(self, data):
"""Transform external data format to Adev format"""
return {
'users': [
{
'external_id': user['id'],
'name': user['full_name'],
'email': user['email_address']
}
for user in data.get('users', [])
]
}
Implement OAuth 2.0 authorization flow
JavaScript
// OAuth 2.0 implementation
class OAuth2Handler {
constructor(clientId, redirectUri) {
this.clientId = clientId;
this.redirectUri = redirectUri;
this.authUrl = 'https://api.adev.tech/v1/oauth/authorize';
this.tokenUrl = 'https://api.adev.tech/v1/oauth/token';
}
// Step 1: Redirect to authorization server
initiateAuth() {
const params = new URLSearchParams({
response_type: 'code',
client_id: this.clientId,
redirect_uri: this.redirectUri,
scope: 'read write',
state: this.generateState()
});
window.location.href = `${this.authUrl}?${params}`;
}
// Step 2: Exchange authorization code for token
async exchangeCodeForToken(code, state) {
if (!this.validateState(state)) {
throw new Error('Invalid state parameter');
}
const response = await fetch(this.tokenUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
grant_type: 'authorization_code',
client_id: this.clientId,
code: code,
redirect_uri: this.redirectUri
})
});
return await response.json();
}
generateState() {
const state = Math.random().toString(36).substring(7);
sessionStorage.setItem('oauth_state', state);
return state;
}
validateState(state) {
const storedState = sessionStorage.getItem('oauth_state');
sessionStorage.removeItem('oauth_state');
return state === storedState;
}
}
Perform bulk operations efficiently
JavaScript
// Batch operations for better performance
class BatchOperations {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.adev.tech/v1';
this.batchSize = 100;
}
async batchCreateUsers(users) {
const batches = this.createBatches(users, this.batchSize);
const results = [];
for (const batch of batches) {
try {
const response = await fetch(`${this.baseUrl}/users/batch`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ users: batch })
});
const result = await response.json();
results.push(...result.created);
} catch (error) {
console.error('Batch operation failed:', error);
// Implement retry logic here
}
}
return results;
}
createBatches(array, size) {
const batches = [];
for (let i = 0; i < array.length; i += size) {
batches.push(array.slice(i, i + size));
}
return batches;
}
async batchUpdate(updates) {
return await fetch(`${this.baseUrl}/users/batch`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ updates })
});
}
}
Need More Help?
Can't find the example you're looking for? Check out our documentation or get in touch with our developer support team.