API Integration Guide
Introduction to ANG SILAKBO API Integrations
Welcome to the ANG SILAKBO API integration guide. This documentation will help you integrate our platform with popular third-party services such as Firebase, Supabase, Cloudinary, and more.
Our API is designed to work seamlessly with these services, allowing you to leverage their capabilities while maintaining a consistent development experience. Whether you need real-time databases, cloud storage, payment processing, or other functionality, this guide will show you how to integrate these services with ANG SILAKBO.
Integration Benefits
- Simplified authentication flows
- Consistent data handling
- Reduced development time
- Unified error handling
Integration Overview
ANG SILAKBO can be integrated with various third-party services to enhance your application's capabilities. Below are the key integrations we support:
Firebase
Google's app development platform
-
Real-time Database
Store and sync data in real-time across all your users' devices
-
Authentication
Secure user authentication with multiple providers
-
Cloud Storage
Store and serve user-generated content
Supabase
Open source Firebase alternative
-
PostgreSQL Database
Powerful and scalable relational database with realtime capabilities
-
Authentication
User management with row-level security
-
Storage
Store and serve large files efficiently
Cloudinary
Cloud-based media management
-
Image & Video Storage
Store, transform, optimize, and deliver media assets
-
Auto-Transformations
Resize, crop, and optimize media on-the-fly
-
AI-Powered Analysis
Automatic tagging and content moderation
Stripe
Payment processing platform
-
Payment Processing
Accept payments online with secure checkout
-
Subscription Management
Recurring billing and subscription management
-
Fraud Prevention
Advanced fraud detection and prevention
MongoDB
NoSQL document database
-
Document Database
Flexible schema design and powerful querying
-
Atlas Cloud
Fully managed database-as-a-service
-
Data Analytics
Real-time data analytics and visualization
AWS S3
Cloud object storage
-
Object Storage
Store and retrieve any amount of data from anywhere
-
Scalability
Virtually unlimited storage capacity
-
Security
Fine-grained access controls and encryption
Firebase is a comprehensive app development platform by Google that provides a variety of tools and services to help you develop high-quality apps. ANG SILAKBO integrates seamlessly with Firebase to provide you with real-time database capabilities, authentication, cloud storage, and more.
Setting Up Firebase
Follow these steps to set up Firebase with your ANG SILAKBO project:
Create a Firebase Project
Go to the Firebase Console and create a new project. Follow the on-screen instructions to set up your project.
Register Your App
In the Firebase console, click on "Add app" and select the web platform. Follow the instructions to register your app and get your Firebase configuration.
Install Firebase SDK
Install the Firebase SDK in your ANG SILAKBO project using npm:
Terminal
npm install firebase
Initialize Firebase
Create a Firebase configuration file in your project:
firebase.js
// Import the functions you need from the SDKs you need import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; import { getFirestore } from "firebase/firestore"; import { getStorage } from "firebase/storage"; // Your web app's Firebase configuration const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_AUTH_DOMAIN", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_STORAGE_BUCKET", messagingSenderId: "YOUR_MESSAGING_SENDER_ID", appId: "YOUR_APP_ID" }; // Initialize Firebase const app = initializeApp(firebaseConfig); // Initialize Firebase services const auth = getAuth(app); const db = getFirestore(app); const storage = getStorage(app); export { app, auth, db, storage };
Connect with ANG SILAKBO
Import your Firebase configuration into your ANG SILAKBO project:
app.js
import { app, auth, db, storage } from './firebase'; import { SILAKBO } from '@silakbo/sdk'; // Initialize ANG SILAKBO with Firebase const silakbo = new SILAKBO({ firebase: { app, auth, db, storage } }); // Now you can use Firebase with ANG SILAKBO export default silakbo;
Firebase Authentication
ANG SILAKBO provides a seamless integration with Firebase Authentication, allowing you to easily implement user authentication in your application.
User Sign Up
import silakbo from './app'; async function signUpUser(email, password) { try { const user = await silakbo.firebase.auth.createUser({ email, password }); // Store additional user data in Firestore await silakbo.firebase.db.setUserData(user.uid, { email: user.email, createdAt: new Date(), role: 'user' }); return user; } catch (error) { console.error('Error signing up user:', error); throw error; } }
User Sign In
import silakbo from './app'; async function signInUser(email, password) { try { const user = await silakbo.firebase.auth.signInUser({ email, password }); // Log user sign in await silakbo.firebase.db.updateUserLastLogin(user.uid); return user; } catch (error) { console.error('Error signing in user:', error); throw error; } }
Social Authentication
import silakbo from './app'; import { GoogleAuthProvider, signInWithPopup } from "firebase/auth"; async function signInWithGoogle() { try { const provider = new GoogleAuthProvider(); const result = await silakbo.firebase.auth.signInWithProvider(provider); // Handle the signed-in user const user = result.user; // Check if this is a new user const isNewUser = result.additionalUserInfo.isNewUser; if (isNewUser) { // Create a new user profile await silakbo.firebase.db.setUserData(user.uid, { email: user.email, displayName: user.displayName, photoURL: user.photoURL, createdAt: new Date(), role: 'user' }); } return user; } catch (error) { console.error('Error signing in with Google:', error); throw error; } }
Firebase Realtime Database & Firestore
ANG SILAKBO provides utilities for working with both Firebase Realtime Database and Firestore, allowing you to choose the database that best fits your needs.
Creating and Reading Data in Firestore
import silakbo from './app'; import { collection, addDoc, query, where, getDocs } from "firebase/firestore"; // Create a new document in a collection async function createPost(userId, postData) { try { const postsCollection = collection(silakbo.firebase.db, "posts"); const newPost = { title: postData.title, content: postData.content, author: userId, createdAt: new Date(), likes: 0, comments: [] }; const docRef = await addDoc(postsCollection, newPost); console.log("Document written with ID: ", docRef.id); return { id: docRef.id, ...newPost }; } catch (error) { console.error("Error adding document: ", error); throw error; } } // Query for documents in a collection async function getUserPosts(userId) { try { const postsCollection = collection(silakbo.firebase.db, "posts"); const q = query(postsCollection, where("author", "==", userId)); const querySnapshot = await getDocs(q); const posts = []; querySnapshot.forEach((doc) => { posts.push({ id: doc.id, ...doc.data() }); }); return posts; } catch (error) { console.error("Error getting documents: ", error); throw error; } }
Real-time Updates with Firestore
import silakbo from './app'; import { collection, query, onSnapshot } from "firebase/firestore"; // Subscribe to real-time updates function subscribeToPostUpdates(callback) { const postsCollection = collection(silakbo.firebase.db, "posts"); // Create a query against the collection const q = query(postsCollection); // Subscribe to query snapshot const unsubscribe = onSnapshot(q, (querySnapshot) => { const posts = []; querySnapshot.forEach((doc) => { posts.push({ id: doc.id, ...doc.data() }); }); // Call the callback function with the updated data callback(posts); }, (error) => { console.error("Error getting real-time updates: ", error); }); // Return the unsubscribe function to stop listening to updates return unsubscribe; } // Usage example const unsubscribe = subscribeToPostUpdates((posts) => { console.log("Current posts: ", posts); // Update UI with the latest posts updateUIWithPosts(posts); }); // When you want to stop listening to updates // unsubscribe();
Firebase Storage
ANG SILAKBO provides utilities for working with Firebase Storage, allowing you to upload, download, and manage files in your application.
Uploading Files
import silakbo from './app'; import { ref, uploadBytes, getDownloadURL } from "firebase/storage"; async function uploadUserProfileImage(userId, file) { try { // Create a storage reference const storageRef = ref(silakbo.firebase.storage, `users/${userId}/profile.jpg`); // Upload the file const snapshot = await uploadBytes(storageRef, file); console.log('Uploaded profile image!'); // Get the download URL const downloadURL = await getDownloadURL(snapshot.ref); // Update user profile with the new image URL await silakbo.firebase.db.updateUserData(userId, { photoURL: downloadURL }); return downloadURL; } catch (error) { console.error('Error uploading image:', error); throw error; } }
Downloading Files
import silakbo from './app'; import { ref, getDownloadURL } from "firebase/storage"; async function getUserProfileImageURL(userId) { try { // Create a reference to the file const storageRef = ref(silakbo.firebase.storage, `users/${userId}/profile.jpg`); // Get the download URL const url = await getDownloadURL(storageRef); return url; } catch (error) { console.error('Error getting download URL:', error); throw error; } }
Deleting Files
import silakbo from './app'; import { ref, deleteObject } from "firebase/storage"; async function deleteUserProfileImage(userId) { try { // Create a reference to the file const storageRef = ref(silakbo.firebase.storage, `users/${userId}/profile.jpg`); // Delete the file await deleteObject(storageRef); console.log('Profile image deleted successfully'); // Update user profile to remove the image URL await silakbo.firebase.db.updateUserData(userId, { photoURL: null }); return true; } catch (error) { console.error('Error deleting image:', error); throw error; } }
Supabase is an open-source Firebase alternative that provides a PostgreSQL database, authentication, storage, and more. ANG SILAKBO integrates seamlessly with Supabase to provide you with powerful database capabilities and authentication.
Setting Up Supabase
Follow these steps to set up Supabase with your ANG SILAKBO project:
Create a Supabase Project
Go to the Supabase Dashboard and create a new project. Follow the on-screen instructions to set up your project.
Get Your API Keys
After creating your project, go to the Project Settings > API section to find your project URL and API keys.
Install Supabase Client
Install the Supabase JavaScript client in your ANG SILAKBO project using npm:
Terminal
npm install @supabase/supabase-js
Initialize Supabase
Create a Supabase client in your project:
supabase.js
import { createClient } from '@supabase/supabase-js'; const supabaseUrl = 'YOUR_SUPABASE_URL'; const supabaseKey = 'YOUR_SUPABASE_KEY'; const supabase = createClient(supabaseUrl, supabaseKey); export default supabase;
Connect with ANG SILAKBO
Import your Supabase client into your ANG SILAKBO project:
app.js
import supabase from './supabase'; import { SILAKBO } from '@silakbo/sdk'; // Initialize ANG SILAKBO with Supabase const silakbo = new SILAKBO({ supabase: supabase }); // Now you can use Supabase with ANG SILAKBO export default silakbo;
Supabase Authentication
ANG SILAKBO provides a seamless integration with Supabase Authentication, allowing you to easily implement user authentication in your application.
User Sign Up
import silakbo from './app'; async function signUpUser(email, password) { try { const { data, error } = await silakbo.supabase.auth.signUp({ email, password }); if (error) throw error; // Create a user profile if sign up was successful if (data?.user) { await silakbo.supabase .from('profiles') .insert([ { id: data.user.id, email: data.user.email, created_at: new Date() } ]); } return data; } catch (error) { console.error('Error signing up user:', error); throw error; } }
User Sign In
import silakbo from './app'; async function signInUser(email, password) { try { const { data, error } = await silakbo.supabase.auth.signInWithPassword({ email, password }); if (error) throw error; // Update last login timestamp if (data?.user) { await silakbo.supabase .from('profiles') .update({ last_login: new Date() }) .eq('id', data.user.id); } return data; } catch (error) { console.error('Error signing in user:', error); throw error; } }
Social Authentication
import silakbo from './app'; import { Auth } from '@supabase/auth-ui-react'; import { ThemeSupa } from '@supabase/auth-ui-shared'; // Component for social login function AuthUI() { return ( <Auth supabaseClient={silakbo.supabase} appearance={{ theme: ThemeSupa }} providers={['google', 'github', 'facebook']} redirectTo={window.location.origin} onSuccess={async (session) => { // Check if user profile exists const { data: profile } = await silakbo.supabase .from('profiles') .select('*') .eq('id', session.user.id) .single(); // Create profile if it doesn't exist if (!profile) { await silakbo.supabase .from('profiles') .insert([ { id: session.user.id, email: session.user.email, created_at: new Date() } ]); } }} /> ); }
Supabase Database
ANG SILAKBO provides utilities for working with Supabase's PostgreSQL database, allowing you to perform CRUD operations and real-time subscriptions.
Creating and Reading Data
import silakbo from './app'; // Create a new post async function createPost(userId, postData) { try { const { data, error } = await silakbo.supabase .from('posts') .insert([ { title: postData.title, content: postData.content, user_id: userId, created_at: new Date() } ]) .select(); if (error) throw error; return data[0]; } catch (error) { console.error('Error creating post:', error); throw error; } } // Get posts for a user async function getUserPosts(userId) { try { const { data, error } = await silakbo.supabase .from('posts') .select('*') .eq('user_id', userId) .order('created_at', { ascending: false }); if (error) throw error; return data; } catch (error) { console.error('Error fetching posts:', error); throw error; } }
Real-time Subscriptions
import silakbo from './app'; // Subscribe to real-time changes on the posts table function subscribeToPostUpdates(callback) { // Enable real-time for this table const subscription = silakbo.supabase .channel('public:posts') .on('postgres_changes', { event: '*', schema: 'public', table: 'posts' }, (payload) => { // Call the callback with the payload callback(payload); } ) .subscribe(); // Return the subscription so it can be unsubscribed later return subscription; } // Usage example const subscription = subscribeToPostUpdates((payload) => { console.log('Change received!', payload); if (payload.eventType === 'INSERT') { console.log('New post added:', payload.new); addPostToUI(payload.new); } else if (payload.eventType === 'UPDATE') { console.log('Post updated:', payload.new); updatePostInUI(payload.new); } else if (payload.eventType === 'DELETE') { console.log('Post deleted:', payload.old); removePostFromUI(payload.old.id); } }); // To unsubscribe // subscription.unsubscribe();
Supabase Storage
ANG SILAKBO provides utilities for working with Supabase Storage, allowing you to upload, download, and manage files in your application.
Uploading Files
import silakbo from './app'; async function uploadUserProfileImage(userId, file) { try { // Define a unique file path const filePath = `${userId}/profile-${Date.now()}.jpg`; // Upload the file const { data, error } = await silakbo.supabase .storage .from('avatars') .upload(filePath, file, { cacheControl: '3600', upsert: true }); if (error) throw error; // Get the public URL for the file const { data: { publicUrl } } = silakbo.supabase .storage .from('avatars') .getPublicUrl(data.path); // Update the user's profile with the new avatar URL const { error: updateError } = await silakbo.supabase .from('profiles') .update({ avatar_url: publicUrl }) .eq('id', userId); if (updateError) throw updateError; return publicUrl; } catch (error) { console.error('Error uploading profile image:', error); throw error; } }
Downloading Files
import silakbo from './app'; async function downloadUserProfileImage(filePath) { try { // Download the file const { data, error } = await silakbo.supabase .storage .from('avatars') .download(filePath); if (error) throw error; // Create a URL for the downloaded blob const url = URL.createObjectURL(data); return url; } catch (error) { console.error('Error downloading file:', error); throw error; } }
Deleting Files
import silakbo from './app'; async function deleteUserProfileImage(userId, filePath) { try { // Delete the file const { error } = await silakbo.supabase .storage .from('avatars') .remove([filePath]); if (error) throw error; // Update the user's profile to remove the avatar URL const { error: updateError } = await silakbo.supabase .from('profiles') .update({ avatar_url: null }) .eq('id', userId); if (updateError) throw updateError; return true; } catch (error) { console.error('Error deleting file:', error); throw error; } }
Cloudinary is a cloud-based media management platform that provides end-to-end media management solutions including uploads, storage, transformations, optimizations, and delivery. ANG SILAKBO integrates seamlessly with Cloudinary to provide you with powerful media management capabilities.
Setting Up Cloudinary
Follow these steps to set up Cloudinary with your ANG SILAKBO project:
Create a Cloudinary Account
Go to the Cloudinary Sign-up page and create a new account.
Get Your API Credentials
After creating your account, go to the Dashboard to find your cloud name, API key, and API secret.
Install Cloudinary SDK
Install the Cloudinary SDK in your ANG SILAKBO project using npm:
Terminal
npm install cloudinary
Initialize Cloudinary
Create a Cloudinary configuration file in your project:
cloudinary.js
import { v2 as cloudinary } from 'cloudinary'; // Configure Cloudinary cloudinary.config({ cloud_name: 'YOUR_CLOUD_NAME', api_key: 'YOUR_API_KEY', api_secret: 'YOUR_API_SECRET' }); export default cloudinary;
Connect with ANG SILAKBO
Import your Cloudinary configuration into your ANG SILAKBO project:
app.js
import cloudinary from './cloudinary'; import { SILAKBO } from '@silakbo/sdk'; // Initialize ANG SILAKBO with Cloudinary const silakbo = new SILAKBO({ cloudinary: cloudinary }); // Now you can use Cloudinary with ANG SILAKBO export default silakbo;
Uploading Media to Cloudinary
ANG SILAKBO provides utilities for uploading images, videos, and other media files to Cloudinary.
Upload an Image
import silakbo from './app'; // Server-side upload using file path async function uploadImage(imagePath, folder = 'general') { try { const result = await silakbo.cloudinary.uploader.upload(imagePath, { folder: folder, resource_type: 'image' }); console.log('Image uploaded successfully:', result); return result; } catch (error) { console.error('Error uploading image:', error); throw error; } } // Client-side upload using a File object async function uploadImageFromClient(file, folder = 'general') { try { // Create a FormData object const formData = new FormData(); formData.append('file', file); formData.append('upload_preset', 'YOUR_UNSIGNED_UPLOAD_PRESET'); // Create this in your Cloudinary dashboard formData.append('folder', folder); // Upload the image to Cloudinary const response = await fetch(`https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/image/upload`, { method: 'POST', body: formData }); const result = await response.json(); console.log('Image uploaded successfully:', result); return result; } catch (error) { console.error('Error uploading image:', error); throw error; } }
Upload a Video
import silakbo from './app'; // Server-side upload using file path async function uploadVideo(videoPath, folder = 'videos') { try { const result = await silakbo.cloudinary.uploader.upload(videoPath, { folder: folder, resource_type: 'video', eager: [ { format: 'mp4', transformation: [ { width: 640, crop: 'scale' }, { quality: 'auto' } ]} ], eager_async: true }); console.log('Video uploaded successfully:', result); return result; } catch (error) { console.error('Error uploading video:', error); throw error; } }
Upload with Progress Tracking
import silakbo from './app'; // Client-side upload with progress tracking function uploadWithProgress(file, folder = 'general', progressCallback) { return new Promise((resolve, reject) => { // Create a FormData object const formData = new FormData(); formData.append('file', file); formData.append('upload_preset', 'YOUR_UNSIGNED_UPLOAD_PRESET'); formData.append('folder', folder); // Create a new XMLHttpRequest const xhr = new XMLHttpRequest(); // Track upload progress xhr.upload.onprogress = (event) => { if (event.lengthComputable) { const progress = Math.round((event.loaded / event.total) * 100); progressCallback(progress); } }; // Handle the response xhr.onload = () => { if (xhr.status === 200) { const response = JSON.parse(xhr.responseText); resolve(response); } else { reject(new Error('Upload failed')); } }; // Handle errors xhr.onerror = () => { reject(new Error('Upload failed')); }; // Open and send the request xhr.open('POST', `https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/auto/upload`, true); xhr.send(formData); }); `https://api.cloudinary.com/v1_1/YOUR_CLOUD_NAME/auto/upload`, true); xhr.send(formData); }); } // Usage example async function handleFileUpload(file) { try { const result = await uploadWithProgress(file, 'user_uploads', (progress) => { console.log(`Upload progress: ${progress}%`); updateProgressBar(progress); // Update UI progress bar }); console.log('Upload complete:', result); return result; } catch (error) { console.error('Upload failed:', error); throw error; } }
Image Transformations
Cloudinary provides powerful image transformation capabilities that you can leverage through ANG SILAKBO.
Basic Transformations
import silakbo from './app'; function getOptimizedImageUrl(publicId, options = {}) { // Default transformations const defaultTransformations = { width: options.width || 800, height: options.height || 600, crop: options.crop || 'fill', quality: options.quality || 'auto', format: options.format || 'auto' }; // Generate the URL const imageUrl = silakbo.cloudinary.url(publicId, { transformation: [defaultTransformations] }); return imageUrl; } // Usage example const optimizedUrl = getOptimizedImageUrl('folder/image1', { width: 500, height: 300, crop: 'fill', quality: 'auto:best' });
Advanced Transformations
import silakbo from './app'; function getProfilePictureUrl(publicId, options = {}) { // Create a round profile picture with a border const transformations = [ { width: options.size || 300, height: options.size || 300, gravity: 'face', crop: 'thumb', radius: 'max' }, { border: '3px_solid_white' }, { effect: 'shadow:50' } ]; // Generate the URL const imageUrl = silakbo.cloudinary.url(publicId, { transformation: transformations }); return imageUrl; } function getWatermarkedImageUrl(publicId, options = {}) { // Add a watermark to an image const transformations = [ { width: options.width || 800, crop: 'scale' }, { overlay: 'company_logo', gravity: 'south_east', x: 20, y: 20, width: 100, opacity: 70 } ]; // Generate the URL const imageUrl = silakbo.cloudinary.url(publicId, { transformation: transformations }); return imageUrl; }
Responsive Images
import silakbo from './app'; function getResponsiveImageSrcSet(publicId, options = {}) { // Generate srcset for responsive images const breakpoints = options.breakpoints || [320, 480, 640, 768, 1024, 1280, 1536]; const transformations = { crop: options.crop || 'fill', quality: options.quality || 'auto' }; // Generate srcset string const srcset = breakpoints.map(width => { const url = silakbo.cloudinary.url(publicId, { transformation: [ { ...transformations, width } ] }); return `${url} ${width}w`; }).join(', '); return srcset; } // Usage in a React component function ResponsiveImage({ publicId, alt, className }) { const srcset = getResponsiveImageSrcSet(publicId); const defaultUrl = silakbo.cloudinary.url(publicId, { transformation: [ { width: 800, crop: 'fill', quality: 'auto' } ] }); return (); }
Advanced Cloudinary Features
ANG SILAKBO integrates with Cloudinary's advanced features like AI-powered content analysis, auto-tagging, and content moderation.
AI Content Analysis
import silakbo from './app'; async function uploadWithAutoTagging(imagePath, folder = 'products') { try { // Upload image with auto-tagging const result = await silakbo.cloudinary.uploader.upload(imagePath, { folder: folder, resource_type: 'image', categorization: 'google_tagging', auto_tagging: 0.6 // Confidence threshold (0.0 to 1.0) }); console.log('Image uploaded with tags:', result.tags); return result; } catch (error) { console.error('Error uploading image with auto-tagging:', error); throw error; } } async function detectFaces(publicId) { try { // Get facial detection data for an image const result = await silakbo.cloudinary.api.resource(publicId, { detection: 'adv_face' }); const faceInfo = result.info.detection.adv_face; console.log('Face detection results:', faceInfo); return faceInfo; } catch (error) { console.error('Error detecting faces:', error); throw error; } }
Content Moderation
import silakbo from './app'; async function uploadWithModeration(imagePath, folder = 'user_content') { try { // Upload image with automatic content moderation const result = await silakbo.cloudinary.uploader.upload(imagePath, { folder: folder, resource_type: 'image', moderation: 'aws_rek', // AWS Rekognition moderation notification_url: 'https://your-webhook-url.com/cloudinary-moderation' }); console.log('Image uploaded with moderation:', result); // Check moderation status if available immediately if (result.moderation) { if (result.moderation[0].status === 'rejected') { console.log('Image was rejected by moderation'); // Handle rejected content await handleRejectedContent(result.public_id); } } return result; } catch (error) { console.error('Error uploading image with moderation:', error); throw error; } } // Handle webhook notification for moderation results async function handleModerationWebhook(req, res) { const moderationData = req.body; if (moderationData.moderation && moderationData.moderation.status === 'rejected') { // Handle rejected content await handleRejectedContent(moderationData.public_id); } res.status(200).send('Webhook received'); } async function handleRejectedContent(publicId) { try { // Option 1: Delete the rejected content await silakbo.cloudinary.uploader.destroy(publicId); // Option 2: Move to a quarantine folder for review // await silakbo.cloudinary.uploader.rename(publicId, `quarantine/${publicId}`); // Update your database to mark content as rejected await updateContentStatus(publicId, 'rejected'); console.log('Handled rejected content:', publicId); } catch (error) { console.error('Error handling rejected content:', error); throw error; } }