Getting started overview

Smartcar provides developers with a unified API to interact with connected vehicles from multiple manufacturers. This allows applications to access vehicle data, such as location, odometer readings, and fuel levels, and to send commands like locking or unlocking doors. The getting started process involves setting up a developer account, creating an application to obtain API credentials, and then using the Smartcar Connect SDK to authorize user vehicles. Once a vehicle is authorized, developers can make API requests to retrieve data or control vehicle functions.

The core components for integration are:

  • Smartcar Dashboard: For account management, application creation, and credential retrieval.
  • Smartcar Connect SDK: A client-side library to streamline the user authorization flow, allowing vehicle owners to grant your application access.
  • Smartcar API: The RESTful interface for fetching vehicle data and sending commands after authorization.

Smartcar offers a free Developer plan that supports up to 10 vehicles, suitable for testing and development before scaling to a Growth or Enterprise plan.

Here's a quick reference for the essential steps:

Step What to do Where
1. Sign up Create a Smartcar developer account. Smartcar documentation portal
2. Create Application Register a new application to get API keys. Smartcar Dashboard
3. Configure Redirect URI Add your application's redirect URI for the Connect flow. Smartcar Dashboard application settings
4. Install SDK Add the Smartcar Connect SDK to your project. Your application backend (e.g., Node.js, Python)
5. Authorize Vehicle Implement the Connect flow to link a user's vehicle. Your application frontend (via Connect SDK)
6. Make First Request Fetch vehicle data using the Smartcar API and access token. Your application backend

Create an account and get keys

Before making any API calls, you need to set up a Smartcar developer account and create an application to obtain your API credentials. These credentials include a Client ID and Client Secret, which authenticate your application with the Smartcar platform.

  1. Sign Up for a Developer Account: Navigate to the Smartcar developer portal and sign up for a new account. The free Developer plan is sufficient for initial testing and integration.
  2. Create a New Application: Once logged in, go to your Smartcar Dashboard. Look for an option to 'Create New App' or similar. You'll need to provide a name for your application.
  3. Retrieve API Credentials: After creating your application, the dashboard will display your unique Client ID and Client Secret. The Client ID is public and is used in the Connect flow, while the Client Secret should be kept confidential and used only on your backend server.
  4. Configure Redirect URI: Crucially, you must configure a Redirect URI for your application. This URI is where Smartcar Connect will redirect the user after they authorize their vehicle. It must be a URL on your server that can handle the authorization code. During development, you can use http://localhost:8000/callback or similar. Ensure this URI is registered in your application settings within the Smartcar Dashboard. This is a standard practice in OAuth 2.0 authorization flows to prevent security vulnerabilities.

It is important to store your Client Secret securely and never expose it in client-side code. For development, environment variables are a common practice to manage these keys.

Your first request

Making your first request with Smartcar involves two primary steps: authorizing a vehicle using the Smartcar Connect SDK and then using the obtained access token to call the Smartcar API from your backend. This example uses Node.js, as it is one of Smartcar's primary language examples.

1. Authorize a Vehicle with Smartcar Connect

The Smartcar Connect SDK simplifies the process of obtaining user consent and an authorization code. This code is then exchanged for an access token on your backend.

Frontend (HTML/JavaScript):

Include the Connect SDK in your frontend and initiate the authorization flow:

<!DOCTYPE html>
<html>
  <head>
    <title>Smartcar Connect</title>
    <script type="text/javascript" src="https://connect.smartcar.com/sdk?version=1.0.0"></script>
  </head>
  <body>
    <button onclick="smartcarConnect()">Connect your car</button>
    <script type="text/javascript">
      function smartcarConnect() {
        Smartcar.popup({
          clientId: 'YOUR_CLIENT_ID',
          redirectUri: 'YOUR_REDIRECT_URI',
          scope: ['read_vehicle_info', 'read_location', 'read_odometer'],
          onComplete: function(err, code, state) {
            if (err) {
              console.error('Authorization error:', err);
            } else {
              console.log('Authorization code:', code);
              // Send this code to your backend to exchange for an access token
              fetch('/exchange-token', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ code: code })
              })
              .then(response => response.json())
              .then(data => console.log('Access token data:', data))
              .catch(error => console.error('Error exchanging token:', error));
            }
          }
        });
      }
    </script>
  </body>
</html>

Replace 'YOUR_CLIENT_ID' with your actual Client ID and 'YOUR_REDIRECT_URI' with the URI registered in your Smartcar Dashboard.

2. Exchange Code for Access Token (Backend)

Your backend server receives the authorization code from the frontend and exchanges it for an access token using the Smartcar SDK for your chosen language. This example uses Node.js.

Backend (Node.js with Express):

const express = require('express');
const smartcar = require('smartcar');
const app = express();
const port = 8000;

// Ensure you have dotenv or similar for environment variables
require('dotenv').config();

app.use(express.json());
app.use(express.static('public')); // Serve your HTML file from a 'public' folder

const client = new smartcar.AuthClient({
  clientId: process.env.SMARTCAR_CLIENT_ID,
  clientSecret: process.env.SMARTCAR_CLIENT_SECRET,
  redirectUri: process.env.SMARTCAR_REDIRECT_URI,
  scope: ['read_vehicle_info', 'read_location', 'read_odometer']
});

