Pastebin API not working with Swift 4 requests

196 views Asked by At

I'm writing some code to hit the Pastebin API and keep getting this issue:

Bad API request, use POST request, not GET

I've tried a whole bunch of things and can't get it working. When I use cURL things work fine, but in my Swift app the call fails.

    func postPasteRequest(urlEscapedContent: String, callback: @escaping (String) -> ()) {
        var request = URLRequest(url: URL(string: "http://pastebin.com/api/api_post.php")!)
        request.httpMethod = "POST"
        let postString = "api_paste_code=\(urlEscapedContent)&api_dev_key=\(API_KEY)&api_option=paste&api_paste_private=1&api_paste_expire_date=N"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil
                // check for fundamental networking error
                else {
                    NSLog("error=\(String(describing: error))")
                    return
            }
            
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                NSLog("statusCode should be 200, but is \(httpStatus.statusCode)")
                NSLog("response = \(String(describing: response))")
            }
            
            let responseString = String(data: data, encoding: .utf8)
...
    }
task.resume()
}
1

There are 1 answers

2
TheAlienMann On

Add task.resume() after the closing curly braces of dataTask method. btw, the pastebin has a pretty detailed method in Swift, on how to get data.

here, you can find a call to that API in swift.

// Vladimir Zhelnov - neatek.pw - Web/iOS dev
class Class_JSONRequest {    
    func get_url_post(get_url: String, params: String, completion: @escaping (_ result: NSDictionary) -> Void) {
        let myUrl = URL(string: get_url);
        var request = URLRequest(url:myUrl!)
        request.httpMethod = "POST"
        let postString = params;
        request.httpBody = postString.data(using: String.Encoding.utf8);
        let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
            if error != nil
            {
                print("error=\(error)")
                return
            }
            do {
                if(data != nil) {
                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                    if let parseJSON = json {
                        //print(parseJSON)
                        completion(parseJSON)
                    }
                }
            } catch {
                print(error)
            }
        }
        task.resume()
    }
}
/* usage:
let post_params = "some=post&params=1";
JSON.get_url_post(get_url: "http://..api", params: post_params , completion: { answer in
    ... something
});
*/