File: rest-client-migration.md

package info (click to toggle)
ruby-faraday 2.14.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,008 kB
  • sloc: ruby: 6,509; sh: 10; makefile: 8
file content (225 lines) | stat: -rw-r--r-- 5,547 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# Migrating from `rest-client` to `Faraday`

The `rest-client` gem is in maintenance mode, and developers are encouraged to migrate to actively maintained alternatives like [`faraday`](https://github.com/lostisland/faraday). This guide highlights common usage patterns in `rest-client` and how to migrate them to `faraday`.

---

## Quick Comparison

| Task              | rest-client example                                      | faraday example                                                            |
| ----------------- | -------------------------------------------------------- | -------------------------------------------------------------------------- |
| Simple GET        | `RestClient.get("https://httpbingo.org/get")`            | `Faraday.get("https://httpbingo.org/get")`                                 |
| GET with params   | `RestClient.get(url, params: { id: 1 })`                 | `Faraday.get(url, { id: 1 })`                                              |
| POST form data    | `RestClient.post(url, { a: 1 })`                         | `Faraday.post(url, { a: 1 })`                                              |
| POST JSON         | `RestClient.post(url, obj.to_json, content_type: :json)` | `Faraday.post(url, obj.to_json, { 'Content-Type' => 'application/json' })` |
| Custom headers    | `RestClient.get(url, { Authorization: 'Bearer token' })` | `Faraday.get(url, nil, { 'Authorization' => 'Bearer token' })`             |
| Get response body | `response.body`                                          | `response.body`                                                            |
| Get status code   | `response.code`                                          | `response.status`                                                          |
| Get headers       | `response.headers` (returns `Hash<Symbol, String>`)      | `response.headers` (returns `Hash<String, String>`)                        |

---

## Installation

In your `Gemfile`, replace `rest-client` with:

```ruby
gem "faraday"
```

Then run:

```sh
bundle install
```

---

## Basic HTTP Requests

### GET request

**rest-client:**

```ruby
RestClient.get("https://httpbingo.org/get")
```

**faraday:**

```ruby
Faraday.get("https://httpbingo.org/get")
```

---

### GET with Params

**rest-client:**

```ruby
RestClient.get("https://httpbingo.org/get", params: { id: 1, foo: "bar" })
```

**faraday:**

```ruby
Faraday.get("https://httpbingo.org/get", { id: 1, foo: "bar" })
```

---

### POST Requests

**rest-client:**

```ruby
RestClient.post("https://httpbingo.org/post", { foo: "bar" })
```

**faraday:**

```ruby
Faraday.post("https://httpbingo.org/post", { foo: "bar" })
```

---

### Sending JSON

**rest-client:**

```ruby
RestClient.post("https://httpbingo.org/post", { foo: "bar" }.to_json, content_type: :json)
```

**faraday (manual):**

```ruby
Faraday.post("https://httpbingo.org/post", { foo: "bar" }.to_json, { 'Content-Type' => 'application/json' })
```

**faraday (with middleware):**

```ruby
conn = Faraday.new(url: "https://httpbingo.org") do |f|
  f.request :json            # encode request body as JSON and set Content-Type
  f.response :json           # parse response body as JSON
end

conn.post("/post", { foo: "bar" })
```

---

## Handling Responses

**rest-client:**

```ruby
response = RestClient.get("https://httpbingo.org/headers")
response.code    # => 200
response.body    # => "..."
response.headers # => { content_type: "application/json", ... }
```

**faraday:**

> notice headers Hash keys are stringified, not symbolized like in rest-client

```ruby
response = Faraday.get("https://httpbingo.org/headers")
response.status     # => 200
response.body       # => "..."
response.headers    # => { "content-type" => "application/json", ... }
```

---

## Error Handling

**rest-client:**

```ruby
begin
  RestClient.get("https://httpbingo.org/status/404")
rescue RestClient::NotFound => e
  puts e.response.code  # 404
end
```

**faraday:**

> By default, Faraday does **not** raise exceptions for HTTP errors (like 404 or 500); it simply returns the response. If you want exceptions to be raised on HTTP error responses, include the `:raise_error` middleware.
>
> With `:raise_error`, Faraday will raise `Faraday::ResourceNotFound` for 404s and other exceptions for other 4xx/5xx responses.
>
> See also:
>
> * [Dealing with Errors](getting-started/errors.md)
> * [Raising Errors](middleware/included/raising-errors.md)

```ruby
conn = Faraday.new(url: "https://httpbingo.org") do |f|
  f.response :raise_error
end

begin
  conn.get("/status/404")
rescue Faraday::ResourceNotFound => e
  puts e.response[:status]  # 404
end
```

---

## Advanced Request Configuration

**rest-client:**

```ruby
RestClient::Request.execute(method: :get, url: "https://httpbingo.org/get", timeout: 10)
```

**faraday:**

```ruby
conn = Faraday.new(url: "https://httpbingo.org", request: { timeout: 10 })
conn.get("/get")
```

---

## Headers

**rest-client:**

```ruby
RestClient.get("https://httpbingo.org/headers", { Authorization: "Bearer token" })
```

**faraday:**

> Notice headers Hash expects stringified keys.

```ruby
Faraday.get("https://httpbingo.org/headers", nil, { "Authorization" => "Bearer token" })
```

---

## Redirects

**rest-client:**
Automatically follows GET/HEAD redirects by default.

**faraday:**
Use the `follow_redirects` middleware (not included by default):

```ruby
require "faraday/follow_redirects"

conn = Faraday.new(url: "https://httpbingo.org") do |f|
  f.response :follow_redirects
end
```