• User Guide
  • Calculation
  • Automation
  • Web API
  • Validation
  • Contact Us
Search Results for

    Show / Hide Table of Contents
    • Introduction
      • Acquiring your API token
      • Endpoints on API website
      • View API schema
      • SolarFarmer API versions
    • –––––––––––––––––––
    • Endpoints
      • 'About' endpoint
      • 'SolarPosition' endpoint
      • 'ModelChain' endpoint
      • 'ModelChainAsync' endpoint
      • 'Service' endpoint
      • 'TerminateModelChainAsync' endpoint
    • Tutorials
      • Introduction
      • Python environment
      • Generate input files from desktop
      • 'About' endpoint tutorial
      • 'SolarPosition' endpoint tutorial
      • 'ModelChain' endpoint tutorial
      • 'ModelChainAsync' endpoint tutorial
      • 'Service' endpoint tutorial
      • 'TerminateModelChainAsync' endpoint tutorial
    • –––––––––––––––––––
    • Troubleshooting
      • Common Problems
      • Validation Service
    • API Class References
      • SolarFarmerApi.Client
        • AnnualEnergyYieldResults
        • DiffuseModel
        • EnergyCalculationInputs
        • EnergyCalculationOptions
        • EnergyYieldResults
        • EnergyYieldResultsForMonth
        • EnumTechnology
        • IAMModelType
        • IAMModelTypeForOverride
        • IAMParameters
        • IndexedObject3D
        • Inverter
        • InverterEfficiencyModelType
        • InverterEfficiencyPoints
        • InverterInput
        • InverterSpecification
        • Layout
        • Location
        • LossTreeEffects
        • LossTreeEntry
        • LossTreeResultForMonth
        • MeteorologicalCondition
        • MeteorologicalConditionsDataset
        • MiniSimpleTerrainDto
        • MissingMetDataMethod
        • ModelChainAsyncQueryResponse
        • ModelChainResponse
        • ModuleGeometry
        • ModuleIndexRange
        • ModuleSpecification
        • ModuleString
        • MountingTypeSpecification
        • MpptLimits
        • PanFileSupplements
        • PointInLossChain
        • ProblemDetails
        • PVPlant
        • PVsystDiodeModelParameters
        • QuadDouble
        • Rack
        • Response
        • Response2
        • Response3
        • RuntimeStatus
        • SimpleTerrainDto
        • SolarPositionDto
        • SolarPositionRequest
        • SolarPositions
        • SystemAttributes
        • TerrainRowDto
        • TerrainRowStartEndColumnsDto
        • ThreeEfficiencyCurves
        • Tracker
        • TrackerSystem
        • Transformer
        • TransformerLossModelTypes
        • TransformerSpecification
        • Vector3Double
    • Release Notes
      • API v2 (2.0.2) (7 September 2023)
      • API v1 (0.2.254) (11 April 2023)
      • API 0.2.249 (22 November 2022)
      • API 0.2.242 (28 July 2022)
      • API 0.2.223 (3 March 2022)
      • API 0.2.64 (23 August 2021)
      • API 0.2.51 (2 June 2021)

    The TerminateModelChainAsync Endpoint Tutorial

    Note

    This tutorial assumes you have already set up a Python environment on your machine. If not, see Setting up a Python Environment for help on how to set this up.

    Definition

    See the TerminateModelChainAsync Endpoint for a definition of this endpoint.

    Tutorial

    This is some sample code to use the TerminateModelChainAsync endpoint to terminate a running calculation started with the ModelChainAsync endpoint.

    1. Create a new empty folder

    2. Create an empty text file in that folder and copy and paste the following Python code into the file and save it as a Python file (e.g. as "TerminateModelChainAsyncEndpointTutorial.py").

    #! python
    """
    Example script to use the 'TerminateModelChainAsync' endpoint to terminate a running 
    calculation that was initiated with a call to the 'ModelChainAsync' endpoint.
    """
    
    # import external libraries
    from http import HTTPStatus
    import requests   # to send the request to SF-API and get the response
    
    sf_web_api_url = 'https://solarfarmer.dnv.com/api'
    api_token = 'ENTER YOUR API TOKEN HERE!!!'
    instance_id = 'ENTER THE INSTANCE ID HERE!!!'
    reason = 'Calculation not finishing'
    
    # Set up the API url to call 
    terminate_url = sf_web_api_url + '/TerminateModelChainAsync'
    try:
        # Set up the headers for the POST API request - setting the API token and content type
        headers = {
            'Authorization': f'Bearer {api_token}',
            'ContentType': 'application/json'}
    
        # Call the POST request to the API
        print(f'Sending POST request to {terminate_url} with instanceId of {instance_id}')
        response = requests.post(
            terminate_url,
            headers = headers,
            params={
                "instanceId": instance_id,
                "reason": reason})
    
        # Handle the response that is returned
        if (response.ok):
            print(f'Status code {response.status_code} ({HTTPStatus(response.status_code).name}) returned')
        else:
            print(f"API request {terminate_url} failed.")
    
        # check for any status >400 and print out the reason and text as these can be useful
        if (response.status_code == 401):
            # Unauthorized - API token not valid or out of date
            print(f"Your API token is not valid for the web API url {sf_web_api_url}.")
        elif (response.status_code >= 400):
            print(f"Error status code: {response.status_code}\n" +
                f"Reason: {response.reason}\n" + f"Message: {response.text}")
    
    except Exception as exc:
        print(f"Exception thrown when calling {terminate_url}")
        print(str(exc))
    
    1. Replace the text 'ENTER YOUR API TOKEN HERE!!!' with your personal API token (encase it in single quotes)

    2. Kick off a calculation using the ModelChainAsync endpoint. This should provide you with an instance ID string in the output (if you use the script in the ModelChain Endpoint Tutorial).

    3. Replace the text 'ENTER THE INSTANCE ID HERE!!!' with the instance ID of the calculation that you wish to terminate (encase it in single quotes)

    4. Update the reason string - not critical but can help us understand why calculations are being terminated

    5. Open a command prompt in the folder that contains "TerminateModelChainAsyncEndpointTutorial.py"

    6. Type python TerminateModelChainAsyncEndpointTutorial.py and hit Return to run the script.

    7. It should return very quickly, giving some output similar to the following (it will be a different instanceId!):

    Sending POST request to https://solarfarmer.dnv.com/api/TerminateModelChainAsync with instanceId of 45f95656759b49ba82cb21f7df7cd9a2
    Status code 202 (ACCEPTED) returned
    
    In This Article
    Back to top DNV SolarFarmer Home