Insert a comment using the YouTube API and Alamofire
Asked Answered
S

2

6

I'm confused on how to insert a comment using the YouTube API. I'm fairly new to using APIs, so I don't quite get what they are saying to do in their documentation.

I've authenticated the user using Google Sign-In for iOS with the scope

"https://www.googleapis.com/auth/youtube.force-ssl"

which is required to insert a comment. But now, I have to actually insert the comment and (like I've said) I don't understand how to do that because I have to provide a resource in the request body. I'm using Alamofire for the request and Swift 4 as my language.

Skantze answered 18/5, 2018 at 13:19 Comment(9)
Did you try this lib? github.com/google/google-api-objectivec-client-for-restFournier
In the sample project they add a comment, here: github.com/google/google-api-objectivec-client-for-rest/blob/…Fournier
@BencePattogato Do you know if there is one in Swift? I don't understand objective c lolSkantze
@JacobCavin You can use Objective-C libraries from Swift without having to know Objective-C. Search for "bridging header". It's easy to use.Regelation
@Moritz It doesn't look as if this code actually has the ability to insert a comment. The function that Bence lead me to is actually just updating a video's thumbnail.Skantze
@BencePattogato It looks like they are not inserting a comment, but actually just updating the thumbnail for a videoSkantze
I found the wrapper: namely GTLRYouTubeQuery_CommentsInsert . See: github.com/google/google-api-objectivec-client-for-rest/blob/…Gibeon
@JacobCavin have you written any code so far, for sending API call to insert comment?Labanna
@Labanna I don't understand how to do it. It says that I need to add data to the Request body (as seen in the documentation I was talking about), but I don't know how to do that. Like I said, I'm very new to using APIs. Thanks for helping me. I've been trying to figure this out for a while, now.Skantze
A
1

As I saw in your other post (Google API - Invalid Credentials) you know how to make an authenticated Alamofire request. Now you need to build a proper parameters dictionary to meet the API requirements. I looked into the Youtube Data API guide.

This is the example of a JSON body provided in the documentation for adding a comment:

{
  "snippet": {
   "channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
   "topLevelComment": {
    "snippet": {
      "textOriginal": "This video is awesome!"
    }
   },
   "videoId": "MILSirUni5E"
  }
 }

Let's build a parameters dictionary based on the above example, it is a nested dictionary:

let commentParams: Parameters = ["textOriginal": "This video is awesome!"]
let snippetParams: Parameters = ["snippet": commentParams]
let topLevelSnippet: Parameters = [
        "channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
        "topLevelComment": snippetParams,
        "videoId": "MILSirUni5E"]

let allParams: Parameters = ["snippet": topLevelSnippet]

Then create your headers, your request and pass the parameters to the request

let headers: HTTPHeaders = ["Authorization": "Bearer \(token)"]
// As API requires "part" is added as url parameter
let path = "https://www.googleapis.com/youtube/v3/commentThreads?part=snippet"
let request = Alamofire.request(path, method: HTTPMethod.post, parameters: allParams, encoding: JSONEncoding.default, headers: headers)

You should check which parameters are mandatory and which ones are not, but the idea is to build a proper parameters dictionary based on their requirements.

Aestheticism answered 28/5, 2018 at 15:2 Comment(12)
Thank you for answering, yet again. You've been the best person I've met on Stack Overflow. I'm getting the error: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})) Any ideas?Skantze
This often happens when the response is not a valid json. Some services throw unreadable errors, but I doubt Google would give such response. Are you using some kind of object mapper made for Alamofire such as SwiftyJSON? It also can happen when a wrong url is called and the service doesn’t know what the request means, thus no proper response. I will check at home if the url is correct again.Aestheticism
Thank you. I copied your code exactly except I changed the channelId and videoId. I am using AlamofireSkantze
@JacobCavin I have corrected the url. It was not necessary to include insert in the url, that is implied by the HTTP method (post). You can read in the docs about the difference between comments and commentThreads methods and decide which one is relevant to you. You should be getting some kind of response from google now.Aestheticism
Thanks again. Haha. I keep on saying that. I'm getting an error from Google, now. Thanks for being so patient. SUCCESS: { error = { code = 400; errors = ( { domain = "youtube.commentThread"; location = "body.snippet.topLevelComment.snippet.textOriginal"; locationType = other; message = "Comments cannot be empty."; reason = commentTextRequired; } ); message = "Comments cannot be empty."; }; }Skantze
Not sure what's wrong here, the error states that textOriginal has no value, but my example includes a string "This video is awesome!". Are you sure you've copied the dictionary correctly?Aestheticism
Let us continue this discussion in chat.Skantze
I figured it out. Instead of "topLevelComment": toplevelCommetParams, in the topLevelSnippet parameter, I needed to have "topLevelComment": snippetParams,Skantze
My bad, I missed that one. Built the dictionary without testing it. I accepted your edit. But glad that finally it worked for you.Aestheticism
Thank you again for all your help!Skantze
Sure, no problem.Aestheticism
I am facing same issue. How & where Can I get "Bearer (token)" ?Ransdell
C
0

Instead build your parameter dictionary like this:

        let allParams: [String: Any] = [
            "snippet" : [
                "channelId" : "UC_x5XG1OV2P6uZZ5FSM9Ttw",
                "topLevelComment" : [
                    "snippet" : [
                        "textOriginal" : "this video is awesome",
                    ],
                    "videoId" : "MILSirUni5E",
                ]
             ]
        ]

Chortle answered 3/8, 2021 at 22:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.