|
1 | 1 | # Leaf Fetch |
| 2 | + |
| 3 | +When building your applications, you will probably end up needing to call APIs or fetch data from external sources. Leaf provides a simple and easy way to do this using Fetch. Fetch provides a clean and modern interface for making network requests in PHP. It is inspired by JavaScript's Fetch API, Axios and uses elements from [Unirest PHP](https://github.com/Kong/unirest-php). |
| 4 | + |
| 5 | +## Setting Up |
| 6 | + |
| 7 | +To get started with Fetch, you need to install the Fetch package. You can do this using the Leaf CLI: |
| 8 | + |
| 9 | +::: code-group |
| 10 | + |
| 11 | +```bash:no-line-numbers [Leaf CLI] |
| 12 | +leaf install fetch |
| 13 | +``` |
| 14 | + |
| 15 | +```bash:no-line-numbers [Composer] |
| 16 | +composer require leafs/fetch |
| 17 | +``` |
| 18 | + |
| 19 | +::: |
| 20 | + |
| 21 | +Once installed, you can start using Fetch in your Leaf application. |
| 22 | + |
| 23 | +## Making Requests |
| 24 | + |
| 25 | +Fetch provides a simple and easy-to-use interface for making network requests in PHP. You can make GET, POST, PUT, DELETE, and other types of requests using Fetch. |
| 26 | + |
| 27 | +Fetch also provides a clean and modern interface for working with response data. |
| 28 | + |
| 29 | +You can write API requests like this: |
| 30 | + |
| 31 | +```php |
| 32 | +$response = fetch([ |
| 33 | + // HTTP method to send |
| 34 | + 'method' => 'PUT', |
| 35 | + |
| 36 | + // URL to send request to |
| 37 | + 'url' => 'https://jsonplaceholder.typicode.com/todos/1', |
| 38 | + |
| 39 | + // Request data to send along if any |
| 40 | + 'data' => [ |
| 41 | + 'firstName' => 'Fred', |
| 42 | + 'lastName' => 'Flintstone' |
| 43 | + ] |
| 44 | +]); |
| 45 | +``` |
| 46 | + |
| 47 | +Once this request is made, Fetch gives you a `FetchResponse` object which contains the response data, status code, headers, and more. |
| 48 | + |
| 49 | +```json |
| 50 | +"data": [], |
| 51 | +"status": 200, |
| 52 | +"headers": {}, |
| 53 | +"request": {} |
| 54 | +``` |
| 55 | + |
| 56 | +You will usually want to access the response data. You can do this using the `data` property of the `FetchResponse` object. |
| 57 | + |
| 58 | +```php |
| 59 | +response()->json($response->data); |
| 60 | +``` |
| 61 | + |
| 62 | +Put it all together and you have a simple and easy way to make network requests in PHP using Fetch. |
| 63 | + |
| 64 | +```php |
| 65 | +$response = fetch([ |
| 66 | + 'method' => 'GET', |
| 67 | + 'url' => 'https://jsonplaceholder.typicode.com/todos/1' |
| 68 | +]); |
| 69 | + |
| 70 | +response()->json($response->data); |
| 71 | +``` |
| 72 | + |
| 73 | +It gets even simpler when you're making a GET or POST request. Fetch provides some handy shortcuts to make these requests even easier. |
| 74 | + |
| 75 | +## Making GET Requests |
| 76 | + |
| 77 | +GET requests are the most common type of request you'll make when fetching data from an API. Fetch makes it easy to make GET requests using the global `fetch()` function. Here's an example of how you can make a GET request using Fetch: |
| 78 | + |
| 79 | +```php |
| 80 | +$res = fetch("https://jsonplaceholder.typicode.com/todos/"); |
| 81 | + |
| 82 | +// data returned is saved in the $data property just like axios |
| 83 | +response()->json($res->data); |
| 84 | +``` |
| 85 | + |
| 86 | +Every request made using Fetch returns a `FetchResponse` object. This object contains the response data, status code, headers, and more. You can access the response data using the `data` property. |
| 87 | + |
| 88 | +## Making POST Requests |
| 89 | + |
| 90 | +POST requests are used to send data to a server to create or update a resource. You can make POST requests using Fetch by passing an array of data as the second argument to the `fetch()` function. Here's an example: |
| 91 | + |
| 92 | +```php |
| 93 | +$res = fetch("https://jsonplaceholder.typicode.com/posts", [ |
| 94 | + "title" => "foo", |
| 95 | + "body" => "bar", |
| 96 | + "userId" => 1 |
| 97 | +]); |
| 98 | + |
| 99 | +response()->json($res->data); |
| 100 | +``` |
| 101 | + |
| 102 | +Once `fetch()` detects that you're passing an array as the second argument, it automatically converts the request to a POST request. |
| 103 | + |
| 104 | +## Setting Base URLs |
| 105 | + |
| 106 | +Base URLs are useful when you're making requests to the same server or API. One popular use case for base URLs is when you're working with a REST API as it allows you to ignore typing lengthy URLs for every request. |
| 107 | + |
| 108 | +You can set a base URL for all your requests using the `baseUrl()` method on the `Fetch` class. |
| 109 | + |
| 110 | +```php |
| 111 | +Leaf\Fetch::baseUrl('https://jsonplaceholder.typicode.com'); |
| 112 | +``` |
| 113 | + |
| 114 | +Now you can make requests without specifying the full URL. |
| 115 | + |
| 116 | +```php |
| 117 | +// https://jsonplaceholder.typicode.com/todos |
| 118 | +$response = fetch('/todos'); |
| 119 | + |
| 120 | +// https://jsonplaceholder.typicode.com/posts |
| 121 | +$response = fetch('/posts', [ |
| 122 | + 'title' => 'foo', |
| 123 | + 'body' => 'bar', |
| 124 | + 'userId' => 1, |
| 125 | +]); |
| 126 | +``` |
| 127 | + |
| 128 | +## Parameters for Requests |
| 129 | + |
| 130 | +This is a list of all options you can pass to Fetch when making requests: |
| 131 | + |
| 132 | +```php |
| 133 | +[ |
| 134 | + // `url` is the server URL that will be used for the request |
| 135 | + 'url' => null, |
| 136 | + |
| 137 | + // `method` is the request method to be used when making the request |
| 138 | + 'method' => 'GET', // default |
| 139 | + |
| 140 | + // `headers` are custom headers to be sent |
| 141 | + 'headers' => [], |
| 142 | + |
| 143 | + // `params` are the URL parameters to be sent with the request |
| 144 | + // Must be a plain object or a URLSearchParams object |
| 145 | + 'params' => [], |
| 146 | + |
| 147 | + // `data` is the data to be sent as the request body |
| 148 | + // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH' |
| 149 | + // When no `transformRequest` is set, must be of one of the following types: |
| 150 | + // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams |
| 151 | + // - Browser 'only' => FormData, File, Blob |
| 152 | + // - Node 'only' => Stream, Buffer |
| 153 | + 'data' => [], |
| 154 | + |
| 155 | + // `timeout` specifies the number of milliseconds before the request times out. |
| 156 | + // If the request takes longer than `timeout`, the request will be aborted. |
| 157 | + 'timeout' => 0, // default is `0` (no timeout) |
| 158 | + |
| 159 | + // `withCredentials` indicates whether or not cross-site Access-Control requests |
| 160 | + // should be made using credentials |
| 161 | + 'withCredentials' => false, // default |
| 162 | + |
| 163 | + // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. |
| 164 | + // This will set an `Authorization` header, overwriting any existing |
| 165 | + // `Authorization` custom headers you have set using `headers`. |
| 166 | + // Please note that only HTTP Basic auth is configurable through this parameter. |
| 167 | + // For Bearer tokens and such, use `Authorization` custom headers instead. |
| 168 | + 'auth' => [], |
| 169 | + |
| 170 | + // `responseType` indicates the type of data that the server will respond with |
| 171 | + // options 'are' => 'arraybuffer', 'document', 'json', 'text', 'stream' |
| 172 | + // browser 'only' => 'blob' |
| 173 | + 'responseType' => 'json', // default |
| 174 | + |
| 175 | + // `responseEncoding` indicates encoding to use for decoding responses (Node.js only) |
| 176 | + // 'Note' => Ignored for `responseType` of 'stream' or client-side requests |
| 177 | + 'responseEncoding' => 'utf8', // default |
| 178 | + |
| 179 | + // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token |
| 180 | + 'xsrfCookieName' => 'XSRF-TOKEN', // default |
| 181 | + |
| 182 | + // `xsrfHeaderName` is the name of the http header that carries the xsrf token value |
| 183 | + 'xsrfHeaderName' => 'X-XSRF-TOKEN', // default |
| 184 | + |
| 185 | + // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js |
| 186 | + 'maxContentLength' => 2000, |
| 187 | + |
| 188 | + // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed |
| 189 | + 'maxBodyLength' => 2000, |
| 190 | + |
| 191 | + // `maxRedirects` defines the maximum number of redirects to follow in node.js. |
| 192 | + // If set to 0, no redirects will be followed. |
| 193 | + 'maxRedirects' => 5, // default |
| 194 | + |
| 195 | + // `socketPath` defines a UNIX Socket to be used in node.js. |
| 196 | + // e.g. '/var/run/docker.sock' to send requests to the docker daemon. |
| 197 | + // Only either `socketPath` or `proxy` can be specified. |
| 198 | + // If both are specified, `socketPath` is used. |
| 199 | + 'socketPath' => null, // default |
| 200 | + |
| 201 | + // `proxy` defines the hostname, port, and protocol of the proxy server. |
| 202 | + // You can also define your proxy using the conventional `http_proxy` and |
| 203 | + // `https_proxy` environment variables. If you are using environment variables |
| 204 | + // for your proxy configuration, you can also define a `no_proxy` environment |
| 205 | + // variable as a comma-separated list of domains that should not be proxied. |
| 206 | + // Use `false` to disable proxies, ignoring environment variables. |
| 207 | + // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and |
| 208 | + // supplies credentials. |
| 209 | + // This will set an `Proxy-Authorization` header, overwriting any existing |
| 210 | + // `Proxy-Authorization` custom headers you have set using `headers`. |
| 211 | + // If the proxy server uses HTTPS, then you must set the protocol to `https`. |
| 212 | + 'proxy' => [], |
| 213 | + |
| 214 | + // `decompress` indicates whether or not the response body should be decompressed |
| 215 | + // automatically. If set to `true` will also remove the 'content-encoding' header |
| 216 | + // from the responses objects of all decompressed responses |
| 217 | + // - Node only (XHR cannot turn off decompression) |
| 218 | + 'decompress' => true, // default |
| 219 | + |
| 220 | + // If false, fetch will try to parse json responses |
| 221 | + 'rawResponse' => false, |
| 222 | + |
| 223 | + // CURLOPT_SSL_VERIFYHOST accepts only 0 (false) or 2 (true). |
| 224 | + // Future versions of libcurl will treat values 1 and 2 as equals |
| 225 | + 'verifyHost' => true, // default |
| 226 | + |
| 227 | + 'verifyPeer' => true, // default |
| 228 | + |
| 229 | + // Set additional options for curl. |
| 230 | + 'curl' => [], |
| 231 | +]; |
| 232 | +``` |
0 commit comments