TeslaPy Documentation

repository·master·Indexed 19 days ago

https://github.com/tdorssers/teslapy

A Python library for interacting with the Tesla Owner API to remotely monitor and control Tesla vehicles, Powerwalls, and solar products. It features OAuth 2 authentication with PKCE, automatic token management, HTTP/2 support via httpx, and real-time data streaming via WebSockets. The library provides specialized classes for Vehicles, Batteries, and SolarPanels, and supports pluggable architectures for custom authentication and cache management.

Tokens
8.5K
Snippets
25
Records
33
Agent score
15%

What's inside TeslaPy

  1. Overview of TeslaPy

    master

    TeslaPy is a Python implementation of the client-side interface to the Tesla Motors Owner API. It allows developers to monitor and control Tesla products (Vehicles, Powerwalls, and Solar Panels) remotely.

    Key Features:

    • OAuth 2 Support: Implements Tesla's Single Sign-On (SSO) service.
    • Automatic Token Management: Acquired tokens are cached in cache.json in the current working directory and automatically refreshed when expired.
    • HTTP/2 Support: Uses httpx (with the [http2] extra) to communicate with Tesla's SSO and Owner API endpoints, which require HTTP/2 as of June 2026. It falls back to requests (HTTP/1.1) if httpx is unavailable.
    • Streaming API: Supports real-time data updates via WebSockets.
    • Pluggable Architecture: Supports custom cache loaders/dumpers and authenticator methods.

    Important Compatibility Note: The Owner API will eventually stop working for vehicles requiring the Tesla Vehicle Command Protocol. Pre-2021 Model S and X vehicles remain controllable via TeslaPy.

  2. Implement custom authentication with an authenticator function

    master

    The Tesla class supports a pluggable authentication method. You can pass a custom function to the authenticator argument in the constructor. This function must accept the authentication URL as an argument and return the redirected URL (the URL containing the authorization code/response) after the user completes the SSO process.

    import teslapy
    import webview
    
    def custom_auth(url):
        result = ['']
        window = webview.create_window('Login', url)
        def on_loaded():
            result[0] = window.get_current_url()
            if 'void/callback' in result[0].split('?')[0]:
                window.destroy()
        window.loaded += on_loaded
        webview.start()
        return result[0]
    
    with teslapy.Tesla('elon@tesla.com', authenticator=custom_auth) as tesla:
        tesla.fetch_token()
  3. Authenticate with Tesla SSO

    master

    TeslaPy 2.0.0+ does not support headless authentication by default.

    Standard Authentication Flow:

    1. Initialize the Tesla class with your email.
    2. The class will open the Tesla SSO page in your system's default web browser.
    3. After successful login, the browser will display a Page not found error.
    4. Action Required: Copy the full URL from the browser's address bar (it should start with https://auth.tesla.com/void/callback) and paste it into your terminal/console.

    Automating Authentication: You can provide a custom authenticator function to the Tesla constructor to automate the URL retrieval (e.g., using pywebview or selenium).

  4. Manual authentication via authorization_url()

    master

    If you prefer not to use an automated authenticator, you can manually retrieve the SSO URL using tesla.authorization_url() and then provide the resulting URL to fetch_token(authorization_response=...) after logging in via a standard browser.

    import teslapy
    tesla = teslapy.Tesla('elon@tesla.com')
    if not tesla.authorized:
        print('Use browser to login. Page Not Found will be shown at success.')
        print('Open this URL: ' + tesla.authorization_url())
        tesla.fetch_token(authorization_response=input('Enter URL after authentication: '))
    vehicles = tesla.vehicle_list()
    print(vehicles[0])
    tesla.close()
  5. Run TeslaPy demo applications via Docker

    master

    You can containerize the demo applications using the provided Dockerfile. To ensure user preferences and cached tokens are preserved, use a bind volume to map the current host directory to /home/tsla inside the container.

    sudo docker build -t teslapy .
    xhost +local:*
    sudo docker run -ti --net=host --privileged -v "$(pwd)":/home/tsla teslapy
  6. Staged authorization for TeslaPy 2.5.0+

    master

    TeslaPy supports staged authorization. You can generate a state and code_verifier using the Tesla instance, pass them to authorization_url(), and then use them when initializing a new Tesla instance for the second stage of authentication.

    import teslapy
    # First stage
    tesla = teslapy.Tesla('elon@tesla.com')
    if not tesla.authorized:
        state = tesla.new_state()
        code_verifier = tesla.new_code_verifier()
        print('Use browser to login. Page Not Found will be shown at success.')
        print('Open: ' + tesla.authorization_url(state=state, code_verifier=code_verifier))
    tesla.close()
    
    # Second stage
    tesla = teslapy.Tesla('elon@tesla.com', state=state, code_verifier=code_verifier)
    if not tesla.authorized:
        tesla.fetch_token(authorization_response=input('Enter URL after authentication: '))
    vehicles = tesla.vehicle_list()
    print(vehicles[0])
    tesla.close()
  7. Install TeslaPy via pip

    master

    You can install TeslaPy directly from PyPI. Note that it requires a specific version constraint for urllib3 to ensure compatibility.

    Ensure you have Python 2.7+ or 3.5+ installed.

    python -m pip install teslapy 'urllib3<2'
  8. Install TeslaPy with full dependencies

    master

    To use all features, including the CLI, GUI, and Selenium-based automation, install the following dependencies using PIP:

    • requests_oauthlib 0.8.0+
    • geopy 1.14.0+
    • pywebview 3.0+ (optional, for GUI)
    • selenium 3.13.0+ (optional, for automation)
    • websocket-client 0.59+
    • httpx[http2]
    python -m pip install requests_oauthlib 'httpx[http2]' geopy pywebview selenium websocket-client
  9. Configure custom cache loading and dumping

    master

    The Tesla class supports pluggable caching. You can provide a cache_loader function (which takes no arguments and returns a dict) and a cache_dumper function (which takes a dict and saves it) to the constructor to use storage other than the default disk cache (e.g., a database).

    import json
    import sqlite3
    import teslapy
    
    def db_load():
        con = sqlite3.connect('cache.db')
        cur = con.cursor()
        cache = {}
        try:
            for row in cur.execute('select * from teslapy'):
                cache[row[0]] = json.loads(row[1])
        except sqlite3.OperationalError:
            pass
        con.close()
        return cache
    
    def db_dump(cache):
        con = sqlite3.connect('cache.db')
        con.execute('create table if not exists teslapy (email text primary key, data json)')
        for email, data in cache.items():
            con.execute('replace into teslapy values (?, ?)', [email, json.dumps(data)])
        con.commit()
        con.close()
    
    with teslapy.Tesla('elon@tesla.com', cache_loader=db_load, cache_dumper=db_dump) as tesla:
        tesla.fetch_token()
  10. Use the Tesla Owner API CLI

    master

    The Tesla Owner API CLI allows you to interact with your Tesla vehicles, batteries, and solar panels from the command line. It supports authentication via Selenium (Chrome or Edge) or pywebview to handle SSO flows.

    Basic Usage Pattern:

    1. Provide your login email using -e.
    2. Use flags to specify what information you want to retrieve (e.g., --get for vehicle data, --battery for battery data, or --site for solar data).
    3. Use --list to see the full objects of the selected products.

    Authentication Note: If you are running in an environment that requires browser interaction for SSO, the CLI will attempt to use pywebview or a Selenium-controlled browser (Chrome/Edge) to capture the callback URL.

    # Example: Get vehicle data for a specific email
    teslapy -e user@example.com --get
    
    # Example: Get battery data
    teslapy -e user@example.com --battery
    
    # Example: Get solar site generation data
    teslapy -e user@example.com --site
  11. Troubleshoot common Tesla API errors

    master

    If you encounter specific error messages, they may indicate an outdated version of the module or changes in Tesla's API requirements:

    • 400 Client Error: endpoint_deprecated: You are using an old version of the module that does not support the required SSO service (auth.tesla.com).
    • ValueError: Credentials rejected. Recaptcha is required: The headless login is blocked by ReCaptcha; update the module.
    • 401 Client Error: Unauthorized: The module is attempting to use deprecated RFC 7523 tokens instead of required SSO tokens.
    • 412 Client Error: Endpoint is only available on fleetapi: The VEHICLE_LIST endpoint has been removed from the standard API; update the module to use the Fleet API.