Link to home
Start Free TrialLog in
Avatar of Mewan Chathuranga
Mewan Chathuranga

asked on

Request error Google Cloud NLP API with Swift

I am trying to make a request to Google Cloud NLP API to obtain sentiment analysis for a piece of text. I used Postman to design the correct request, and I was able to get a valid response using Postman. However, when I try to make the same request from Swift, it gives me an error. The error and code snippet used to make the request is shown below.

func sendAPIRequest(with text: String){

    print("Text: ", text)
    let jsonRequest = [
        [
        "document":[
            "type":"PLAIN_TEXT",
            "language": "EN",
            "content":"'Lawrence of Arabia' is a highly rated film biography about British Lieutenant T. E. Lawrence. Peter O'Toole plays Lawrence in the film."
        ],
        "encodingType":"UTF8"
    ]
        ]

    let jsonObject = JSON(jsonRequest)


    let headers: HTTPHeaders = [
        "X-Ios-Bundle-Identifier": "\(Bundle.main.bundleIdentifier ?? "") ",
        "Content-Type": "application/json"
    ]
    let APIRequest = Alamofire.request("https://language.googleapis.com/v1/documents:analyzeSentiment?key=\(gCloudAPIKey)", method: .post , parameters: jsonRequest as? [String: Any], encoding: JSONEncoding.default , headers: headers).responseJSON { (response) in
        print(response)
        if let json = response.result.value {
            print("JSON: \(json)")
        }
    }

Open in new window


Error:
JSON: {
error =     {
    code = 400;
    details =         (
                    {
            "@type" = "type.googleapis.com/google.rpc.BadRequest";
            fieldViolations =                 (
                                    {
                    description = "Must have some text content to annotate.";
                    field = "document.content";
                }
            );
        }
    );
    message = "One of content, or gcs_content_uri must be set.";
    status = "INVALID_ARGUMENT";
};
}

Open in new window

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.