Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the JSON body with POST request in moya

Tags:

ios

swift

moya

I'm using the moya library to make a POST request. In TargetType, I couldn't able to see any property to pass the parameters[JSON body] along with POST request. Here, I attach the TargetType

public protocol TargetType {

    /// The target's base `URL`.
    var baseURL: URL { get }

    /// The path to be appended to `baseURL` to form the full `URL`.
    var path: String { get }

    /// The HTTP method used in the request.
    var method: Moya.Method { get }

    /// Provides stub data for use in testing.
    var sampleData: Data { get }

    /// The type of HTTP task to be performed.
    var task: Task { get }

    /// Whether or not to perform Alamofire validation. Defaults to `false`.
    var validate: Bool { get }

    /// The headers to be used in the request.
    var headers: [String: String]? { get }
}

public extension TargetType {
    var validate: Bool {
        return false
    }
}
like image 608
sathish Avatar asked Jan 21 '18 16:01

sathish


People also ask

What is request body in JSON?

A request body is data sent by the client to your API. A response body is the data your API sends to the client.


1 Answers

Finally,I got the solution for my problem. In Moya 10.0, we can pass the http body JSON payload in task property [TargetType].

click here for reference

var task: Task {
    switch self {
    case .zen, .showUser, .showAccounts: // Send no parameters
        return .requestPlain
    case let .updateUser(_, firstName, lastName):  // Always sends parameters in URL, regardless of which HTTP method is used
        return .requestParameters(parameters: ["first_name": firstName, "last_name": lastName], encoding: URLEncoding.queryString)
    case let .createUser(firstName, lastName): // Always send parameters as JSON in request body
        return .requestParameters(parameters: ["first_name": firstName, "last_name": lastName], encoding: JSONEncoding.default)
    }
}
like image 186
sathish Avatar answered Sep 18 '22 18:09

sathish