如何在Vapor 3中进行第三方api通话?

问题描述 投票:2回答:1

我想在Vapor 3中使用一些参数进行调用。

POST: http://www.example.com/example/post/request

title: How to make api call
year: 2019

可以使用哪个包/功能?

swift api vapor
1个回答
5
投票

这很简单,你可以像这样使用Client

func thirdPartyApiCall(on req: Request) throws -> Future<Response> {
    let client = try req.client()
    struct SomePayload: Content {
        let title: String
        let year: Int
    }
    return client.post("http://www.example.com/example/post/request", beforeSend: { req in
        let payload = SomePayload(title: "How to make api call", year: 2019)
        try req.content.encode(payload, as: .json)
    })
}

或者例如像这样在boot.swift

/// Called after your application has initialized.
public func boot(_ app: Application) throws {    
    let client = try app.client()
    struct SomePayload: Content {
        let title: String
        let year: Int
    }
    let _: Future<Void> = client.post("http://www.example.com/example/post/request", beforeSend: { req in
        let payload = SomePayload(title: "How to make api call", year: 2019)
        try req.content.encode(payload, as: .json)
    }).map { response in
        print(response.http.status)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.