Back

Reading and Writing Data Using the CompanyCam API

Aug 15, 20247 minute read

Hey there, fellow JavaScript wizards! Ready to dive into the world of CompanyCam API integration? Buckle up, because we're about to embark on a journey that'll have you syncing data like a pro in no time.

Introduction

CompanyCam's API is your ticket to seamlessly integrating photo documentation into your app. Whether you're building a project management tool or a customer portal, this API has got your back. Let's get cracking!

Authentication: Your VIP Pass

First things first, you'll need to get cozy with OAuth 2.0. Don't worry, it's not as scary as it sounds!

  1. Grab your API credentials from the CompanyCam dashboard.
  2. Implement the OAuth flow like this:
const getAccessToken = async (code) => { const response = await fetch('https://api.companycam.com/oauth/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ client_id: YOUR_CLIENT_ID, client_secret: YOUR_CLIENT_SECRET, code, grant_type: 'authorization_code' }) }); return response.json(); };

Reading Data: Time to Get Nosy

Fetching Projects

Want to grab all those juicy projects? Here's how:

const getProjects = async (accessToken, page = 1) => { const response = await fetch(`https://api.companycam.com/v2/projects?page=${page}`, { headers: { 'Authorization': `Bearer ${accessToken}` } }); return response.json(); };

Pro tip: Don't forget to handle pagination! The API returns 25 projects per page by default.

Retrieving Photos

Photos are the bread and butter of CompanyCam. Fetch 'em like this:

const getPhotos = async (accessToken, projectId) => { const response = await fetch(`https://api.companycam.com/v2/projects/${projectId}/photos`, { headers: { 'Authorization': `Bearer ${accessToken}` } }); return response.json(); };

Writing Data: Leave Your Mark

Creating a New Project

Time to make your mark! Create a project with this nifty snippet:

const createProject = async (accessToken, projectData) => { const response = await fetch('https://api.companycam.com/v2/projects', { method: 'POST', headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify(projectData) }); return response.json(); };

Uploading Photos

What's a project without photos? Here's how to upload them:

const uploadPhoto = async (accessToken, projectId, photoFile) => { const formData = new FormData(); formData.append('photo[image]', photoFile); const response = await fetch(`https://api.companycam.com/v2/projects/${projectId}/photos`, { method: 'POST', headers: { 'Authorization': `Bearer ${accessToken}` }, body: formData }); return response.json(); };

Syncing Data: Keep Everything in Harmony

Implementing Webhook Listeners

Webhooks are your best friend for real-time updates. Set up a listener like this:

app.post('/webhook', (req, res) => { const event = req.body; // Handle the event based on its type switch (event.type) { case 'project.created': // Handle new project break; case 'photo.created': // Handle new photo break; // ... handle other event types } res.sendStatus(200); });

Efficient Delta Syncing

Keep things speedy with delta syncing:

const syncData = async (accessToken, lastSyncTime) => { const response = await fetch(`https://api.companycam.com/v2/projects?modified_after=${lastSyncTime}`, { headers: { 'Authorization': `Bearer ${accessToken}` } }); const updatedProjects = await response.json(); // Process and save the updated projects return new Date().toISOString(); // Return current time as new lastSyncTime };

Error Handling and Rate Limiting

Don't let errors rain on your parade. Implement retry logic like a champ:

const apiCall = async (fn, maxRetries = 3) => { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.status === 429) { // Rate limited, wait and retry await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); } else if (i === maxRetries - 1) { throw error; // Max retries reached, throw the error } } } };

Best Practices: The Cherry on Top

  1. Cache aggressively: Your future self will thank you.
  2. Batch API calls when possible: The API loves efficiency as much as you do.
  3. Use compression: gzip is your friend for large requests.

Wrapping Up

And there you have it, folks! You're now armed with the knowledge to build a killer CompanyCam integration. Remember, the API is your oyster – so get out there and create something awesome!

Need more details? Check out the CompanyCam API docs. Now go forth and code!