{"id":13535188,"url":"https://github.com/carson-katri/swift-request","last_synced_at":"2025-04-04T09:07:05.830Z","repository":{"id":40622412,"uuid":"196612897","full_name":"carson-katri/swift-request","owner":"carson-katri","description":"Declarative HTTP networking, designed for SwiftUI","archived":false,"fork":false,"pushed_at":"2022-07-26T21:04:05.000Z","size":704,"stargazers_count":741,"open_issues_count":9,"forks_count":44,"subscribers_count":14,"default_branch":"main","last_synced_at":"2025-03-28T08:05:21.207Z","etag":null,"topics":["declarative","dsl","functionbuilder","http","networking","swiftui"],"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/carson-katri.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":["carson-katri"]}},"created_at":"2019-07-12T16:40:50.000Z","updated_at":"2025-03-15T13:00:01.000Z","dependencies_parsed_at":"2022-07-31T23:48:42.445Z","dependency_job_id":null,"html_url":"https://github.com/carson-katri/swift-request","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carson-katri%2Fswift-request","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carson-katri%2Fswift-request/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carson-katri%2Fswift-request/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carson-katri%2Fswift-request/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/carson-katri","download_url":"https://codeload.github.com/carson-katri/swift-request/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247149500,"owners_count":20891954,"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","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":["declarative","dsl","functionbuilder","http","networking","swiftui"],"created_at":"2024-08-01T08:00:50.990Z","updated_at":"2025-04-04T09:07:05.807Z","avatar_url":"https://github.com/carson-katri.png","language":"Swift","readme":"![Request](Resources/banner.png)\n\n![swift 5.1](https://img.shields.io/badge/swift-5.1-blue.svg)\n![SwiftUI](https://img.shields.io/badge/-SwiftUI-blue.svg)\n![iOS](https://img.shields.io/badge/os-iOS-green.svg)\n![macOS](https://img.shields.io/badge/os-macOS-green.svg)\n![tvOS](https://img.shields.io/badge/os-tvOS-green.svg)\n[![Build](https://github.com/carson-katri/swift-request/workflows/Build/badge.svg)](https://github.com/carson-katri/swift-request/actions)\n[![codecov](https://codecov.io/gh/carson-katri/swift-request/branch/master/graph/badge.svg)](https://codecov.io/gh/carson-katri/swift-request)\n\n[Installation](#installation) - [Getting Started](#getting-started) - [Building a Request](#building-a-request) - [Codable](#codable) - [Combine](#combine) - [How it Works](#how-it-works) - [Request Groups](#request-groups) - [Request Chains](#request-chains) - [Json](#json) - [Contributing](#contributing) - [License](#license)\n\n[Using with SwiftUI](Resources/swiftui.md)\n\n\n## Installation\n`swift-request` can be installed via the `Swift Package Manager`.\n\nIn Xcode 11, go to `File \u003e Swift Packages \u003e Add Package Dependency...`, then paste in `https://github.com/carson-katri/swift-request`\n\nNow just `import Request`, and you're ready to [Get Started](#getting-started)\n\n\n## Getting Started\nThe old way:\n```swift\nvar request = URLRequest(url: URL(string: \"https://jsonplaceholder.typicode.com/todos\")!)\nrequest.addValue(\"application/json\", forHTTPHeaderField: \"Accept\")\nlet task = URLSession.shared.dataTask(with: url!) { (data, res, err) in\n    if let data = data {\n        ...\n    } else if let error = error {\n        ...\n    }\n}\ntask.resume()\n```\nThe *declarative* way:\n```swift\nRequest {\n    Url(\"https://jsonplaceholder.typicode.com/todo\")\n    Header.Accept(.json)\n}\n.onData { data in\n    ...\n}\n.onError { error in\n    ...\n}\n.call()\n```\nThe benefit of declaring requests becomes abundantly clear when your data becomes more complex:\n```swift\nRequest {\n    Url(\"https://jsonplaceholder.typicode.com/posts\")\n    Method(.post)\n    Header.ContentType(.json)\n    Body(Json([\n        \"title\": \"foo\",\n        \"body\": \"bar\",\n        \"usedId\": 1\n    ]).stringified)\n}\n```\nOnce you've built your `Request`, you can specify the response handlers you want to use.\n`.onData`, `.onString`, `.onJson`, and `.onError` are available.\nYou can chain them together to handle multiple response types, as they return a modified version of the `Request`.\n\nTo perform the `Request`, just use `.call()`. This will run the `Request`, and give you the response when complete.\n\n`Request` also conforms to `Publisher`, so you can manipulate it like any other Combine publisher ([read more](#combine)):\n```swift\nlet cancellable = Request {\n    Url(\"https://jsonplaceholder.typicode.com/todo\")\n    Header.Accept(.json)\n}\n.sink(receiveCompletion: { ... }, receiveValue: { ... })\n```\n\n## Building a Request\nThere are many different tools available to build a `Request`:\n- `Url`\n\nExactly one must be present in each `Request`\n```swift\nUrl(\"https://example.com\")\nUrl(protocol: .secure, url: \"example.com\")\n```\n- `Method`\n\nSets the `MethodType` of the `Request` (`.get` by default)\n```swift\nMethod(.get) // Available: .get, .head, .post, .put, .delete, .connect, .options, .trace, and .patch \n```\n- `Header`\n\nSets an HTTP header field\n```swift\nHeader.Any(key: \"Custom-Header\", value: \"value123\")\nHeader.Accept(.json)\nHeader.Authorization(.basic(username: \"carsonkatri\", password: \"password123\"))\nHeader.CacheControl(.noCache)\nHeader.ContentLength(16)\nHeader.ContentType(.xml)\nHeader.Host(\"en.example.com\", port: \"8000\")\nHeader.Origin(\"www.example.com\")\nHeader.Referer(\"redirectfrom.example.com\")\nHeader.UserAgent(.firefoxMac)\n```\n- `Query`\n\nCreates the query string\n```swift\nQuery([\"key\": \"value\"]) // ?key=value\n```\n- `Body`\n\nSets the request body\n```swift\nBody([\"key\": \"value\"])\nBody(\"myBodyContent\")\nBody(myJson)\n```\n- `Timeout`\n\nSets the timeout for a request or resource:\n```swift\nTimeout(60)\nTimeout(60, for: .request)\nTimeout(30, for: .resource)\n```\n- `RequestParam`\n\nAdd a param directly\n\u003e **Important:** You must create the logic to handle a custom `RequestParam`. You may also consider adding a case to `RequestParamType`. If you think your custom parameter may be useful for others, see [Contributing](#contributing)\n\n\n## Codable\nLet's look at an example. Here we define our data:\n```swift\nstruct Todo: Codable {\n    let title: String\n    let completed: Bool\n    let id: Int\n    let userId: Int\n}\n```\nNow we can use `AnyRequest` to pull an array of `Todo`s from the server:\n```swift\nAnyRequest\u003c[Todo]\u003e {\n    Url(\"https://jsonplaceholder.typicode.com/todos\")\n}\n.onObject { todos in ... }\n```\nIn this case, `onObject` gives us `[Todo]?` in response. It's that easy to get data and decode it.\n\n`Request` is built on `AnyRequest`, so they support all of the same parameters.\n\n\u003e If you use `onObject` on a standard `Request`, you will receive `Data` in response.\n\n## Combine\n`Request` and `RequestGroup` both conform to `Publisher`:\n```swift\nRequest {\n    Url(\"https://jsonplaceholder.typicode.com/todos\")\n}\n.sink(receiveCompletion: { ... }, receiveValue: { ... })\n\nRequestGroup {\n    Request {\n        Url(\"https://jsonplaceholder.typicode.com/todos\")\n    }\n    Request {\n        Url(\"https://jsonplaceholder.typicode.com/posts\")\n    }\n    Request {\n        Url(\"https://jsonplaceholder.typicode.com/todos/1\")\n    }\n}\n.sink(receiveCompletion: { ... }, receiveValue: { ... })\n```\n`Request` publishes the result using `URLSession.DataTaskPublisher`. `RequestGroup` collects the result of each `Request` in its body, and publishes the array of results.\n\nYou can use all of the Combine operators you'd expect on `Request`:\n```swift\nRequest {\n    Url(\"https://jsonplaceholder.typicode.com/todos\")\n}\n.map(\\.data)\n.decode([Todo].self, decoder: JSONDecoder())\n.sink(receiveCompletion: { ... }, receiveValue: { ... })\n```\nHowever, `Request` also comes with several convenience `Publishers` to simplify the process of decoding:\n\n1. `objectPublisher` - Decodes the data of an `AnyRequest` using `JSONDecoder`\n2. `stringPublisher` - Decodes the data to a `String`\n3. `jsonPublisher` - Converts the result to a `Json` object\n\nHere's an example of using `objectPublisher`:\n```swift\nAnyRequest\u003c[Todo]\u003e {\n    Url(\"https://jsonplaceholder.typicode.com/todos\")\n}\n.objectPublisher\n.sink(receiveCompletion: { ... }, receiveValue: { ... })\n```\nThis removes the need to constantly use `.map.decode` to extract the desired `Codable` result.\n\nTo handle errors, you can use the `receiveCompletion` handler in `sink`:\n```swift\nRequest {\n    Url(\"https://jsonplaceholder.typicode.com/todos\")\n}\n.sink(receiveCompletion: { res in\n    switch res {\n    case let .failure(err):\n        // Handle `err`\n    case .finished: break\n    }\n}, receiveValue: { ... })\n```\n\n## How it Works\nThe body of the `Request` is built using the `RequestBuilder` `@resultBuilder`.\n\nIt merges each `RequestParam` in the body into one `CombinedParam` object. This contains all the other params as children.\n\nWhen you run `.call()`, the children are filtered to find the `Url`, and any other optional parameters that may have been included.\n\nFor more information, see [RequestBuilder.swift](Sources/Request/Request/RequestBuilder.swift) and [Request.swift](Sources/Request/Request/Request.swift)\n\n\n## Request Groups\n`RequestGroup` can be used to run multiple `Request`s *simulataneously*. You get a response when each `Request` completes (or fails)\n```swift\nRequestGroup {\n    Request {\n        Url(\"https://jsonplaceholder.typicode.com/todos\")\n    }\n    Request {\n        Url(\"https://jsonplaceholder.typicode.com/posts\")\n    }\n    Request {\n        Url(\"https://jsonplaceholder.typicode.com/todos/1\")\n    }\n}\n.onData { (index, data) in\n    ...\n}\n.call()\n```\n\n\n## Request Chains\n`RequestChain` is used to run multiple `Request`s *one at a time*. When one completes, it passes its data on to the next `Request`, so you can use it to build the `Request`.\n\n`RequestChain.call` can optionally accept a callback that gives you all the data of every `Request` when completed.\n\n\u003e **Note:** You must use `Request.chained` to build your `Request`. This gives you access to the data and errors of previous `Request`s.\n```swift\nRequestChain {\n    Request.chained { (data, errors) in\n        Url(\"https://jsonplaceholder.typicode.com/todos\")\n    }\n    Request.chained { (data, errors) in\n        let json = Json(data[0]!)\n        return Url(\"https://jsonplaceholder.typicode.com/todos/\\(json?[0][\"id\"].int ?? 0)\")\n    }\n}\n.call { (data, errors) in\n    ...\n}\n```\n\n## Repeated Calls\n`.update` is used to run additional calls after the initial one. You can pass it either a number or a custom `Publisher`. You can also chain together multiple `.update`s. The two `.update`s in the following example are equivalent, so the end result is that the `Request` will be called once immediately and twice every 10 seconds thereafter.\n```swift\nRequest {\n    Url(\"https://jsonplaceholder.typicode.com/todo\")\n}\n.update(every: 10)\n.update(publisher: Timer.publish(every: 10, on: .main, in: .common).autoconnect())\n.call()\n```\n\nIf you want to use `Request` as a `Publisher`, use `updatePublisher`:\n```swift\nRequest {\n    Url(\"https://jsonplaceholder.typicode.com/todo\")\n}\n.updatePublisher(every: 10)\n.updatePublisher(publisher: ...)\n.sink(receiveCompletion: { ... }, receiveValue: { ... })\n```\nUnlike `update`, `updatePublisher` does not send a value immediately, but will wait for the first value from the `Publisher`.\n\n## Json\n`swift-request` includes support for `Json`.\n`Json` is used as the response type in the `onJson` callback on a `Request` object.\n\nYou can create `Json` by parsing a `String` or `Data`:\n```swift\nJson(\"{\\\"firstName\\\":\\\"Carson\\\"}\")\nJson(\"{\\\"firstName\\\":\\\"Carson\\\"}\".data(using: .utf8))\n```\nYou can subscript `Json` as you would expect:\n```swift\nmyJson[\"firstName\"].string // \"Carson\"\nmyComplexJson[0][\"nestedJson\"][\"id\"].int\n```\nIt also supports `dynamicMemberLookup`, so you can subscript it like so:\n```swift\nmyJson.firstName.string // \"Carson\"\nmyComplexJson[0].nestedJson.id.int\n```\n\nYou can use `.string`, `.int`, `.double`, `.bool`, and `.array` to retrieve values in a desired type.\n\u003e **Note:** These return **non-optional** values. If you want to check for `nil`, you can use `.stringOptional`, `.intOptional`, etc.\n\n## Contributing\nSee [CONTRIBUTING](CONTRIBUTING.md)\n\n\n## License\nSee [LICENSE](LICENSE)\n","funding_links":["https://github.com/sponsors/carson-katri"],"categories":["🛠 Examples","Swift","Networking"],"sub_categories":["Helpers"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcarson-katri%2Fswift-request","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcarson-katri%2Fswift-request","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcarson-katri%2Fswift-request/lists"}