0

I would like to use the Firestore REST API from Swift, because I am using Siri Shortcut Intents, where I am not able to use the native SDK.

What I have tried so far is to create an URLSession with "POST" httpmethod, but no luck. I have been able successfully to create document to use the form found on firestore website. But I could make successful Swift version of it.

Here is the code I have tried:

private func addTask() {

    let parent = "projects/reality-kanban/databases/(default)/documents/l3VXrtTLoz11VGn60ott"
    let collectionId = "A33XrtfL2ea3dG340era"
    let urlString = "https://firestore.googleapis.com/v1/\(parent)/\(collectionId)"
    let requestBody = DocumentBody(name: parent, fields: RequestTask(description: "test")) // it is a codable struct

    let jsonData = try! JSONEncoder().encode(requestBody)
    print(String(data: jsonData, encoding: .utf8)!)

    let url = URL(string: urlString)!

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = jsonData

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
            print("Invalid Response received from the server") // this is what I get
            return
        }
    }

    task.resume()

}

This is the error I get: Invalid Response received from the server (400)

Viktor Maric
  • 443
  • 1
  • 4
  • 10
  • 1
    Pleas add the code of what you have tried so far? What errors do you get? Where exactly do you struggle? This question is to broad and missing vital debugging information. – burnsi Jul 12 '22 at 14:58
  • Try to print the status code received from the server. This would at least give you a hint in what direction to go. – burnsi Jul 12 '22 at 21:06
  • It is: 404 This is how the firestore documentation suggest using the url: POST https://firestore.googleapis.com/v1/{parent=projects/*/databases/*/documents/**}/{collectionId} – Viktor Maric Jul 12 '22 at 21:31
  • And you are sure `projects/reality-kanban/databases/(default)/documents/l3VXrtTLoz11VGn60ott` will give you a valid link? The brackets seem not valid. – burnsi Jul 12 '22 at 21:35
  • I have updated the url, now I get status with 400. – Viktor Maric Jul 12 '22 at 21:38
  • Could you add `--debug` to the command you are running and share the output? Maybe some of your settings are mismatching, [ie the project ID](https://stackoverflow.com/questions/58514630/why-does-firebase-serve-error-with-http-error-400-request-contains-an-inval/58530651#58530651). – Andrés Jul 14 '22 at 17:40

1 Answers1

0

Add --debug to the command you are running to corroborate if you have set the right project.

Andrés
  • 487
  • 1
  • 12