// Endpoint to handle the authorization code from the frontend
app.post('/exchange-token', async (req, res) => {
  const code = req.body.code;
  if (!code) {
    return res.status(400).send({ error: 'Authorization code missing.' });
  }

  try {
    const access = await client.exchangeCode(code);
    // Store access.accessToken and access.refreshToken securely
    // for subsequent API calls and token refreshes.
    console.log('Access Token:', access.accessToken);
    console.log('Refresh Token:', access.refreshToken);
    res.send({ message: 'Token exchanged successfully!', accessToken: access.accessToken });
  } catch (error) {
    console.error('Error exchanging code for token:', error);
    res.status(500).send({ error: 'Failed to exchange code.' });
  }
});

// Endpoint to make a first API call using the obtained access token
app.get('/vehicle-info', async (req, res) => {
  // In a real application, you would retrieve the access token from your database
  // For this example, we'll assume it's passed or available.
  const accessToken = req.query.accessToken; // Or retrieve from session/DB
  if (!accessToken) {
    return res.status(400).send({ error: 'Access token missing.' });
  }

  try {
    const vehicleIds = await smartcar.getVehicleIds({ accessToken });
    if (vehicleIds.vehicles.length === 0) {
      return res.status(404).send({ error: 'No vehicles found for this access token.' });
    }
    const vehicle = new smartcar.Vehicle(vehicleIds.vehicles[0], accessToken);
    const attributes = await vehicle.attributes();
    const odometer = await vehicle.odometer();
    const location = await vehicle.location();
    res.send({ attributes, odometer, location });
  } catch (error) {
    console.error('Error fetching vehicle info:', error);
    res.status(500).send({ error: 'Failed to fetch vehicle information.' });
  }
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});

Remember to install the Smartcar SDK (npm install smartcar) and Express (npm install express) and set up your environment variables (SMARTCAR_CLIENT_ID, SMARTCAR_CLIENT_SECRET, SMARTCAR_REDIRECT_URI) for the backend script.

Common next steps

After successfully making your first request, consider these common next steps to build out your Smartcar integration:

  • Handle Refresh Tokens: Access tokens have a limited lifespan. Smartcar issues refresh tokens that allow your application to obtain new access tokens without requiring the user to re-authorize their vehicle. Implement logic to store and use refresh tokens to maintain continuous access to vehicle data. The Smartcar documentation on refresh tokens provides specific guidance.
  • Explore More Endpoints: Smartcar offers a variety of endpoints to access different types of vehicle data (e.g., fuel, battery, tire pressure) and controls (e.g., lock/unlock, start/stop charging). Consult the Smartcar API reference to discover additional capabilities relevant to your application.
  • Error Handling: Implement robust error handling for API calls, including network issues, invalid tokens, and vehicle-specific errors. Smartcar's API returns standard HTTP status codes and detailed error messages.
  • Webhooks: For real-time updates and asynchronous events (e.g., vehicle disconnected, odometer change), explore Smartcar Webhooks. This reduces the need for constant polling and improves efficiency.
  • User Management: Develop a system to associate Smartcar vehicle access tokens with your application's users. This typically involves storing the accessToken and refreshToken in a secure database tied to a user ID.
  • Production Deployment: When moving to production, ensure your Redirect URIs are secure (HTTPS), your Client Secret is protected, and your application scales appropriately. Consider the Smartcar pricing plans for production usage.

Troubleshooting the first call

Encountering issues during your initial Smartcar integration is common. Here are some frequent problems and their solutions:

  • Invalid Client ID or Secret: Double-check that you are using the correct Client ID and Client Secret from your Smartcar Dashboard. Ensure no leading or trailing spaces are present.
  • Incorrect Redirect URI: The redirectUri used in your frontend Connect SDK initiation and in your backend AuthClient configuration must exactly match a Redirect URI registered in your application's settings in the Smartcar Dashboard. Even a slight mismatch (e.g., HTTP vs. HTTPS, trailing slash) will cause an error.
  • Missing Scope: If you receive errors about insufficient permissions, verify that the scope array passed to Smartcar.popup (frontend) and AuthClient (backend) includes all the necessary permissions for the API endpoints you are trying to access. For example, to read odometer, read_odometer scope is required. The Smartcar documentation on permissions provides a full list.
  • Expired Access Token: Access tokens have a limited lifespan. If you're making repeated API calls, ensure you have implemented logic to refresh the token using the refresh token before it expires.
  • CORS Issues: If your frontend is trying to directly access the Smartcar API or your backend from a different origin, you might encounter Cross-Origin Resource Sharing (CORS) errors. Ensure your backend properly handles CORS headers, especially if running on a different domain or port than your frontend during development.
  • Vehicle Not Authorized: The Smartcar API will return an error if you attempt to access data for a vehicle that has not been successfully authorized by the user through the Connect flow. Verify the authorization process completed successfully and an access token was issued for the target vehicle.
  • Network Connectivity: Ensure your server has outbound network access to Smartcar's API endpoints. Firewall rules or proxy settings can sometimes block these connections.
  • SDK Installation: Confirm that the Smartcar SDK for your chosen language is correctly installed and imported into your project. For Node.js, this means npm install smartcar.