Bifrost is a lightweight, scalable framework for interacting with JSON, REST APIs.
Bifrost is available via Swift Package Manager.
dependencies: [
.package(url: "https://github.com/mtzaquia/bifrost.git", from: "3.0.4"),
],Simply declare an entity conforming to API to start, then fulfill the required protocol conformances:
struct MyAPI: API {
let baseURL: URL = URL(string: "https://api.myapi.com/v2/")!
// ...
}You can define default query parameters that will apply to all requests. You can also configure the decoder for your specific use-case.
struct MyAPI: API {
// ...
func queryParameters() -> [URLQueryItem]
[
URLQueryItem(name: "api-key", value: "<my secret key>")
]
}
var jsonDecoder: JSONDecoder = {
let jd = JSONDecoder()
jd.dateDecodingStrategy = .iso8601
return jd
}()
}For each request, create a type with its supported parameters. Make sure this type conforms to Requestable.
You can also provide header fields for a specific request if needed, and you can choose the HTTP method for that request.
struct MyRequest {
private(set) var name: String
private(set) var anotherParam: String?
}
extension MyRequest: Requestable {
var path: String { "api/my-request" }
struct Response: Decodable {
let results: [MyResultObject]
}
}Note
If you expect an empty response, the built-in EmptyResponse type is avaiable for convenience.
Finally, you are ready to submit a request! Concurrency allows you to inline your call easily:
// ...
let response = try await MyAPI().response(for: MyRequest(name: "My fancy name"))
print(response.results) // Our response is already a Swift type! More specifically, an instance of `MyRequest.Response`.You can define request and response interceptors on your API for request mutation, mocking, and response post-processing.
requestInterceptorsrun after Bifrost builds the finalURLRequestand before transport- request-local headers belong in
Requestable.headerFields; API-wide headers belong in request interceptors responseInterceptorsrun on raw response data before Bifrost decodes the final success body- both phases use
InterceptionResult<T>with.continue,.return(...), and.restart - mocked and real responses share the same
InterceptedResponsewrapper, which exposesbody,httpResponse,statusCode, and normalizedheaderFields - interceptors can return
.restartto rerun the full request and response interceptor pipeline - unsuccessful HTTP statuses are surfaced after the response phase, so response interceptors can recover from responses like
401
struct AddAuthorization: RequestInterceptor {
let token: String
func intercept<Request>(
_ context: inout InterceptionContext<Request>
) async throws -> InterceptionResult<InterceptedResponse> where Request: Requestable {
if context.request is MyRequest {
context.urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
return .continue
}
}
struct RewriteResponse: ResponseInterceptor {
func intercept(
_ response: inout InterceptedResponse
) async throws -> InterceptionResult<InterceptedResponse> {
return .continue
}
}
struct MyAPI: API {
let baseURL = URL(string: "https://api.myapi.com/v2/")!
var requestInterceptors: [any RequestInterceptor] {
[AddAuthorization(token: "<token>")]
}
var responseInterceptors: [any ResponseInterceptor] {
[RewriteResponse()]
}
}Request interceptors receive an InterceptionContext with the original typed request as read-only context and the final built URLRequest as the mutable request that will be sent.
struct MockUser: RequestInterceptor {
func intercept<Request>(
_ context: inout InterceptionContext<Request>
) async throws -> InterceptionResult<InterceptedResponse> where Request: Requestable {
guard context.request is GetUserRequest else {
return .continue
}
let httpResponse = HTTPURLResponse(
url: URL(string: "https://api.myapi.com/v2/user")!,
statusCode: 200,
httpVersion: nil,
headerFields: ["X-Mocked": "true"]
)!
return .return(
InterceptedResponse(
body: Data(#"{"name":"Mocked User"}"#.utf8),
httpResponse: httpResponse
)
)
}
}Response interceptors always receive the full intercepted response, including metadata, so they can make decisions based on the HTTP code, headers, and raw body bytes before decoding happens. They can also return .restart after doing recovery work like refreshing a token.
struct NormalizeUser: ResponseInterceptor {
func intercept(
_ response: inout InterceptedResponse
) async throws -> InterceptionResult<InterceptedResponse> {
if response.statusCode == 202 {
response.httpResponse = HTTPURLResponse(
url: response.httpResponse.url!,
statusCode: 200,
httpVersion: nil,
headerFields: response.headerFields
)!
}
return .continue
}
}Copyright (c) 2025 @mtzaquia
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.