# fetchRemote (Server)

> Makes an HTTP or HTTPS request and hands the response to a function when it arrives.

- **Platform**: MY Multiplayer (MYMP)
- **Kind**: Lua Function
- **Side**: Server
- **Category**: Network and HTTP
- **URL**: https://wiki.mymp.gg/en/fetchRemote

## Syntax

```lua
bool|string, table fetchRemote(string url, function callback, any ... [, table options = nil])
```

## Parameters

| Name | Type | Description |
| --- | --- | --- |
| `url` | `string` | The address, starting with `http://` or `https://`. Anything else raises an error. |
| `options` | `table` | Optional table: `method` (`GET`, `POST`, `PUT`, `PATCH`, `DELETE` or `HEAD`; `POST` when there is `postData` and no method), `headers` (name → value), `postData` (the body to send) and `connectTimeout` (in ms, from 1000 to 60000, 10000 if missing). An unknown method raises an error. *(default: `nil`)* |
| `callback` | `function` | Called with the response's body, the `info` table and the extra arguments. |
| `...` | `any` | Arguments passed to `callback` after `info`. |

## Returns

`true` if the request was sent. Inside `async.thread` and without `callback`, the function waits for the response and returns the body and the `info` table.

`info` has `success` (`true` when the status is 2xx), `statusCode`, `headers` (name → value) and, if the request failed, `error`. When the resource stops, the responses that have not arrived yet are dropped.

## Example

```lua
local options = {
    method = "POST",
    headers = { ["Content-Type"] = "application/json" },
    postData = toJSON({ event = "server_started" }),
}

fetchRemote("https://example.com/api/events", options, function(body, info)
    if not info.success then
        outputDebugString("request failed: " .. (info.error or info.statusCode))
    end
end)
```

### Coming from MTA

Of MTA's options, only `method`, `headers`, `postData` and `connectTimeout` are read. Inside `async.thread`, `callback` can be left out and the call waits for the response.

## See also

- [async.thread (Shared)](https://wiki.mymp.gg/en/async.thread.md): Runs a function in a new async thread, right away. The call returns when the function ends or first pauses, as with async.wait.
- [fromJSON (Shared)](https://wiki.mymp.gg/en/fromJSON.md): Turns JSON text into a Lua value. It is the same function as json.decode.
- [toJSON (Shared)](https://wiki.mymp.gg/en/toJSON.md): Turns a Lua value into JSON text. It is the same function as json.encode.
