Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

vapor

api

I'd like to make a post call with some parameters in Vapor 3.

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

title: How to make api call
year: 2019

Which package/function can be used?

like image 424
Danny Avatar asked Apr 09 '19 21:04

Danny


1 Answers

It's easy, you could do that using Client like this

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 e.g. like this in 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)
    }
}
like image 142
imike Avatar answered Nov 08 '22 13:11

imike