Learn Courses My Dashboard

Alamofire + POST + JSONBin.io response is success but Invalid JSON

I am trying to upload a simple JSON to JSONBin.io API
using Alamofire

Using third party app, I can post the same simple data

I’m not sure what this means, what third party app? Like Postman?

Also I would hide your master key, that may be secret and you shouldn’t post it on a forum

Is params the JSON body that you’re trying to send?

I haven’t used Alamofire, but you could accomplish this with URLSession and not need a third party framework

I was not able to fix the issue as I switch to different JSON storage API
But I encountered same issue when using the new JSON storage API as what I encounter in JSONBin.io

To fix it I used something like this:

let ord = Orders(name: "KareKare", price: "500")
        guard let encoded = try? JSONEncoder().encode(ord) else {
            print("Failed to encode order")
            return
        }
        
        let url = URL(string: "https://api.vultr.com/v2/object-storage")!
        var request = URLRequest(url: url)
        request.setValue("Bearer XXXXXXXXXXXXXXX", forHTTPHeaderField: "Authorization")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        
        let task = URLSession.shared.uploadTask(with: request, from: encoded) { data, response, error in
            
            if let error = error {
                    print ("error: \(error)")
                    return
                }
                guard let response = response as? HTTPURLResponse,
                    (200...299).contains(response.statusCode) else {
                    print ("server error: \(response)" )
                    return
                }
                if let mimeType = response.mimeType,
                    mimeType == "application/json",
                    let data = data,
                    let dataString = String(data: data, encoding: .utf8) {
                    print ("got data: \(dataString)")
                }
            
        }
        task.resume()