{"id":19509869,"url":"https://github.com/steamclock/netable","last_synced_at":"2026-03-18T00:40:44.975Z","repository":{"id":45037666,"uuid":"153495240","full_name":"steamclock/netable","owner":"steamclock","description":"A Swift library for encapsulating network APIs using Codable in a type-oriented way.","archived":false,"fork":false,"pushed_at":"2024-09-16T15:41:57.000Z","size":5839,"stargazers_count":97,"open_issues_count":10,"forks_count":3,"subscribers_count":11,"default_branch":"main","last_synced_at":"2025-09-03T08:36:58.761Z","etag":null,"topics":["swift"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/steamclock.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2018-10-17T17:15:52.000Z","updated_at":"2025-01-13T21:18:12.000Z","dependencies_parsed_at":"2024-09-16T18:54:40.006Z","dependency_job_id":null,"html_url":"https://github.com/steamclock/netable","commit_stats":{"total_commits":173,"total_committers":10,"mean_commits":17.3,"dds":0.7109826589595376,"last_synced_commit":"920c0e9c7665a1caa5f516ab9a8931202e6f6fd8"},"previous_names":[],"tags_count":22,"template":false,"template_full_name":null,"purl":"pkg:github/steamclock/netable","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/steamclock%2Fnetable","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/steamclock%2Fnetable/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/steamclock%2Fnetable/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/steamclock%2Fnetable/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/steamclock","download_url":"https://codeload.github.com/steamclock/netable/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/steamclock%2Fnetable/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":276289804,"owners_count":25616962,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-21T02:00:07.055Z","response_time":72,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["swift"],"created_at":"2024-11-10T23:13:38.366Z","updated_at":"2025-09-21T22:27:36.976Z","avatar_url":"https://github.com/steamclock.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"![](header.png)\n\n[![Swift Package Manager compatible](https://img.shields.io/badge/Swift%20Package%20Manager-compatible-brightgreen.svg)](https://github.com/apple/swift-package-manager)[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Platform](https://img.shields.io/cocoapods/p/Netable.svg?style=flat)](http://cocoapods.org/pods/Netable)\n\nModern apps interact with a lot of different APIs. Netable makes that easier by providing a simple interface for using those APIs to drive high-quality iOS and MacOS apps, built on Swift `Codable`, while still supporting non-standard and unusual APIs when need be.\n\n- [Features](#features)\n- [Usage](#usage)\n    - [Standard Usage](#standard-usage)\n    - [Resource Extraction](#resource-extraction)\n    - [Handling Errors](#handling-errors)\n    - [Request Interceptors](#request-interceptors)\n    - [GraphQL Support](#graphql-support)\n- [Example](#example)\n   - [Full Documentation](#full-documentation)\n- [Installation](#installation)\n   - [Requirements](#requirements)\n   - [Supporting Earlier Versions][#supporting-earlier-versions-of-ios]\n- [License](#license)\n\n## Features\n\nNetable is built on a number of core principles we believe a networking library should follow:\n- Handle the simplest REST API calls with minimal code, while still having the extensibility to decode the gnarliest responses\n- Leverage Swift’s Codable protocols for automatic decoding and encoding\n- Avoid monolithic networking files and avoid wrappers\n- Straightforward global and local error handling\n- Add a little bit of magic, but only where it goes a long way \n\n## Usage\n\n### Standard Usage\n\n#### Make a new instance of `Netable`, and pass in your base URL:\n\n```swift\nlet netable = Netable(baseURL: URL(string: \"https://api.thecatapi.com/v1/\")!)\n```\nSee [here](#additional-netable-instance-parameters) for information on adding additional instance parameters. \n\n#### Extend `Request`\n\n```swift\nstruct CatImage: Decodable {\n    let id: String\n    let url: String\n}\n\nstruct GetCatImages: Request {\n    typealias Parameters = [String: String]\n    typealias RawResource = [CatImage]\n\n    public var method: HTTPMethod { return .get }\n\n    public var path: String {\n        return \"images/search\"\n    }\n\n    public var parameters: [String: String] {\n        return [\"mime_type\": \"jpg,png\", \"limit\": \"2\"]\n    }\n}\n```\n\n#### Make your request using `async`/`await` and handle the result:\n\n```swift\nTask {\n    do {\n        let catImages = try await netable.request(GetCatImages())\n        if let firstCat = catImages.first,\n           let url = URL(string: firstCat.url),\n           let imageData = try? Data(contentsOf: url) {\n            self.catsImageView1.image = UIImage(data: imageData)\n        }\n\n        if let lastCat = catImages.last,\n           let url = URL(string: lastCat.url),\n           let imageData = try? Data(contentsOf: url) {\n            self.catsImageView2.image = UIImage(data: imageData)\n        }\n    } catch {\n        let alert = UIAlertController(\n            title: \"Uh oh!\",\n            message: \"Get cats request failed with error: \\(error)\",\n            preferredStyle: .alert\n        )\n\n        alert.addAction(UIAlertAction(title: \"OK\", style: .cancel))\n        self.present(alert, animated: true, completion: nil)\n    }\n}\n```\n\n#### Making a request with Combine\n\n```swift\nnetable.request(GetCatImages())\n    .sink { result in\n        switch result {\n        case .success(let catImages):\n            if let firstCat = catImages.first,\n               let url = URL(string: firstCat.url),\n               let imageData = try? Data(contentsOf: url) {\n                self.catsImageView1.image = UIImage(data: imageData)\n            }\n\n            if let lastCat = catImages.last,\n               let url = URL(string: lastCat.url),\n               let imageData = try? Data(contentsOf: url) {\n                self.catsImageView2.image = UIImage(data: imageData)\n            }\n        case .failure(let error):\n            let alert = UIAlertController(\n                title: \"Uh oh!\",\n                message: \"Get cats request failed with error: \\(error)\",\n                preferredStyle: .alert\n            )\n\n            alert.addAction(UIAlertAction(title: \"OK\", style: .cancel))\n            self.present(alert, animated: true, completion: nil)\n        }\n    }.store(in: \u0026cancellables)\n```\n\n#### Or, if you prefer good old fashioned callbacks\n\n```swift\nnetable.request(GetCatImages()) { result in\n    switch result {\n    case .success(let catImages):\n        if let firstCat = catImages.first,\n           let url = URL(string: firstCat.url),\n           let imageData = try? Data(contentsOf: url) {\n            self.catsImageView1.image = UIImage(data: imageData)\n        }\n\n        if let lastCat = catImages.last,\n           let url = URL(string: lastCat.url),\n           let imageData = try? Data(contentsOf: url) {\n            self.catsImageView2.image = UIImage(data: imageData)\n        }\n    case .failure(let error):\n        let alert = UIAlertController(\n            title: \"Uh oh!\",\n            message: \"Get cats request failed with error: \\(error)\",\n            preferredStyle: .alert\n        )\n\n        alert.addAction(UIAlertAction(title: \"OK\", style: .cancel))\n        self.present(alert, animated: true, completion: nil)\n    }\n}\n```\n\n#### Canceling A Request\n\nYou're able to easily cancel a request using `.cancel()`, which you can see in action in the [AuthNetworkService](https://github.com/steamclock/netable/blob/main/Netable/Example/Services/AuthNetworkService.swift#L82) within the Example Project.\n\nTo cancel a task, we first need to ensure we retain a reference to the task, like so: \n\n```swift\n let createRequest = Task {\n               let result = try await netable.request()\n}\n\ncreateRequest.cancel()\n```\n\n#### Additional Netable instance parameters\n\nWithin your Netable Instance, you're able to provide optional parameters beyond the `baseURL` to send additional information with each request made. These include:\n\n- Config parameters to specify options like `globalHeaders`, your preferred `encoding/decoding` strategy, `logRedecation`, and/or `timeouts`.\n- specifying a `logDestination` for the request logs\n- a `retryConfiguration` to retry the request as desired if it fails.\n- specifying a `requestFialureDelegate/Subject`.\n\n```swift\n  let netable = Netable(baseURL: URL(string: \"https://...\")!,\n            config: Config(globalHeaders: [\"Authentication\" : \"Bearer \\(login.token)\"]),\n            logDestination: EmptyLogDestination(),\n            retryConfiguration: RetryConfiguration(errors: .all, count: 3, delay: 5.0),\n            requestFailureDelegate: ErrorService.shared)\n```\n\nSee [AuthNetworkService](https://github.com/steamclock/netable/blob/master/Netable/Example/Services/AuthNetworkService.swift#L45) in the Example Project for a more detailed example.\n\n#### Additional Request parameters\n\nYou also have the flexibility to set optional parameters to be sent along with each individual request made to an instance. Note that for duplicated parameters between an instance and an individual request, the instance's paramters will be overridden by an individual request. You can see the list of these [here](https://github.com/steamclock/netable/blob/master/Netable/Netable/Request.swift).\n\nWithin the Example Project, you can see an example of adding `unredactedParameterKeys` within the [LoginRequest](https://github.com/steamclock/netable/blob/master/Netable/Example/Requests/LoginRequest.swift) and a `jsonKeyDecodingStrategy` within the [GetUserRequest](https://github.com/steamclock/netable/blob/master/Netable/Example/Requests/GetUserRequest.swift).\n\n### Resource Extraction\n\n#### Have your request object handle extracting a usable object from the raw resource\n\n```swift\nstruct CatImage: Decodable {\n    let id: String\n    let url: String\n}\n\nstruct GetCatImageURL: Request {\n    typealias Parameters = [String: String]\n    typealias RawResource = [CatImage]\n    typealias FinalResource = URL\n\n     // ...\n\n    func finalize(raw: RawResource) async throws -\u003e FinalResource {\n        guard let catImage = raw.first else {\n            throw NetableError.resourceExtractionError(\"The CatImage array is empty\")\n        }\n\n        guard let url = URL(string: catImage.url) else {\n            throw NetableError.resourceExtractionError(\"Could not build URL from CatImage url string\")\n        }\n\n        return url\n    }\n}\n```\n\n#### Leave your network code to deal with the important stuff\n\n```swift\nTask { \n    do {\n        let catUrl = try await netable.request(GetCatImages())\n        guard let imageData = try? Data(contentsOf: catUrl) else {\n            throw NetableError.noData\n        }\n\n        self.imageView.image = UIImage(data: imageData)\n    } catch {\n        // ...\n    }\n}\n```\n\n#### Smart Unwrapping Objects\n\nSometimes APIs like to return the object you actually care about inside of a single level wrapper, which `Finalize` is great at dealing with, but requires a little more boilerplate code than we'd like. This is where `SmartUnwrap\u003c\u003e` comes in! \n\nCreate your request as normal, but set your `RawResource = SmartUnwrap\u003cObjectYouCareAbout\u003e` and `FinalResource = ObjectYourCareAbout`. You can also specify `Request.smartUnwrapKey` to avoid ambiguity when unwrapping objects from your response.\n\nBefore: \n```swift\nstruct UserResponse {\n    let user: User\n}\n\nstruct User {\n    let name: String\n    let email: String\n}\n\nstruct GetUserRequest: Request {\n    typealias Parameters: GetUserParams\n    typealias RawResource: UserResponse\n    typealias FinalResource: User\n    \n    // ...\n    \n    func finalize(raw: RawResource) async throws -\u003e FinalResource {\n        return raw.user\n    }\n}\n```\n\nAfter: \n```swift\nstruct User: {\n    let name: String\n    let email: String\n}\n\nstruct GetUserRequest: Request {\n    typealias Parameters: GetUserParams\n    typealias RawResource: SmartUnwrap\u003cUser\u003e\n    typealias FinalResource: User\n}\n\n```\n\n#### Partially Decoding Arrays\n\nSometimes, when decoding an array of objects, you may not want to fail the entire request if some of those objects fail to decode. For example, the following `json` would fail to decode using standard decoding because the second post is missing the content.\n\n```json\n{ \n    posts: [\n        { \n        \"title\": \"Super cool cat.\"\n        \"content\": \"Info about a super cool cat.\"\n        },\n        {\n        \"title\": \"Even cooler cat.\"\n        }\n    ]\n}\n\n```\n\nTo do this, you can set your Request's `arrayDecodeStrategy` to `.lossy` to return any elements that succeed to decode.\n\n```swift\nstruct Post: {\n   let title: String\n   let content: String\n}\n\nstruct GetPostsRequests: {\ntypealias RawResource: SmartUnwrap\u003c[Post]\u003e\ntypealias FinalResource: [Post]\n\nvar arrayDecodingStrategy: ArrayDecodingStrategy: { return .lossy }\n}\n```\n\nNote that this will only work if your `RawResource` is `RawResource: Sequence` or `RawResource: SmartUnwrap\u003cSequence\u003e`. For better support of decoding nested, lossy arrays we recommend checking out [Better Codable](https://github.com/marksands/BetterCodable). Also, at this time, Netable doesn't support partial decoding for GraphQL requests.\n\n#### Create a LossyArray directly within your object\n\nUsing `.lossy` as our `arrayDecodingStrategy` works well for objects that are being decoded as an array. We've added support to allow for partial decoding of objects that _contain_ arrays.\n\n```swift\nstruct User: Decodable {\n    let firstName: String\n    let lastName: String\n    let bio: String\n    let additionalInfo: LossyArray\u003cAdditionalInfo\u003e\n}\n\nstruct UserLoginData: Decodable, Hashable {\n    let age: Int\n    let gender: String\n    let nickname: String\n}\n```\n\nNote: to access the LossyArray's elements, you have to access `.element` within, like so.\n\n```swift\n    ForEach(user.additionalInfo.element, id: \\.self) {\n    // ..\n    }\n```\n\n#### Perform an optional process before returning the result using postProcess\n\nThis is helpful for managing data in places like caches or data managers. You can see this more indepth in our [UserRequest](https://github.com/steamclock/netable/blob/main/Netable/Example/Requests/GetUserRequest.swift)\n\nTo use `postProcess` inside of the request, add the code you want to run before the return statement:\n\n```swift\n\nstruct GetUserRequest: Request {\n   // ...\n   \n    func postProcess(result: FinalResource) -\u003e FinalResource {\n        DataManager.shared.user = result\n        return result\n    }\n}\n\n```\n\n### Handling Errors\n\nIn addition to handling errors locally that are thrown, or returned through `Result` objects, we provide two ways to handle errors globally. These can be useful for doing things like presenting errors in the UI for common error cases across multiple requests, or catching things like failed authentication requests to clear a stored user.\n\n#### Using `requestFailureDelegate`\n\nSee [GlobalRequestFailureDelegate](https://github.com/steamclock/netable/blob/main/Netable/Example/Services/ErrorService.swift) in the Example project for a more detailed example.\n\n```swift\nextension GlobalRequestFailureDelegateExample: RequestFailureDelegate {\n    func requestDidFail\u003cT\u003e(_ request: T, error: NetableError) where T : Request {\n        let alert = UIAlertController(title: \"Uh oh!\", message: error.errorDescription, preferredStyle: .alert)\n        present(alert, animated: true)\n    }\n}\n```\n\n### Request Interceptors\n\nInterceptors are a powerful and flexible way to modify a `Request` before it is executed. When you create your `Netable` instance, you can pass in an optional `InterceptorList`, containing any `Interceptor`s you would like to be applied to requests.\n\nWhen you make a request, each `Interceptor` will call its `adapt` function in turn, in the order it was passed in to the `InterceptorList`. `adapt` should return a special `AdaptedRequest` object that indicates the result of the function call.\n\nYou might attached a new header, modifying the request:\n\n```\nfunc adapt(_ request: URLRequest, instance: Netable) async throws -\u003e AdaptedRequest {\n    var newRequest = request\n    newRequest.addValue(\"1a2a3a4a\", forHTTPHeaderField: \"Authorization\")\n    return .changed(newRequest)\n}\n\n```\n\nOr, you might sub out the entire request with a mocked file for specific endpoints, otherwise do nothing:\n\n```\nfunc adapt(_ request: URLRequest, instance: Netable) async throws -\u003e AdaptedRequest {\n    if request.url.contains(\"/foo\") {\n        return .mocked(\"./path/to/foo-mock.json\")\n    } else if request.url.contains(\"/bar\") {\n        return .mocked(\"./path/to/bar-mock.json\")\n    }\n    \n    return .notChanged\n}\n```\n\nSee [MockRequestInterceptor](https://github.com/steamclock/netable/blob/main/Netable/Example/Services/AuthNetworkService.swift) in the Example project for a more detailed example.\n\n#### Using `requestFailurePublisher`\n\nIf you prefer `Combine`, you can subscribe to this publisher to receive `NetableErrors` from elsewhere in your app.\n\nSee [GlobalRequestFailurePublisher](https://github.com/steamclock/netable/blob/main/Netable/Example/Services/AuthNetworkService.swift#L34) in the Example project for a more detailed example.\n\n```swift\nnetable.requestFailurePublisher.sink { error in\n    let alert = UIAlertController(title: \"Uh oh!\", message: error.errorDescription, preferredStyle: .alert)\n    self.present(alert, animated: true)\n}.store(in: \u0026cancellables)\n```\n\n#### Using `FallbackResource`\n\nSometimes, you may want to specify a backup type to try and decode your response to if the initial decoding fails, for example:\n- You want to provide a fallback option for an important request that may have changed due to protocol versioning\n- An API may send back different types of responses for different types of success\n\n`Request` allows you to optionally declare a `FallbackResource: Decodable` associated type when creating your request. If you do and your request fails to decode the `RawResource`, it will try to decode your fallback resource, and if successful, throw a `NetableError.fallbackDecode` with your successful decoding.\n\n```swift\nstruct CoolCat {\n    let name: String\n    let breed: String\n}\n\nstruct Cat {\n    let name: String\n}\n\nstruct GetCatRequest: Request {\ntypealias RawResource: CoolCat\ntypealias FallbackResource: Cat\n\n// ...\n}\n```\n\nSee [FallbackDecoderViewController](https://github.com/steamclock/netable/blob/main/Netable/Example/Requests/GetVersionRequest.swift) in the Example project for a more detailed example.\n\n### GraphQL Support\n\nWhile you can technically use `Netable` to manage GraphQL queries right out of the box, we've added a helper protocol to make your life a little bit easier, called `GraphQLRequest`.\n\n```swift\nstruct GetAllPostsQuery: GraphQLRequest {\n    typealias Parameters = Empty\n    typealias RawResource = SmartUnwrap\u003c[Post]\u003e\n    typealias FinalResource = [Post]\n\n    var source = GraphQLQuerySource.resource(\"GetAllPostsQuery\")\n}\n```\n\nSee [UpdatePostsMutation](https://github.com/steamclock/netable/blob/main/Netable/Example/Requests/GraphQL/UpdatePostsMutation.swift) in the Example Project for a more detailed example. Note that by default it's important that your `.graphql` file's name matches _exactly_ with your request.\n\nWe recommend using a tool like [Postman](https://www.postman.com/) to document and test your queries. Also note that currently, shared fragments are not supported.\n\n## Example\n\n### Full Documentation\n\n[In-depth documentation](https://steamclock.github.io/netable/) is provided through Jazzy and GitHub Pages.  \n\n## Installation\n\n### Requirements\n\n- iOS 15.0+\n- MacOS 10.15+\n- Xcode 11.0+\n\nNetable is available through **[Swift Package Manager](https://swift.org/package-manager/)**. To install it, follow these steps:\n\n1. In Xcode, click **File**, then **Swift Package Manager**, then **Add Package Dependency**\n2. Choose your project\n3. Enter this URL in the search bar `https://github.com/steamclock/netable.git`\n\n### Supporting earlier version of iOS\n\nSince Netable 2.0 leverages `async`/`await` under the hood, if you want to build for iOS versions before 15.0 you'll need to use `v1.0`.\n\n## License\n\nNetable is available under the MIT license. See the [License.md](https://github.com/steamclock/netable/blob/main/LICENSE.md) for more info.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsteamclock%2Fnetable","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsteamclock%2Fnetable","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsteamclock%2Fnetable/lists"}