PUT Vehicle

The PUT Vehicle method within the Customer Meta Data – Vehicles API enables integrated users to edit the vehicle object details within the referenced REVEAL account.

Before attempting to retrieve vehicle location information it is important to know if the REVEAL account has been updated with valid VEHICLE NUMBERS for each vehicle to be pulled via the API. The VEHICLE NUMBER and VEHICLE NAME fields are different fields within REVEAL and the VEHICLE NUMBER field is not automatically populated upon account creation.

<?php
   $token = 'TOKEN_STRING';
   $FIM_app_id = 'APP_ID';
   $FIM_endpoint = 'https://fim.api.us.fleetmatics.com/cmd/v1/vehicles/';

   //Set local variables
   $vehicle_number = 'VEHICLE_NUMBER';
   $vehicle_reg_number = '12345HAQS';
   $vehicle_vin = '12FG4561523A415F153';
   $vehicle_make = 'FORD';
   $vehicle_year = '2012';
   $vehicle_model = 'Fiesta';
   $vehicle_tankCapacity = 20.5;
   $vehicle_highwayMPG = 14.5;
   $vehicle_cityMPG = 11.5;
   $vehicle_size = 1;
   
   //Using variables, create an array to store data for PUT. Note: '=>' is necessary
   $put_data = array('RegistrationNumber' => $vehicle_reg_number,
                     'VIN' => $vehicle_vin,
                     'Make' => $vehicle_make,
                     'Year' => $vehicle_year,
                     'Model' => $vehicle_model,
                     'TankCapacity' => $vehicle_tankCapacity,
                     'HighwayMPG' => $vehicle_highwayMPG,
                     'CityMPG' => $vehicle_cityMPG,
                     'VehicleSize' => $vehicle_size					 
                     );

   //Call method
   echo put_vehicle_info($vehicle_number, $put_data, $FIM_endpoint, $FIM_app_id, $token);

   function put_vehicle_info($vehicle_number, $data, $endpoint, $app_id, $token)
   {
       //Append vehicle number onto the end of the endpoint string for a complete url
       $url = $endpoint.$vehicle_number;  
   
       //Get necessary headers for REST call
       $headers = get_call_headers($app_id, $token);
       
       //convert data to JSON format
       $json_data = json_encode($data);
       
       $session = curl_init($url);                                 //Initialize transfer with URL
       curl_setopt($session, CURLOPT_CUSTOMREQUEST, "PUT");        //Set to PUT transfer request type
       curl_setopt($session, CURLOPT_RETURNTRANSFER, true);        //Return transfer as a string of the return value of curl_exec() 
       curl_setopt($session, CURLOPT_HTTPHEADER, $headers);        //Pass in headers 
       curl_setopt($session, CURLOPT_POSTFIELDS, $json_data);      //Pass in PUT data 
   
       //Execute transfer of $session    
       $response = curl_exec($session); 
       
       //Get http code outcome of the #session transfer    
       $http_code = curl_getinfo($session, CURLINFO_HTTP_CODE);
       
       //Measure false response/error
       if($response === false)
       {
           echo 'Error: '. curl_error($session);
       }
   
       //ALWAYS close transfer connection 
       curl_close($session);
        
       //Evaluate variable for non 204(No Content) http code
       if($http_code !== 204)
       {
           echo 'Error: Http Status Code returned '.$http_code;
       }

       return $response;    
   }
   
   function get_call_headers($app_id, $token)
   {
       //Inserts app_id and token into respective '%s' spaces in the auth header   
       $auth_header = sprintf('Authorization: Atmosphere atmosphere_app_id=%s, Bearer %s', $app_id, $token);
      
       //Create necessary headers for REST call   
       $headers = array();
       $headers[] = $auth_header;  
       //IMPORTANT! - You must use 'Content-Type' as opposed to Accept as you are describing how the info is being sent
       $headers[] = 'Content-Type: application/json'; 
       
       return $headers;
   }
?>

DISCLAIMER

All sample code is provided by Fleetmatics, A Verizon Company, for illustrative purposes only. These examples have not been thoroughly tested under all conditions. Fleetmatics, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. All programs contained herein are provided to you “AS IS” without any warranties of any kind.

The PUT Vehicle method within the Customer Meta Data – Vehicles API enables integrated users to edit the vehicle object details within the referenced REVEAL account.

