Search code examples
swiftvapor

Cant decode client response on vapor swift post request


I am making a post request using vapor swift client. My code looks like this

 _req.client.post("https://oauth2.googleapis.com/token") { req in
    try req.content.encode( [
        "code": code,
        "grant_type": "authorization_code",
        "redirect_uri": "http://localhost:8080/googleAuth"
    ])
}.flatMapThrowing { response in
    try response.content.decode(AccessToken.self)
}.map{ json in
    print(json)
}

The flatMapThrowing returns the full http response, but when I try to decode it with .map I get a nil.

This is the response I get from flatMapThrowing

HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Expires: Mon, 01 Jan 1990 00:00:00 GMT
Pragma: no-cache
Date: Fri, 23 Apr 2021 16:03:57 GMT
Content-Type: application/json; charset=utf-8
Vary: X-Origin
Vary: Referer
Server: scaffolding on HTTPServer2
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
Alt-Svc: h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
Accept-Ranges: none
Vary: Origin,Accept-Encoding
Transfer-Encoding: chunked

{
  "access_token": "...",
  "expires_in": 3599,
  "refresh_token": "...",
  "scope": "...",
  "token_type": "Bearer",
  "id_token": "..."
}

But when I try to decode it with this model I got an empty var

import Fluent
import Vapor

struct AccessToken: Content {
    var access_token: String
    var expires_in: String?
    var refresh_token: String?
    var scope: String?
    var token_type: String?
    var id_token: String?
}

Solution

  • As told by Nick, the model had an error in the expires_in: String?, I decoded the json changing my model to:

    import Fluent
    import Vapor
    
    struct AccessToken: Content {
        var access_token: String?
        var expires_in: Int?
        var refresh_token: String?
        var scope: String?
        var token_type: String?
        var id_token: String?
    }