Skip to content

Instantly share code, notes, and snippets.

@djryanash
Created May 12, 2023 09:35
Show Gist options
  • Save djryanash/1ec7fb879c3e3b9bebe4054d54be6f00 to your computer and use it in GitHub Desktop.
Save djryanash/1ec7fb879c3e3b9bebe4054d54be6f00 to your computer and use it in GitHub Desktop.
Testing a REST API POST Request
class AnyClass {
func restApiPostRequest() {
let url = URL(string: "https://reqres.in/api/users")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let userData = ["name": "John", "position": "Software Engineer", "age": "37"]
do { let jsonData = try JSONSerialization.data(withJSONObject: userData, options: .prettyPrinted)
request.httpBody = jsonData }
catch { print("Error: \(error)") }
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data, let response else { fatalError("There is no valid data.") }
print("Data: \(data)")
print("Response: \(response)")
if let error { fatalError("Error: \(error)")} }
task.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment