0

so I have been using requests in python to make an api call and currently use it in this way:

import requests

data = {"tag":"hello","value":"ayush"}
r = requests.post('MY URl', data)

and now I want to implement the same kind of post api call in swift,(in the shortest and easiest way possible)so can you please help

2 Answers2

1

The easiest way would be to use Alamofire: POST request with a simple string in body with Alamofire - but this will require an additional library in your project

You could also do it "by hand" with internal frameworks provided by Apple, via URLRequest / URLSession: HTTP Request in Swift with POST method

Community
  • 1
  • 1
Andreas Oetjen
  • 9,889
  • 1
  • 24
  • 34
0

You asked fast and easy, this just fires and forgets. If you want to handle the response see HTTP Request in Swift with POST method suggested above by Andreas. For an elegant approach check out Swift Talk Networking: POST Requests (these discussions are excellent).

If you're using HTTP vs. HTTPS you have to set the project's Info.plist NSAppTransportSecurity property Allow Arbitrary Loads to true.

    let url = URL(string: "http://yourdomain.com")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = "{\"tag\":\"hello\",\"value\":\"ayush\"}".data(using: .utf8)
    URLSession.shared.dataTask(with: request).resume()
Community
  • 1
  • 1
Norman
  • 3,020
  • 22
  • 21