Search code examples
jsonapihttpjuliapycall

Post API in Julia when the input is a JSON


I'm trying to access the TexSmart HTTP API https://ai.tencent.com/ailab/nlp/texsmart/en/api.html , where the input text is a dictionary matching the following structure:

Dict("str" => "text you want to analyze",
     "options"=> Dict(      "input_spec"=>Dict("lang"=>"auto"),
                              "word_seg"=>Dict("enable"=>true),
                           "pos_tagging"=>Dict("enable"=>true,
                                          "alg"=>"log_linear"),
                                   "ner"=>Dict("enable"=>true,
                                          "alg"=>"fine.std"),
                     "syntactic_parsing"=>Dict("enable"=>false),
                                   "srl"=>Dict("enable"=>false)),
      "echo_data"=>Dict("request_id"=>12345)
                     )

The "options" and "echo_data" fields are optional and probably not crucial to my implementation, so feel free to leave them out of your answer.

How would I submit this in a HTTP.request?


Based on the Python example on the API page, I tried this:

HTTP.request("POST", "https://texsmart.qq.com/api", 
[codeunits(json(Dict("str"=>"He stayed in San Francisco.")))])

I didn't receive a response, and I'm not sure why. Here's the Python example in the API's documentation:

import json
import requests
obj = {"str": "he stayed in San Francisco."}
req_str = json.dumps(obj).encode()
url = "https://texsmart.qq.com/api"
r = requests.post(url, data=req_str)
r.encoding = "utf-8"
print(r.text)

Since the json.dumps().encode() function returns bytes, I thought that codeunits() wrapping a json representation of the input string would do the trick, but still nothing. I don't receive an error, just a Response with content length 0.


Note: If someone knows a way to do this with PyCall or ccall(), that answer would also work for me!


Solution

  • The following should work:

    import HTTP, JSON
    HTTP.request(
        "POST",
        "https://texsmart.qq.com/api",
        [],
        JSON.json(Dict("str"=>"He stayed in San Francisco."))
    )
    

    In particular:

    • The third argument to HTTP.request are the request headers, not body, so you need to pass an empty array there.
    • codeunits is unnecessary, since HTTP.request happily accepts a string too.