Before attempting to retrieve vehicle location information it is important to know if the REVEAL account has been updated with valid VEHICLE NUMBERS for each vehicle to be pulled via the API. The VEHICLE NUMBER and VEHICLE NAME fields are different fields within REVEAL and the VEHICLE NUMBER field is not automatically populated upon account creation.

Main Method
public class Program{
  public static void main(String[] args){
    
    // Token call goes here, see TokenGenerator example 
    
    // App Id from Fleetmatics Integration Manager (FIM) 
    String appId = "companyname-p-us-4654sdf4fa351af65dsf1d";        
        
    // Local variables that correspond to Vehicle object in PUT
    String vehicleNum = "0112358";
    String vehicleName = "TESTER";
    String registrationNumber = "GA23423";
    String vin = "1GNDX03E5YD117167";
    String make = "Ford";
    Integer year = 2012;
    String model =  "F150";
    Double tankCapacity = 20.5;	
    Double highwayMPG = 14.5;
    Double cityMPG = 11.5;	
    Integer vehicleSize = 1;
    
    // Put Vehicle URI; vehicle number is appended to the end of the string to complete the URI	
    String putVehicleUri = String.format("https://fim.api.us.fleetmatics.com/cmd/v1/vehicles/%s", vehicleNum);  
	
    // Create new PUT_Vehicle object
    PUT_Vehicle rest_put = new PUT_Vehicle();
    
    // Pass in local variables to create a Vehicle object
    rest_put.CreateNewPutVehicle(vehicleName, vehicleNum, registrationNumber, vin, make, model, year, tankCapacity, highwayMPG, cityMPG, vehicleSize);
    
    // Call method to execute the API call
    rest_put.PutVehicle(/* token auth string passed here */, putVehicleUri, appId);
  }  
}
PUT_Vehicle Class
import java.io.IOException;
import java.io.OutputStream;
import javax.net.ssl.HttpsURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.lang.reflect.*;

public class PUT_Vehicle
{
  private Vehicle _vehicle;
  
  public void PutVehicle(String authString, String putVehicleUri, String appId)
  {   
    try{
      // Construct authentication header for FIM   
      String authHeader = String.format("Atmosphere atmosphere_app_id=%s, Bearer %s", appId, authString);             
      
      // Serialize workorder object into JSON for POST request body     
      String json = DummySerializer(_vehicle);           
      
      URL url = new URL(putVehicleUri);                                        // Create URL object from uri parameter   
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();     // Begin new Https connection       
      conn.setRequestMethod("PUT");                                            // Set REST method to PUT  
      conn.setRequestProperty("Authorization", authHeader);                    // Set Authorization Header   
      conn.setRequestProperty("Content-Type", "application/json");             // Set Content-Type to json 
      conn.setDoOutput(true);                                                  // Allow output to come back in response 
      
      OutputStream os = conn.getOutputStream();   // Create new output stream for body from connection   
      os.write(json.getBytes());                  // Transmit the json workorder object       
      os.close();                                 // Flush and close stream  
      
      // Read response, 204 "no content" evaluation for "success", if not throw exception 
      if (conn.getResponseCode() != HttpsURLConnection.HTTP_NO_CONTENT) {
        throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
      }
      else {
        System.out.println("Vehicle Updated Successfully!");
        _vehicle = null                          // Clear object 
      }
 
      conn.disconnect();                         // End connection to free resources 
      
    } catch (MalformedURLException e) {          // Required Exception 
      e.printStackTrace();
    } catch (IOException e) {                    // Required Exception 
      e.printStackTrace();
    }
  } 
  
  // Public method used to create the Vehicle object which contains.
  // After serialization, this will be used as the body for the PUT command
  public void CreateNewPutVehicle(String name, String number, String registrationNumber, String vin, String make, String model,
                                  Integer year, Double tankCapacity, Double highwayMpg, Double cityMpg, Integer vehicleSize)
  {
    _vehicle = new Vehicle();
    _vehicle.Name = name;
    _vehicle.VehicleNumber = number;
    _vehicle.RegistrationNumber = registrationNumber;
    _vehicle.VIN = vin;
    _vehicle.Make = make;
    _vehicle.Model = model;
    _vehicle.Year = year;
    _vehicle.TankCapacity = tankCapacity;
    _vehicle.HighwayMPG = highwayMpg;
    _vehicle.CityMPG = cityMpg;
    _vehicle.VehicleSize = vehicleSize;
  }
  
