API Connect

 View Only

Complex JSON object in API string

  • 1.  Complex JSON object in API string

    Posted 29 days ago

    in Postman i have a API call running 
    /ByRecordType/REP?tsGenListViewParams={"tsDisplayType":"dtList","tsParentId":5909237214,"tsProjects":"5909236975","tsEtpIds":"790", "fields":"id,name,description"}

    This returns some records from the database

    Now i am trying to create this in an automation script

    # imports bibliotheken
    from com.ibm.json.java import JSONObject
     
    from java.text import SimpleDateFormat
    from java.util import Date, Properties, List, ArrayList
    from sys import *
    from psdi.iface.router import HTTPHandler
    from java.util import HashMap
    from psdi.webclient.system.controller import SessionContext, Utility, WebClientEvent
    from psdi.common.context import UIContext
    from psdi.server import MXServer
    from psdi.util.logging import MXLoggerFactory
    from java.net import URL
    from java.io import BufferedReader, InputStreamReader, OutputStreamWriter
    from java.lang import StringBuffer
     
    ## serialiser
    def dict_to_json(data):
        """
        Eenvoudige JSON-serializer voor dictionaries.
        """
        import re
        json_string = '{' + ', '.join(
            '"{}": {}'.format(k, '"{}"'.format(v) if isinstance(v, str) else v)
            for k, v in data.items()
        ) + '}'
        return json_string
     
     
    # start logging
    myLogger = MXLoggerFactory.getLogger("maximo.script.customscript")
    myLogger.error("##### Start ")
     
    # 1. Bouw de complexe JSON-string op
    json_data = {
        "tsDisplayType": "dtList",
        "tsProjects": "5909236975",
        "tsFilterType": "ftFilterCondition",
        "tsFilterValue": "\"ID\" IN LIST \"BB-15583\"",
        "fields": "id,name,description"
    }
     
    # 2. Serialiseer de JSON-string
    json_string = dict_to_json(json_data)
     
    # 3. Maak de headers inclusief de complexe JSON-string
    headers = {
        "Authorization": "Basic {passkey}",
        "tsGenListViewParams": json_string
    }
     
    # 4. Stuur een HTTP-verzoek (Maximo ingebouwde HTTP-handler)
    endpoint = "https://endpoint.nl/rest/ttmrestsrv.dll/2.0/ByRecordType/REP"
     
    #try:
    if 1:    
        url = URL(endpoint)
        conn = url.openConnection()
        conn.setRequestMethod("GET")
        conn.setRequestProperty("Authorization", headers["Authorization"])
        conn.setRequestProperty("tsGenListViewParams", headers["tsGenListViewParams"])
        
        # Optioneel: voeg meer headers toe
        conn.setRequestProperty("Content-Type", "application/json")
     
        # Verwerk de response
        response_code = conn.getResponseCode()
        if response_code == 200:
            reader = BufferedReader(InputStreamReader(conn.getInputStream()))
            response = ""
            line = reader.readLine()
            while line is not None:
                response += line
                line = reader.readLine()
            reader.close()
            myLogger.error("### Response: %s" % response)
        else:
            myLogger.error("### Error Response Code: %s" % response_code)


    This gives me the same error as it gives in Curl, and in my opinion this has something to do with the JSON string

    error":"Cannot fetch records, unable to parse request string for tsGenListViewParams." 

    how to include the key tsGenListViewParams={"tsDisplayType":"dtList","tsParentId":5909237214,"tsProjects":"5909236975","tsEtpIds":"790", "fields":"id,name,description"} into my API call?



    ------------------------------
    Jan-Willem Steenbergen
    ------------------------------