Search code examples
4d-database

How do I make a HTTP request in 4D v12 database


My 4D database has a method that calls an external application to make an HTTP request to an API site, e.g. https://somewhere.com/api/?key=somekey&param=someparam. The request returns a JSON response. However, the external application only returns a call success or fail. I am not able to extract the JSON response.

My 4D database is still in version 12 and have no plans to migrate yet to latest version. Is there any way for me to make an HTTP request and get the JSON response? I was thinking of using the built-in PHP engine and make cURL call. Has anybody done this in 4D?


Solution

  • I recommend using Keisuke Miyako's OAuth plugin. https://github.com/miyako/4d-plugin-oauth. It comes with a cURL library and a JSON parsing library. I use it to pull JSON data from an api source. It looks like he's depricated the plug-in but has links to the separate components.

    http://sources.4d.com/trac/4d_keisuke/wiki/Plugins/

    ARRAY LONGINT($optionNames;0)
    ARRAY TEXT($optionValues;0)
    C_BLOB($inData;$outData)
    
    $url:="https://api.atsomewhere.com/blahblah"
    $error:=cURL ($url;$optionNames;$optionValues;$inData;$outData)
    
    If ($error=0)
      $jsonText:=BLOB to text($outData;UTF8 text without length)
    
      $root:=JSON Parse text ($jsonText)
    
      JSON GET CHILD NODES ($root;$nodes;$types;$names)
    
      $node:=JSON Get child by name ($root;"Success";JSON_CASE_INSENSITIVE)
      $status:=JSON Get bool ($node)
    
      If ($status=1)
       $ResponseRoot:=JSON Get child by name ($root;"Response";JSON_CASE_INSENSITIVE)
    
       $node1:=JSON Get child by name ($ResponseRoot;"SourceId";JSON_CASE_INSENSITIVE)
       $node2:=JSON Get child by name ($ResponseRoot;"SourceName";JSON_CASE_INSENSITIVE)
    
       $output1:=JSON Get text ($node1)
       $output2:=JSON Get text ($node2)
    
    End if 
    

    End if