Created
May 12, 2023 09:35
-
-
Save djryanash/1ec7fb879c3e3b9bebe4054d54be6f00 to your computer and use it in GitHub Desktop.
Testing a REST API POST Request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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