Buying a Tesla? Get 1,000 miles of free supercharging with my referral code.
This is an unofficial .NET 5 client implementation of the Tesla JSON API used by the Android and iOS apps. The API provides functionality to monitor and control the Tesla vehicles remotely.
From Powershell
Nuget-Install 'Tesla-API'
.NET CLI
dotnet add package 'Tesla-API'
In the Startup.cs
file, add the following to the ConfigureServices
method to allow the TeslaAPI to be dependency injected.
services.AddScoped<ITeslaAPI, TeslaAPI>();
To make a request with the Tesla API, you'll need to create a HttpClient
and set the User-Agent
header to an identifier for your application.
Follow the standard OAuth process as documented by Tim Dorr to get an access token. After getting an access token, add it to the Authorization
header on the HttpClient
, which is passed into data API calls.
You can use the TeslaAuth package that provides a .net implementation to obtain a (refresh) token.
public class TeslaService
{
private readonly ITeslaAPI _teslaAPI;
private readonly HttpClient _client = new HttpClient();
/// <summary>
/// Initializes a new instance of the <see cref="TeslaService"/> class.
/// </summary>
/// <param name="teslaClient">The TeslaAPI client.</param>
public TeslaService(ITeslaAPI teslaAPI)
{
_teslaAPI = teslaAPI;
_client.DefaultRequestHeaders.Add("User-Agent", "MyApplication");
}
/// <summary>
/// Get all Vehicles in the user's account.
/// </summary>
/// <returns>Returns a list of all Vehicles.</returns>
public async Task<List<Vehicle>> GetVehiclesAsync(string clientID, string clientSecret, string bearerToken)
{
TeslaAccessToken accessToken = await _teslaAPI.GetAccesTokenAsync(_client, clientID, clientSecret, bearerToken);
_client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.AccessToken}");
return await _teslaAPI.GetAllVehiclesAsync(_client);
}
}