rewrite basics page. focus on making requests, not middleware.

This commit is contained in:
rick olson 2019-06-05 15:22:41 -06:00
parent 78fd49eecf
commit 31d03bec46

View File

@ -5,92 +5,125 @@ permalink: /introduction/basics
hide: true
---
A `GET` request can be performed by calling the `.get` class method:
# Faraday Basics
Make a simple `GET` request by requiring the Faraday gem and using `Faraday.get`:
```ruby
response = Faraday.get 'http://sushi.com/nigiri/sake.json'
```
This works if you don't need to set up anything; you can roll with the default middleware
stack and default adapter (see [Faraday::RackBuilder#initialize][rack_builder]).
This returns a `Faraday::Response` object with the response status, headers, and
body.
```ruby
response.status
# => 200
response.headers
# => {"server"=>"sushi.com", "content-type"=>"text/html; charset=utf-8"...
response.body
# => "<html lang=\"en\">...
```
## Requests without a body
Faraday supports the following HTTP verbs that typically don't include a request
body:
* `get`
* `head`
* `delete`
* `trace`
You can specify URI query parameters and HTTP headers when making a request.
```ruby
url = 'http://sushi.com/nigiri/sake.json'
resp = Faraday.get(url, {a: 1}, {'Accept' => 'application/json'})
# => GET http://sushi.com/nigiri/sake.json?a=1
```
TODO: Link to query encoding config
## Requests with a body
Faraday also supports HTTP verbs that do include request bodies, though the
optional method arguments are different. Instead of HTTP query params, these
methods accept a response body.
* `post`
* `put`
* `patch`
```ruby
# POST 'application/x-www-form-urlencoded' content
url = 'http://sushi.com/fave'
resp = Faraday.post(url, "choice=sake")
# POST JSON content
resp = Faraday.post(url, '{"choice": "sake"}',
"Content-Type" => "application/json")
```
TODO: Link to json middleware?
### Form upload
Faraday can automatically convert hashes to values for form or multipart request
bodies.
```ruby
url = 'http://sushi.com/fave'
resp = Faraday.post(url, choice: 'sake')
# => POST 'choice=sake' to http://sushi.com/fave
```
TODO: Link to query encoding config
## Detailed HTTP Requests
All HTTP verbs support a longer form style of making requests. This is handy if
you need to change a lot of the defaults, or if the details of the HTTP request
change according to method arguments. Each of the HTTP verb helpers can yield a
`Faraday::Request` that can be modified before being sent.
This example shows a hypothetical search endpoint that accepts a JSON request
body as the actual search query.
```ruby
resp = Faraday.get('http://sushi.com/search') do |req|
req.params['limit'] = 100
req.headers['Content-Type'] = 'application/json'
req.body = {query: 'salmon'}.to_json
end
```
## The Connection Object
A more flexible way to use Faraday is to start with a Connection object. If you want to keep the same defaults, you can use this syntax:
A more flexible way to use Faraday is to start with a `Faraday::Connection`
object. Connection objects can store a common URL base path or HTTP headers to
apply to every request. All of the HTTP verb helpers described above
(`Faraday.get`, `Faraday.post`, etc) are available on the `Faraday::Connection`
instance.
```ruby
conn = Faraday.new(url: 'http://www.sushi.com')
```
conn = Faraday.new(
url: 'http://sushi.com',
params: {param: '1'},
headers: {'Content-Type' => 'application/json'}
)
Connections can also take an options hash as a parameter, or be configured with a block.
Check out the [Middleware][middleware] page for more details about how to use this block for configurations.
Since the default middleware stack uses the `url_encoded` middleware and default adapter, use them when building your own middleware stack.
```ruby
conn = Faraday.new(url: 'http://sushi.com') do |faraday|
# form-encode POST params
faraday.request :url_encoded
# log requests and responses to $stdout
faraday.response :logger
# make requests with Net::HTTP
faraday.adapter Faraday.default_adapter
end
```
## Perform requests with parameters
Once you have the connection object, use it to make HTTP requests. You can pass parameters to it in a few different ways.
### GET Requests
```ruby
conn = Faraday.new(url: 'http://sushi.com/nigiri')
response = conn.get 'sake.json'
# => GET http://sushi.com/nigiri/sake.json
# You can then access the response body
response.body
```
Using an absolute path overrides the path from the connection initializer
```ruby
response = conn.get '/maki/platters.json'
# => GET http://sushi.com/maki/platters.json
```
Path can also be empty. Parameters can be provided as a hash.
```ruby
conn.get '', { name: 'Maguro' }
# => GET http://sushi.com/nigiri?name=Maguro
conn.get do |req|
req.url '/search', page: 2
resp = Faraday.get('search') do |req|
req.params['limit'] = 100
req.body = {query: 'salmon'}.to_json
end
# => GET http://sushi.com/search?limit=100&page=2
# GET http://sushi.com/search?param=1&limit=100
```
### POST Requests
Parameters for POST requests are automatically put in the body as www-form-urlencoded.
```ruby
conn.post '', { name: 'Maguro' }
# => POST "name=maguro" to http://sushi.com/nigiri
```
To post as JSON instead of www-form-urlencoded, set the request header.
```ruby
conn.post do |req|
req.url ''
req.headers['Content-Type'] = 'application/json'
req.body = '{ "name": "Unagi" }'
end
# => POST "{ "name": "Unagi" }" to http://sushi.com/nigiri
```
[rack_builder]: https://github.com/lostisland/faraday/blob/master/lib/faraday/rack_builder.rb
[middleware]: ../middleware
A `Faraday::Connection` object can also be used to change the default HTTP
adapter or add custom middleware that runs during Faraday's request/response
cycle. See the [Middleware][../middleware] page for more details.