简体   繁体   English

如何在Vapor 3中进行第三方api调用?

[英]How to make a third party api call in Vapor 3?

I'd like to make a post call with some parameters in Vapor 3. 我想在Vapor 3中使用一些参数进行后期调用。

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

title: How to make api call
year: 2019

Which package/function can be used? 可以使用哪个包装/功能?

It's easy, you could do that using Client like this 很简单,您可以像这样使用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)
    })
}

or eg like this in boot.swift 或者例如在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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM