# Consuming REST APIs

**URL:** https://community.linx.software/community/t/consuming-rest-apis/482
**Category:** Guide
**Created:** [November 16, 2020, 12:39pm UTC](https://community.linx.software/community/t/consuming-rest-apis/482 "2020-11-16T12:39:19Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![ronan](https://community.linx.software/community/user_avatar/community.linx.software/ronan/32/433_2.png) [@ronan](https://community.linx.software/community/u/ronan)
#### Post date: [November 16, 2020, 12:39pm UTC](https://community.linx.software/community/t/consuming-rest-apis/482/1 "2020-11-16T12:39:19Z")

</div>

# Consuming REST APIs

You are are able to make HTTP requests to any [REST API](https://www.codecademy.com/article/what-is-rest) using Linx. This allows you to connect to many of the main enterprise platforms ([Google](https://developers.google.com/drive/api/v2/reference), [Microsoft](https://docs.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0), [Shopify](https://shopify.dev/docs/admin-api/rest/reference) etc.) as well as share data between applications.

Connect to any REST API using the [CallRESTEndpointFNC](https://linx.software/docs/6/reference/plugins/rest/content/callrestendpoint) from the REST plugin.

  

 **Note:**  
  
 If you are looking to host REST web services using Linx, then take a look at [these articles](https://community.linx.software/?search=resthost). 

The below sections are covered in this article:

**CallRESTEndpoint Properties:**

- **[Authentication](#properties-authentication)**
  - [Type](#properties-authentication-type)

- **[Request](#properties-request)**
  - [Method](#properties-request-method)
  - [URL](#properties-request-url)
  - [Query string](#properties-request-query-string)
  - [Headers](#properties-request-headers)
  - [Body format](#properties-request-body-format)
  - [Body](#properties-request-body)

- **[Response](#properties-response)**
  - [Output type](#properties-response-output-type)

- **[Settings](#properties-settings)**
  - [Handle all status codes](#properties-settings-status-codes)
  - [Timeout](#properties-settings-timeout)
  - [Max response content size](#properties-settings-max-size)

**Authenticating requests:**

- [Anonymous](#authenticating-requests-anonymous)
- [HTTP Basic](#authenticating-basic)
- [API Key](#authenticating-requests-api-key)
- [Bearer Tokens](#authenticating-requests-bearer)

**Handling responses:**

- [Response status codes](#handling-responses-status-codes)
- [Setting the output type](#handling-responses-output-type)
- [Import from API Documentation](#handling-responses-output-type-import)
- [Import from an initial response](#handling-responses-output-type-import)

  

 **Tutorial:**  
  
 A more in depth parctical tutorial on consuming REST APIs has been written [here](https://community.linx.software/community/t/consuming-rest-apis-tutorial/484).

  
Please note the terms ‘Process’ and ‘Custom Type’ have been depreciated and have been replaced with ‘Function’ and ‘Type’ respectively. More details [**here**](https://linx.software/docs/releasenotes/linx/5.20.2.0/).
  

## CallRESTEndpoint Properties

The [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint) has the following properties which you will need to configure differently depending on the request type.

### Authentication

The authentication properties refer to the built-in authentication structures created by Linx when a request is made.

#### Type

The type of built-in authentication format to use:

- Anonymous
- Basic
- Digest
- Windows

  

 **Note:**

The following authentication schemes must be custom configured in the header or query of the request , for these schemes the Authentication Type property must be set to `Anonymous`:

- HTTP Bearer
- API Key
- OAuth 2.0

For authentication schemes that require custom authorization such as API Key or Bearer tokens, you will need to add this information to the respective part of the request such as the header.

For authentication schemes requiring certificate request signing or OAuth encryption key signing, these options are available in separate Properties.

  

 **Learn:**  
  
 Learn more about authenticating request [here](#authenticating-requests).

### Request

The below properties relate to the values needed to make the initial request.

#### Method

The HTTP Method of the request.

Linx supports the following HTTP methods when making REST requests:

- `GET`: Typically used to retrieve information, you are unable to supply a `request body` using this method.
- `POST`: Typically involves sending information in the `request body` to create an entity on the external system.
- `PUT`: Typically involves sending information in the `request body` to update an entity on the external system. This results in the entities details being completely replaced.
- `PATCH`: Typically involves sending information in the `request body` to update an entity on the external system. This results in the entities details being partially updated.
- `DELETE`: Typically used to remove entities from an external system, you are unable to supply a `request body` using this method.
- `HEAD`: Similar to the `GET` method, except no response body is returned, rather information is returned in the response headers.

#### URL

The URL of the endpoint to request.

An example of a REST endpoint URL:

```http
https://graph.microsoft.com/v1.0/users

```

You are able to set this property as:

- **TX:** Plain text, this value will always remain the same.  
  

  

- **EX:** Using an expression you are able to create dynamic URLs at runtime like the below:

```auto
= $.Settings.MicrosoftGraphAPI_BaseURI + "/users/"+ $.Input.User_ID 

```

The result of the above expression at runtime would be similar to the below :

```http
https://graph.microsoft.com/v1.0/users/1227272-ASSDSD-2332349

```

#### Query string

You are able to add query parameters to the request which will then be URL encoded and will be appended onto the end of the request URL.

Typical usage involves submitting query values that are used for filtering on the target system.

In order to add query parameters, expand the Query string property of the [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint)  
and add the query parameters.

 **Tip:**  
  
It is advised that any query string values are added to the Query string property of the CallRESTEndpointFNC . This will ensure that the correct URL encoding takes place.

For example, if you made a request to `https://graph.microsoft.com/v1.0/users` with the below query parameters:

- **email** : `support@linx.software`
- **name** : `Team Linx`

At runtime, the above query parameters will be URL encoded and appended onto the request URL as the `query string`:

```http
https://graph.microsoft.com/v1.0/users?email=support%40linx.software&name=Team+Linx

```

You are able to set the query parameters as plain text, a $.Setting ⚙ value or a result of an expression.

![Connecting to APIs - Tutorial - Add query](https://community.linx.software/community/uploads/default/original/1X/289b6731698abdf168a0903f248d6b8f64d4d162.gif)

#### Headers

In the Header property, you are able to add header parameters to the request in the format of `Name : Value` pairs.

Linx automatically includes the following headers when making a request:

- `Content-Type`: Depending on what was set as the Body format.

- `Content-Length`: The size of the request body.

- `Authorization`: Applicable when selecting the `Basic` built-in authentication Type.

 **Note:**

Custom authentication headers can be appended to this list by expanding the Headers property.

Typically this would involve authorization credentials being added to the headers in the case of Bearer or API Key authentication schemes.

See more about submitting custom authorization headers [here](#auth-api-key).

In order to add header parameters, expand the Headers property of the [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint) and add your parameters.

You are able to set the header parameters as plain text, a $.Setting⚙ value or a result of an expression.

#### Body format

This property refers to the `Content-Type` of the request body being sent.

The following types are available with their respective `Content-Type` header:

- **Text** : `text/plain; charset=utf-8`
- **XML** : `application/xml; charset=utf-8`
- **JSON** : `application/json; charset=utf-8`
- **Stream** : No `Content-Type` header is automatically added, you will need to supply the relevant `Content-Type` header specified by the target API.
- **URL** encoded content: `application/x-www-form-urlencoded`
- **Multi-part encoded content** : `multipart/form-data; boundary=#boundaryvalue#`

Whatever data value is in the Body at runtime, will be serialized into the `Content-Type` set by the Body format.

#### Body

This is where the data reference for the request body is set is set.

The data object referenced in the Body will be formatted by Linx automatically depending on the Body format.

 **Caution:** For GET methods, you are unable to supply a request body value.

Depending on what Body format is selected the available Body options will differ.

Typically, you would reference a CustomTYP as this value.

 **Tip:**  
  
 An example of submitting a request body can be found [here](https://community.linx.software/community/t/consuming-rest-apis-tutorial/484#sending-content). 

### Response

This section allows you to configure the structure of the data that Linx will deserialized the response being returned from the web service into.

#### Output type

The type (basic or complex) of data structure to deserialized the response body into.

If you create a CustomTYP and you have formatted your response accordingly, you can point the Output type field at your user defined CustomTYP . After the request has executed, Linx will map the returned result to the specified structure.

 **Learn:**  
  
More about handling responses [here](#handling-responses).

### Settings

#### Handle all status codes

Default: `False`

If left as `False`, an exception will be thrown at runtime if a HTTP Status Code not in the [200-299] range is returned (typically 4xx, 5xx).

To not throw an explicit exception, select the Handle all status codes . The UI will display 2 execution paths – **Success** and **Error**.

 ![image](https://community.linx.software/community/uploads/default/original/1X/e16a36a69fedc73ff4c611934f6004a5f73e269b.png)

Responses with the HTTP Status Code in the range of [`200` - `299`] will go into the **Success** execution path, while all other responses will go into the **Error** execution path.

 **Note:**  
  
Invalid requests, e.g. invalid hostnames, will throw an explicit exception, and will not go into the Error execution path.

#### Timeout

The timeout value (in milliseconds) for the request.

If a request takes longer than this timeout value then a exception similar to the below will be shown:

```http
Exception at CallRESTEndpoint:
Process.CallRESTEndpoint: Timeout of 100000ms reached. Task cancelled.

```

Typically this would indicate an issue on the server side, however with testing you must determine what the appropriate timeout value for this property is.

Timeouts are used to avoid ‘bottlenecking’ or ‘hanging’ in your application, whereby ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) flows may ‘stack up’ if a request is being attempted for too long.

#### Max response content size

The maximum amount of bytes response content can contain.

The purpose of this is to limit the amount of content retrieved in cases where you may request a heavy content URL, things such as incorrect URLs leading to full web pages are an example. If the size of the response is over this limit then the request will fail and an exception similar to the below will be shown:

```http
Exception at CallRESTEndpoint: 
Process.CallRESTEndpoint: Cannot write more bytes to the buffer than the configured maximum buffer size: 65536.

```

In order to retrieve content over this size, increase the Max response content size of the [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint) to the desired size.

* * *

## Authenticating requests

Authenticating requests in Linx has several approaches which depend on the security level and design choices of the target API.

The below sections highlight some of the most common authentication methods used in the industry today as well as how to submit requests with the relevant authentication in Linx.

### Anonymous

This is the default configuration, no built in authentication credentials are submitted with the request.

 **Note:**

If custom authentication credentials are required such as API keys or Bearer tokens then leave the Type as `Anonymous`.

### HTTP Basic

Basic authentication refers to `base64 encoded(username:password)` credentials included in a `Authorization header` like below:

```http
Authorization = Basic bXl1c2VybmFtZTpteXBhc3N3b3Jk

```

To submit HTTP Basic authentication credentials with a request:

1. Set the [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint) Authentication Type to `Basic`.
2. Complete the Username and Password fields that appear in the Properties.

When a request is made, the Username and Password will be automatically encoded and formatted into the required format for the `Authorization` header.

![CallRESTEndpoint - Basic Auth](https://community.linx.software/uploads/default/original/1X/2d2ae21e4dee97acb3f6786fe1f6bcc194c1ead1.gif)

### API Key

API Key authentication involves submitting a `key` in one of several places in a request (header, query). These API keys are usually generated on the source system front-end or provided by their support team. Due to the varying formats of API Key authentication, you will need to custom configure the appropriate API Key.

To submit API Key authentication credentials with a request:

1. Set the [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint) Authentication Type to `Anonymous`.

2. Expand the Headers editor

3. Add a new `Header` with the Name of the API Key i.e. `X-API-KEY`, `API-KEY` etc.

4. For the Value , add the API Key reference.

The example below submits a `X-API-KEY` header containing the API Key which is stored as a setting.

![CallRESTEndpoint - Add API Key to Header](https://community.linx.software/uploads/default/original/1X/c9e7b27cf53768bafe2f1d1f2c298af74799c9ea.gif)

 **Note:**

You are also able to add API Keys as query string values by expanding the Query string editor and adding the respective key in a similar format to the example above.

### Bearer Tokens

Bearer token authentication involves submitting a `token` in the `Authorization` header with a value of `Bearer {token}` like below:

```http
Authorization : Bearer eyJ0eXAiO ... 0X2tnSQLEANnSPHY0gKcgw

```

To submit a Bearer token with a request:

1. Set the [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint) Authentication Type to `Anonymous`.

2. Expand the Headers editor

3. Add a new Header with the Name of `Authorization`.

4. For the Value , open the expression editor.

5. Add the text `"Bearer "`

6. Combine the above with a reference to the `{token}` value like below:

The example below retrieves a `token` value from a database using an [ExecuteSQLFNC](https://linx.software/docs/reference/plugins/database/content/executesql) , then , using an expression, the `Authorization` header value is built up in the format of `Bearer {token from database}`:

![CallRESTEndpoint - Add Bearer Token](https://community.linx.software/uploads/default/original/1X/a7a305bce4553cf8c3981f29c793a3db8d28fe1e.gif)

* * *

## Handling responses

There are several approaches for handling responses with a [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint) . It is intentionally left as dynamic as possible in order to give maximum flexibility.

When you make a request using a [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint) , a `response body` will be returned (including `no-content`). The data contained in the `response body` will then be accessible to use in further Linx functions and services, for example, adding retrieved order records to a database.

The [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint) has the following output values:

- **ResponseHeaders** : Header list in the format `key:value` pairs which contain metadata associated with the response.
- **ResponseBody** : The `Response Body` of the object. This wil deserialized into the structure set as the Output type.
- **StatusCode** : The HTTP Status Code of the request i.e. `200` , `404`.

  

 **Sample:**  
  
 A practical demonstration of working with responses can be found [here](https://community.linx.software/community/t/consuming-rest-apis-tutorial/484#working-with-the-response-body). 

### Response status codes

The most common response HTTP status codes are discussed below with regards to what they indicate and what troubleshooting can be done, for a full list of description visit [here](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes).

| **Status Code** | **Description** | | |
| --- | --- | --- | --- |
| **`1XX`** | `Informational` | | |
| **`2XX`** | `Success` | The response was successful. | |
| **`3XX`** | `Redirection` | The response contains resources that should be used in subsequent requests or redirection requests. | |
| **`4XX`** | `Client Error` | The submitted request contained invalid formatting. | |
| **`5XX`** | `Server Error` | A critical error occurred on the server-side of the request. | |

**Common**

| **Status Code** | **Phrase** | **Description** | **Probable error** |
| --- | --- | --- | --- |
| **`200`** | `OK` | Successful request | |
| **`401`** | `Unauthorized` | Security validation failures or authentication failures. | Incorrect authentication credentials or incorrect format of submitted authorization credentials. |
| **`400`** | `Bad Request` | Indicates issue with request, typically an incorrect `body` has been submitted. | Incorrect body format or type. |
| **`415`** | `Unsupported Media Type` | Indicates a request `body` has been submitted which is not allowed. | Indicates that either an incorrect content-type header has been included or that the response body submitted does not correspond to an accepted format. |
| **`500`** | `Internal Server Error` | Indicates fatal error on the server side of the request, typically error details are excluded from this response. | Due to the issue being on the server-side, there is very little you can do due to the limited error information. |

Example of a unsuccessful request:

```auto
 Exception at CallRESTEndpoint:
 Process.CallRESTEndpoint : Response status code does not indicate success: 404 (NotFound).

```

 **Tip:**

To not explicitly throw an exception when an error status code is returned, select the Handle all status code property.

### Setting the output type of the response

Typically, responses are returned as JSON (and XML occasionally), and this `response body` would normally contain several fields and objects related to the request.

An example of a JSON response

```auto
    {
      "id": "4668200040404",
      "inv_number": "gg_456",
      "date": "2020-06-15T11:55:01.7400485+02:00",
      "customer_id": "701",
      "total": 450.0,
      "status": "paid"
    }

```

By default, the [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint)Output type is set to a [StringTYP](https://linx.software/docs/reference/plugins/linx/content/string) . This means the whole response is returned from the function as text and no deserialization is performed on the data.

In order to make the response easier to manage and work with, you are able to create CustomTYP objects and set these as the output type of the [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint) function.

The `response body` will then be deserialized into this object, the individual fields and objects will then be available to use in conjunction with other functions in your process, operation or event.

#### Import from API Documentation

Typically, API documentation will provide examples of request and responses ( An example can be found from Microsoft Graph [here](https://docs.microsoft.com/en-us/graph/api/site-get?view=graph-rest-1.0&tabs=http#response) ).

```auto
{
  "id": "contoso.sharepoint.com,2C712604-1370-44E7-A1F5-426573FDA80A,2D2244C3-251A-49EA-93A8-39E1C3A060FE",
  "displayName": "OneDrive Team Site",
  "name": "1drvteam",
  "createdDateTime": "2017-05-09T20:56:00Z",
  "lastModifiedDateTime": "2017-05-09T20:56:01Z",
  "webUrl": "https://contoso.sharepoint.com/teams/1drvteam"
}

```

You can copy this JSON out and import it as a CustomTYP.

 **Tip:**  
  
 In cases where the API documentation is lacking, you are able to retrieve a response by following the below section 

#### Import from an initial request’s response

If the API documentation is limited, you are able to copy the text returned in the response body as a CustomTYP. This is done making a request to the endpoint and using the response as the base template for the CustomTYP.

In order to do this:

1. Right click on the [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint) in your ~~process~~ [_Function_](https://linx.software/docs/releasenotes/linx/5.20.2.0/) and click **Enable Logging**.
2. Set the Output type to `String`
3. **Debug** your Process.
4. Copy the `response body` returned in the **Debug Output**.
5. Right-click on a **Project** in the Solution Explorer.
6. Click **Import Custom Type**
7. Paste the copied text in the editor and update the Name .

![Connecting to REST APIs - Tutorial - Import Response](https://community.linx.software/uploads/default/original/1X/bd9f22582592edd71ad36b0863d162bf58b239c8.gif)

 **Caution:**  
  
Be aware however, using this approach does leave room for error as you are relying on a single response to determine the structure for all subsequent responses. It is therefore suggested that you use several example responses to ensure all the necessary fields are added, additionally the more "safe" route is to define your Custom Type using a field editor or using JSON/XML schema.

If a response is returned that does not conform to the Custom Type then an exception will be thrown. If you are missing fields or need to alter the types, you are always able to add and edit a Custom Type’s fields using the field editor.

  
You are then able to reference the CustomTYP in the Output type of the [CallRESTEndpointFNC](https://linx.software/docs/reference/plugins/rest/content/callrestendpoint).   

![Connecting to REST APIs - Tutorial - Setting JokeResponse](https://community.linx.software/uploads/default/original/1X/7e8638bbf1c1ae1c2a55a8661f5fb00751586a6b.gif)

  

 **Tip:**  
  
 Take a look at [these](https://community.linx.software/community/t/custom-type-import-conventions/480) articles to see more about CustomTYP import conventions.

### Next steps?

> 🚀 [Get started](https://community.linx.software/community/t/consuming-rest-apis-tutorial/484) with consuming REST APIs.
