Search code examples
swiftvapor

Accessing `Request` body parameters


I'm trying to create a chain of requests to third-party API with the following code:

import Vapor

final class APIController: RouteCollection {

    private let baseULR = "..."

    func boot(router: Router) throws {
        router.post("login", use: validate)
    }

    func validate(_ req: Request) throws -> Future<Response> {
        // Get the phone number of the user
        let phoneNumber = try req.content.syncGet(String.self, at: "phone_number")
        return try req.client().post("\(baseUrl)/...", beforeSend: { post in
            try post.content.encode(json: ["phone_number": phoneNumber])
        })
    }
}

But when testing request, I'm getting an error:

[ ERROR ] Abort.415: Unsupported Media Type (ContentCoders.swift:95)
[ DEBUG ] Suggested fixes for Abort.415: Register an `DataDecoder` using `ContentConfig`. Use one of the decoding methods that accepts a custom decoder. (ErrorMiddleware.swift:26)

That, unfortunately, I don't understand how to fix.


Solution

  • You could try to provide a Content-Type of a payload

    func validate(_ req: Request) throws -> Future<Response> {
        // Get the phone number of the user
        return req.content.get(String.self, at: "phone_number").flatMap { phoneNumber in
            return try req.client().post("/...") {
                try $0.content.encode(["phone_number": phoneNumber], as: .json)
            }
        }
    }