  // Serializer - "object to JSON" for Vehicle object
  private String DummySerializer(Object object)
  {    
    try{
      StringBuilder sb = new StringBuilder();
      sb.append("{");                                             // Open parentheses
      
      for (Field field : object.getClass().getDeclaredFields())   // Loop through object
      {
        field.setAccessible(true);                                // Override
        if (field != null && field.getName() != "this$0")         // Skip "this$0" - outer class
        {
          sb.append("\"" + field.getName() + "\" : ");
          sb.append(field.get(object) != null ? ("\"" + field.get(object) + "\"") : "null");   
          sb.append(", ");
        }
      }
      
      sb.setLength(sb.length() - 2);                              // Remove last ", "
      sb.append("}");                                             // Close parentheses
      
      return sb.toString
      
    } catch (IllegalAccessException e) {                          // Required exception
      throw new RuntimeException("Error accessing object value!");
    }
  }
  
  public class Vehicle
  {
    public String VehicleNumber;
    public String Name;
    public String RegistrationNumber;
    public String VIN;
    public String Make;
    public Integer Year;
    public String Model;
    public Double TankCapacity;
    public Double HighwayMPG;
    public Double CityMPG;
    public Integer VehicleSize;
  }
}

DISCLAIMER

All sample code is provided by Fleetmatics, A Verizon Company, for illustrative purposes only. These examples have not been thoroughly tested under all conditions. Fleetmatics, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. All programs contained herein are provided to you “AS IS” without any warranties of any kind.

The PUT Vehicle method within the Customer Meta Data – Vehicles API enables integrated users to edit the vehicle object details within the referenced REVEAL account.

Before attempting to retrieve vehicle location information it is important to know if the REVEAL account has been updated with valid VEHICLE NUMBERS for each vehicle to be pulled via the API. The VEHICLE NUMBER and VEHICLE NAME fields are different fields within REVEAL and the VEHICLE NUMBER field is not automatically populated upon account creation.

Main Method
namespace Rest_Put_Vehicle_Example
{
    class Program
    {
        static void Main()
        {
            // Token call goes here, see Rest_Token_Example

            // App Id from Fleetmatics Integration Manager (FIM)
            string appId = "companyname-p-us-4654sdf4fa351af65dsf1d";

            // Put Vehicle URI
            string putVehicleUri = "https://fim.api.us.fleetmatics.com/cmd/v1/vehicles/";

            // Local variables that correspond to put body fields
            string vehicleNum = "0112358";
            string vehicleName = "TESTER";
            string registrationNumber = "GA23423";
            string vin = "1GNDX03E5YD117167";
            string make = "Ford";
            string model = "F150";
            int? year = 2012;
            double? tankCapacity = 20.5;
            double? highwayMPG = 14.5;
            double? cityMPG = 11.5;
            int? vehicleSize = 1;

            // Create new PUT_Vehicle object
            var rest_put = new PUT_Vehicle();

            // Pass in local variables to create a vehicle object
            rest_put.CreateNewPutVehicle(vehicleName, vehicleNum, registrationNumber, vin, make, model, year, tankCapacity, highwayMPG, cityMPG, vehicleSize);

            // Call method to execute the API call
            rest_put.PutVehicle(/* token object or auth string passed here */, putVehicleUri, appId);
        }
    }
}
PUT_Vehicle Class
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Script.Serialization;

namespace Rest_Post_WorkOrder_Example
{
    public class POST_WorkOrder
    {
         private WorkOrder _workOrder { get; set; }

         public void PostWorkOrder(/* token object or auth string passed here */, string postWorkOrderUri, string appId)
         {
            // Construct authentication header for FIM
            string authHeader = string.Format("Atmosphere atmosphere_app_id={0}, Bearer {1}", appId, /* token authentication string goes here */);

	    // Serialize workorder object into JSON for POST body
            string workOrderContent = new JavaScriptSerializer().Serialize(_workOrder);

	    // Create the body, pass in serialized data and set content type
            string bodyContent = new StringContent(workOrderContent, Encoding.UTF8, "application/json");

            // Begin new HttpClient. Use "using" to ensure the resource is released
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authHeader);     // Pass in FIM auth header

                // Pass in URI, supply bodyContent, and execute REST POST
                using(HttpResponseMessage response = client.PostAsync(postWorkOrderUri, bodyContent).Result)
                (
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);       // Logging
                    Console.WriteLine(response.Content.ReadAsStringAsync().Result);                        // Read result from response

                    // True if HttpStatusCode was in the successful range (200-299); otherwise false
                    if (response.IsSuccessStatusCode)
                    {
                        _workOrder = null;                                         // Clear workorder object
                        return;
                    }

                    // If this is reached, the call has failed
                    switch (response.StatusCode)
                    {
                        case HttpStatusCode.Unauthorized:
                            // Optional token renewal here, see Rest_Token_Example
                        break;
                        /*
                          ... Other cases here
                        */
                    default:
                        // Take another action
                        break;
                }
            }
        }

        // Public method used to create the workorder object which contains a nested Address object.
        // After serialization, this will be used as the body for the POST command
        public void CreateWorkOrder(string actualDateUtc, int? actualDurationSecs, string addressLine1, string addressLine2, string locality, string administrativeArea,
                                    string postalCode, string country, string clientCustomerId, string description, string driverNumber, double latitude, double longitude,
                                    int? onSiteDurationSecs, double radiusInKM, string scheduledDateUtc, int? scheduledDurationSecs, string statusChangeDateUtc,
                                    string workOrderNumber, string statusCode, string typeCode)
        {
            _workOrder = new WorkOrder
            {
                ActualDateUtc = actualDateUtc,
                ActualDurationSeconds = actualDurationSecs,
                Address = new Address
                {
                    AddressLine1 = addressLine1,
                    AddressLine2 = addressLine2,
                    Locality = locality,
                    AdministrativeArea = administrativeArea,
                    PostalCode = postalCode,
                    Country = country,
                },
                ClientCustomerId = clientCustomerId,
                Description = description,
                DriverNumber = driverNumber,
                Latitude = latitude,
                Longitude = longitude,
                OnSiteDurationSecs = onSiteDurationSecs,
                RadiusInKM = radiusInKM,
                ScheduledDateUtc = scheduledDateUtc,
                ScheduledDurationSecs = scheduledDurationSecs,
                StatusChangeDateUtc = statusChangeDateUtc,
                WorkOrderNumber = workOrderNumber,
                WorkOrderStatusCode = statusCode,
                WorkOrderTypeCode = typeCode,
            };
        }
    }

    public class WorkOrder
    {
         public string ActualDateUtc { get; set; }
         public int? ActualDurationSeconds { get; set; }
         public Address Address { get; set; }
         public string ClientCustomerId { get; set; }
         public string Description { get; set; }
         public string DriverNumber { get; set; }
         public double Latitude { get; set; }
         public double Longitude { get; set; }
         public int? OnSiteDurationSecs { get; set; }
         public double RadiusInKM { get; set; }
         public string ScheduledDateUtc { get; set; }
         public int? ScheduledDurationSecs { get; set; }
         public string StatusChangeDateUtc { get; set; }
         public string WorkOrderNumber { get; set; }
         public string WorkOrderStatusCode { get; set; }
         public string WorkOrderTypeCode { get; set; }
    }

    public class Address
    {
         public string AddressLine1 { get; set; }
         public string AddressLine2 { get; set; }
         public string Locality { get; set; }
         public string AdministrativeArea { get; set; }
         public string PostalCode { get; set; }
         public string Country { get; set; }
    }
}

DISCLAIMER

All sample code is provided by Fleetmatics, A Verizon Company, for illustrative purposes only. These examples have not been thoroughly tested under all conditions. Fleetmatics, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. All programs contained herein are provided to you “AS IS” without any warranties of any kind.

Microsoft Visual Studio

To open and use the zipped Visual Studio projects, you will need a copy of Microsoft Visual Studio. Unzip the file and click on the Visual Studio solution file to begin, after the above requirements have been met.

Xamarin Interactive Workbooks

Xamarin Workbooks provide a blend of documentation and code that is perfect for experimentation, learning, and creating code. To be able to view the interactive workbooks provided by Fleetmatics, please check the specific requirements for your OS and install Xamarin Workbooks, here.