REST API Integration for AS2
With AS2 Gateway REST API, you can programmatically send AS2 messages, check and retrieve received messages, and so forth. This is a very convenient AS2 integration mechanism for any trading system that is capable of making HTTP calls.
The current version of the AS2 Gateway API is v1. API details and specification are available as online documentation as well as a downloadable PDF reference. The complete API list and documentation with examples code snippets can be found here.
1 REST API - v1
All the API calls should be made under the base path https://api.as2gateway.com/v1. HTTP requests will be automatically redirected to HTTPS with a HTTP 307 response.
API calls are rate-limited at 50 requests per each 10-second period.
v1 API is protected with token-based authentication, dependent on a predefined data model, and supports the following operations:
- send (enqueue) messages
- list messages
- get (retrieve) individual messages, and mark them as read
- download message attachments and MDN payloads
- control retry behavior for queued messages
2 Authentication
The AS2 Gateway API uses JWT token based authentication. Endpoint to obtain the token is as follows.
Get JWT Token
POST /:v/authorize
Content-Type: application/json
{
"username": "<email>",
"password": "<password>"
}
200 OK
Content-Type: application/json
{
"token": "<token_string>",
"expiry": <expiry_timestamp>
}
E.g.:
curl -XPOST https://api.as2gateway.com/v1/authorize \
-H 'Content-Type: application/json' \
--data '{"username":"email@domain.com","password":"pazzword"}'
The received authorization token should be added as an Authorization header for all other requests:
Authorization: <token_string>
Note: Do not include any scheme part (Basic, Bearer etc.) on the header.
The token will generally be valid for ~24 hours (as indicated by the expiry field), so you can use it for multiple API calls without having to re-authenticate frequently.
3 Data Model
This is a brief overview of the types of entities (payloads) returned by different endpoints of AS2 Gateway REST API.
3.1 Generic Response
An entity with a single message (String) field, returned as an acknowledgement of an action (e.g. submitting a message) or an error description (e.g. failure to find an AS2 message by the given ID):
{"message": "Successfully added a new outbound entry"}
3.2 AS2 Message
Represents an AS2 message sent/received by AS2 Gateway, with the following attributes:
- as2MessageId (String) - AS2 message ID
- persistedTimestamp (Long) - timestamp in milliseconds
- compressed (Boolean) - true or false depicting whether the AS2 message was compressed
- encrypted (Boolean) - true or false depicting whether the AS2 message was encrypted
- signed (Boolean) - true or false depicting whether the AS2 message was signed
- subject (String) - Subject of AS2 message. If there is no subject, this field will not be included in the response.
- receiverId (String) - AS2 ID of the AS2 partner who has sent/received this message
- senderId (String) - AS2 ID of the AS2 station which has received/sent this message
- transportStatusReceived (Integer, optional) - HTTP response code received. Only available on sent messages.
- deliveryStatus (String, optional) - AS2-level delivery status of the AS2 message. Only available on sent messages. Possible values are Delivered, Not Delivered and No Status.
- mdnStatus (String) - Delivery status of MDN. Possible values are Pending, Received, Not Requested and No MDN.
- partnerType (String) - AS2 Partner type. Possible values are Production and Test
- mdnMessage (MDN Message, optional) - represents the MDN sent/received for this AS2 message
- attachments (Array of Attachments) - the attachments sent/received in this AS2 message
3.3 MDN Message
Represents a receipt, i.e. disposition notification (MDN) message received/sent by AS2 Gateway, with the following attributes:
- persistedTimestamp (Long) - timestamp in milliseconds when the message was saved in AS2 Gateway
- mdnError (Boolean) - true or false depicting whether the received MDN is an error MDN or not
- content (String) - String with human-readable part of the MDN received
3.4 Attachment
Represent details of a single attachment sent/received by AS2 Gateway (usually appearing within a list of attachments), with the following attributes:
- name (String) - attachment file name
- size (Integer) - size of the attachment in bytes
3.5 Partner
Represents details of a trading partner:
as2Identifier
(String): partner’s AS2 IDname
(String): name assigned to partner on AS2Gdescription
(String): description set on partner’s settingsuri
(String): partner’s message receive URL/endpointmessageSubject
(String): default message subject assigned to partner; will be used if a subject is not specified when submitting a new messageencryptionAlgorithm
(String): encryption algorithm used for outgoing messages to this partnersignDigestAlgorithm
(String): signing algorithm used for outgoing messages to this partnerencryptCert
({id: Number}): structure with encryption certificateid
assigned to partner; used to encrypt outgoing messagessignCert
({id: Number}): structure with signing certificateid
assigned to partner; used to verify signatures of incoming messages/MDNs; often same as encryption certificateuseDiffCertAsSignCert
(Boolean): will betrue
ifsignCert
is different fromencryptCert
(partner uses two certificates for the two purposes)httpsCert
({id: Number}): structure with HTTPS certificateid
assigned to partner; used to verify/trust partner’s AS2 endpoint if it uses HTTPSencryptMessages
(Boolean):true
if encryption is enabled for outgoing messagessignMessage
(Boolean):true
if signing is enabled for outgoing messagescompressAfter
(Boolean):true
if compression mode is set to “After signing and/or encryption”compressBefore
(Boolean):true
if compression mode is set to “Before signing and/or encryption”requestAsyncMdn
(Boolean):true
if Request Asynchronous MDN option is enabledrequestMdn
(Boolean):true
if Request MDN option is enabledrequestSignedMdn
(Boolean):true
if Request Digitally Signed MDN option is enabledrequestHttpsMdn
(Boolean):true
if Request MDN over HTTPS option is enabledcustomHeaders
(Array<{headerKey: String, headerValue: String}>): custom HTTP request headers configured for outgoing messagesuseAs2Restart
(Boolean):true
if Use AS2 Restart option is enabledpauseIncoming
(Boolean):true
if incoming traffic is paused for the partnerpauseOutgoing
(Boolean):true
if outgoing traffic is paused for the partnersendTimeout
(Number): number of seconds that an outgoing message from this partner is allowed to wait for a responseflows
(Array<String>): custom integration flows that are enabled for this partner’s messagespartnerType
(String):Production
orTest
, based on type of the partnerisGlobalPartner
(Boolean):false
(not yet supported)pinned
(Boolean):true
if the partner is pinned on the partner-list dashboard
3.6 Station
Represents details of a trading station:
as2Identifier
(String): station’s AS2 IDname
(String): name assigned to station on AS2Gcomments
: description set on station’s settingsemail
(String): email address assigned to station; used for message-related notification delivery and in theDisposition-Notification-To
outbound AS2 headercertificate
({id: Number}): structure with station certificate (key pair)id
assigned to station; used to decrypt incoming messages and sign outgoing messages/MDNssftpStructure
(Number): zero-based index/ordinal of inbox folder structure for SFTP, S3, etc.emailNotifications
(Boolean):true
if email notifications are enabled for incoming messagessendFailureEmails
(Boolean):true
if email notifications are enabled for message send-out failuressendMdnFailureEmails
(Boolean):true
if email notifications are enabled for MDN-related failures (receiving an error MDN, MIC mismatch, etc.)pinned
(Boolean):true
if the station is pinned on the station-list dashboard
3.7 Pagination
Represents a collection of entities (usually AS2 Messages) returned from a pagination-enabled endpoint (usually a list endpoint)
- totalRecords (Integer) - the total number of results that match the query
- records (Array) - a subset of those results based on the requested pageOffset and pageLength
An example pagination response of AS2 Message entities would be as follows:
{
"totalRecords": 10,
"records": [
{ // an AS2 Message entity
"as2MessageId": "<as2@message.id>",
...,
"mdnMessage": { // (nested) an optional MDN Message entity
"persistedTimestamp": 1556797479000,
...
},
"attachments": [ // (nested) an array of Attachment entities
{
"name": "file1.txt",
"size": 391
},
...
]
},
// more AS2 Message entities
]
}
4 Send (Enqueue) AS2 Message
4.1 Request
4.1.1 Sending a Single File
POST /:v/message/:as2_station_id/:as2_partner_id
Authorization: <token_string>
Content-Type: <mime_type_of_file>
Content-Length: <size_of_file>
Name: <name_of_file>
<content_of_file> goes in the request body
4.1.2 Sending Multiple Files
POST /:v/message/:as2_station_id/:as2_partner_id
Authorization: <token_string>
Content-Type: multipart/form-data; boundary=<multipart_boundary>
--<multipart_boundary>
Content-Disposition: form-data; name="file"; filename=<name_of_file_1>
Content-Type: <mime_type_of_file_1>
<content_of_file_1>
--<multipart_boundary>
Content-Disposition: form-data; name="file"; filename=<name_of_file_2>
Content-Type: <mime_type_of_file_2>
<content_of_file_2>
--<multipart_boundary>--
4.2 Path Parameters
- :as2_station_id: AS2 identifier of the AS2 Station from which you want to send the AS2 message out
- :as2_partner_id: AS2 identifier of the AS2 Partner to which you want to send the AS2 message out
4.3 Query Parameters (Optional)
partnerType
: Possible values:production
andtest
. If unspecified, defaults to production.subject
: Any subject string can be usedprofile
: name of a message submission profile to use for composing this message, such as to include additional profile-specific HTTP transmission headers
4.4 Request Payload
4.4.1 Single File
Include the raw content of the file as the payload (similar to how curl –data-binary @path/to/file works).
File/payload can be up to 10 MB in size.
Also specify the following request headers, which provide mandatory metadata about the file:
- Name: name of the file that you are sending (e.g. invoice-12345.edi); what you provide here will be the name of the file received on the partner’s side.
- Content-Type: MIME type of the file (e.g. text/xml for XML, application/edi-consent for EDI, etc. If you do not know the MIME type and are not interested in including that information in the message, you may use the generic type application/octet-stream.
- Content-Length: The size (number of bytes) of the file that you are sending (e.g. 94813)
Notes:
- Many common tools and programming libraries will automatically compute and include the last two headers on your behalf, if you use their “upload file” functionality. In such cases you would only need to include the Name header explicitly.
- If you do not specify a MIME type (Content-Type), AS2G will auto-detect it by file extension - and by content (EDI sub-types for “.edi” extension).
4.4.2 Multiple Files: multipart/form-data
A multipart payload containing one or more “file” parts (attachment payloads to be sent). Each attachment must have a unique filename.
You can add up to 10 files per message, adding up to a total size of 10 MB.
4.5 Response
202 Accepted
Content-Type: application/json
Link: https://api.as2gateway.com/v1/message/sent/<90766548.41.1573209810390@as2gateway.com>
{
"message": "Successfully added a new outbound entry"
}
4.5.1 Response Headers
Link
: An absolute URL to the AS2 message which will be created after the outgoing message entry is processed. Therefore, the resource in this URL may not be available immediately after the response for this API call is returned. It would be better to wait around 5 to 10 seconds before querying for the resource represented in the Link header value.
Note that the header includes the AS2 message ID for this outgoing message entry.
4.6 Examples
Sending a Single File
If you are generating the content (i.e. there is no actual local file):
curl -XPOST https://api.as2gateway.com/v1/message/RJ_Station/RJ_Partner \
-H "Authorization: <token_string>" \
-H "Name: invoice_20200101.xml" \
-H "Content-Type: text/xml" \
-H "Content-Length: 132" \
--data-binary \
'<?xml version="1.0" encoding="UTF-8"?>
<invoice>
<items total="1000">
<item sku="10344" qty="10" total="1000"/>
</items>
</invoice>'
If you are sending an already generated/existing file:
curl -XPOST https://api.as2gateway.com/v1/message/RJ_Station/RJ_Partner \
-H "Authorization: <token_string>" \
-H "Name: invoice_20200101.xml" \
-H "Content-Type: text/xml" \
--data-binary @invoice_20200101.xml
Sending Two (or More) Files
curl -XPOST https://api.as2gateway.com/v1/message/RJ_Station/RJ_Partner \
-H "Authorization: <token_string>" \
-H "Content-Type: multipart/form-data; boundary=----foobarbaz" \
--data-binary \
'------foobarbaz
Content-Disposition: form-data; name="file"; filename="file1.txt"
Content-Type: text/plain
one
------foobarbaz
Content-Disposition: form-data; name="file"; filename="file2.txt"
Content-Type: text/plain
two
------foobarbaz--'
4.7 Queueing (asynchronous) nature
Please note that, similar to the AS2 Gateway web dashboard, this simply places the newly submitted message into a queue, in a to-be-sent state; it may take several seconds before the message actually gets sent out.
Additionally, if the actual send action fails, the message will not appear under the sent messages category; and the URL previously returned in the Link header would no longer be valid. In such cases it is advised to check failed and queued categories to find out the current status of the message.
5 Listing AS2 Messages
These endpoints share a common set of query parameters (all optional):
- sortCol - Column name to sort data. Possible values are persistedTimestamp, receiverId, senderId and subject. Defaults to persistedTimestamp.
- sortDir - Sort direction. Possible values are asc and desc. Defaults to desc.
- partnerType - Possible values are production and test. Default value is production.
- pageOffset - Page number. An integer value greater or equal to zero is accepted. Default is zero.
- pageLength - Length of a page. An integer value greater than or equal to 1 and less than or equal to 100 is accepted. Default is 10.
- partnerAS2Id - AS2 identifier of the AS2 Partner that sent/received these messages
- stationAS2Id - AS2 identifier of the AS2 Station that received/sent these messages
- as2MessageId - ID of the required AS2 message(s)
- subject - Any subject string, to filter messages against
During filtering, all filter parameters (other than pagination and sorting) are combined (effective AND).
For all successful responses,
- the response status will be HTTP 200 OK.
- the response payload will be a Pagination of AS2 Message entities.
5.1 Received
GET /:v/message/received
The received endpoint supports an additional unreadOnly (Boolean) flag (query parameter) to allow skipping of messages that have already been “marked as read” within the API scope. This can be useful for ensuring one-time processing of messages, e.g. retrieve a batch of unprocessed messages and then mark each as “read” when done.
5.2 Successfully sent
GET /:v/message/sent
5.3 Send-failed
GET /:v/message/failed
Since AS2 Gateway retries queued messages up to 10 times, and each retry uses the same AS2 message ID, the failed endpoint may return multiple messages with the same AS2 ID.
5.4 Queued (pending-send)
GET /:v/message/queued
For the queued endpoint, instead of partnerAS2Id, stationAS2Id, as2MessageId, and subject, there is a single parameter named query that can accommodate a single value from any of the four types.
For example, for checking a queued message with ID
GET /:v/message/queued?query=<foo>
Currently, queued endpoint will only return messages that are not in “processing” status (actively being sent out at the moment of making the API call). Hence, a given queued message may sometimes not appear in the retrieved list, although it may still be effectively in the queue.
6 Retrieving an AS2 Message
Each endpoint accepts an :as2_message_id
path parameter indicating the AS2 message to be retrieved.
For all successful responses,
- the response status will be HTTP 200 OK.
- the response payload will be an AS2 Message entity.
6.1 Received
GET /:v/message/received/:as2_message_id
This endpoint supports an additional markAsRead (Boolean) query parameter. If this is set to true, the message will be “marked as read” upon retrieval; any list queries with unreadOnly=true will not return it afterwards. You can combine this and the unreadOnly query parameter, to ensure one-time processing of received messages. (Note that this marking happens only at API scope; marked messages may still appear as unread on the AS2 Gateway Inbox.)
6.2 Successfully sent
GET /:v/message/sent/:as2_message_id
6.3 Send-failed
GET /:v/message/failed/:as2_message_id
6.4 Queued (pending-send)
GET /:v/message/queued/:as2_message_id
Currently, some AS2 message attributes (such as attachments) may be missing from the queued endpoint response.
Marking an AS2 Message as Unread
If a message has been marked as read via the API (using the markAsRead query parameter), it will not be returned in subsequent listing API calls. This behavior can be restored by marking the message as unread again.
POST /:v/message/received/:as2_message_id/markUnread
:as2_message_id
: The AS2 message identifier of the relevant message
HTTP 200 OK
{
"message": "Successfully marked message <id> as unread"
}
7 Downloading Attachments
Each endpoint accepts an :as2_message_id
path parameter indicating the source AS2 message.
For messages containing multiple attachments, an additional :index
path parameter can be provided to specify which attachment to download. The parameter is zero-based; e.g. for a message with 5 attachments, valid values for :index would be 0 through 4. If :index is unspecified, only the first attachment (position 0) will be downloaded.
The received endpoints support an additional markAsRead (Boolean) query parameter (similar to the equally named flag on the message retrieve endpoint). If this is set to true, the message associated with the attachment(s) will be “marked as read” upon retrieval so that any list queries with unreadOnly=true will not return it afterwards.
For all successful responses,
- the response status will be HTTP 200 OK
- the response payload will be the binary data of the attachment, with Content-Type: application/octet-stream
- the attachment file name will be available in the Content-Disposition header: Content-Disposition: attachment; filename=
7.1 Received AS2 Message
GET /:v/message/received/:as2_message_id/attachments
GET /:v/message/received/:as2_message_id/attachments/:index
7.2 Sent AS2 Message
GET /:v/message/sent/:as2_message_id/attachments
GET /:v/message/sent/:as2_message_id/attachments/:index
7.3 Downloading Multiple Attachments
Single AS2 Message
GET /:v/message/received/:as2_message_id/attachments/all
GET /:v/message/sent/:as2_message_id/attachments/all
Multiple AS2 Messages (Batch Download)
POST /:v/message/received/batch/attachments
Submit the message IDs whose attachments you want to download (up to 100), as a JSON array in the request body:
POST /:v/message/received/batch/attachments
Authorization: <token_string>
Content-Type: application/json
["message-id-1","message-id-2",...]
You can also pass in a markAsRead query parameter to automatically mark these messages as read, after downloading their attachments.
The response payload will be a zip archive (Content-Type: application/octet-stream) containing attachments of each message under a folder named after the respective message ID:
<zip archive>
|
|__message-id-1/
| |
| |__attachment-1-1
| |__attachment-1-2
|
|__message-id-2/
| |
| |__attachment-2-1
| |__attachment-2-2
...
If the API failed to find attachments for any provided message ID, the corresponding folder inside the archive will contain a .error file with the respective error message.
If the total size of aggregated attachments exceeds 10 MB, the API will stop the aggregation, and return the set of attachments aggregated so far, as the zip content.
In the above case, the response HTTP code will be 206 Partial Content (instead of the usual 200), and the zero-based index of the last successfully added attachment will be indicated in an X-Batch-Truncation-Index HTTP response header. For example, if the size limit was reached after adding the 3rd attachment (index 2) of the 2nd message (index 1), the header would be:
X-Batch-Truncation-Index: (1,2)
Also in this case, if markAsRead flag is set, only the fully-archived messages would be marked as read; in above example, only message-id-1 would be marked, because message-id-2 was only partially downloaded.
7.4 Downloading MDNs
Endpoint specification is the same as attachment download.
Received AS2 Message
GET /:v/message/received/:as2_message_id/mdn
Sent AS2 Message
GET /:v/message/sent/:as2_message_id/mdn
8 Controlling Message Retry
In some cases, queued messages may remain in retrying state for various reasons, e.g. unavailability of the partner endpoint. In such cases, you can invoke the following endpoints to stop/resume the retry process.
8.1 Stopping Retrying of a Queued AS2 Message
POST /:v/message/queued/:as2_message_id/stop
:as2_message_id
- The AS2 message identifier of the message to stop retrying
HTTP 200 OK
{
"message": "Successfully stopped retrying AS2 message with ID <id>"
}
8.2 Resuming Retrying of a Stopped AS2 Message
POST /:v/message/queued/:as2_message_id/retry
:as2_message_id
- The AS2 message identifier of the message to resume retrying
HTTP 200 OK
{
"message": "Successfully started retrying AS2 message with ID <id>"
}
9 Cleaning up (deleting) messages
9.1 Delete single message: DELETE /:message_type:/:message_as2_id:
You can delete a message under a specific category, by issuing a DELETE request to /:message_type:/:message_as2_id:
9.1.1 Path parameters
:message_type:
: type/location of the message to delete:received
: inboxsent
: “Sent” listqueued
: message-queue entries that are currently being sent/retried; from “Outbox” liststopped
: incomplete (not sent) message-queue entries, which have exhausted auto-retries or been stopped manually; from “Stopped” listfailed
: individual message entries that have failed during sending; from “Failure Log” list
:message_as2_id:
: AS2 identifier (Message-ID
) of the message/queue entry to be deleted
9.2 Bulk deletion: DELETE /:message_type:
You can delete up to 100 messages in a single DELETE request issued to /:message_type:
(see above “path parameters” section).
9.2.1 Request body
Provide a JSON array containing the list of AS2 identifiers (Message-ID
s) of the message/queue entries to be deleted.
["message-id-1","message-id-2",...]
9.2.2 Response
{"message": "Deleted 3 messages"}
10 Partner API
10.1 Partner list/search: GET /partner
List all partners available in your AS2G account, optionally filtered by name or AS2 ID.
10.1.1 Query parameters
query
: string to use to filter partners, by assigned name or AS2 identifier (partial matches accepted)
10.1.2 Response
JSON array containing matching Partner entries
[
{
"partnerId": 3,
"as2Identifier": "foo",
"compressAfter": false,
"compressBefore": false,
"precompressInputFiles": false,
"encryptCert": {
"id": 5
},
"signCert": {
"id": 7
},
"useDiffCertAsSignCert": true,
"encryptMessages": true,
"name": "Foo",
"requestAsyncMdn": false,
"requestMdn": true,
"requestSignedMdn": true,
"requestHttpsMdn": false,
"signMessage": true,
"uri": "http://as2.foo/bar",
"encryptionAlgorithm": "AES256_CBC",
"signDigestAlgorithm": "SHA256",
"signEncryptAlgorithm": "RSA",
"isGlobalPartner": false,
"partnerType": "Production",
"httpsCert": {
"id": 8
},
"pinned": false,
"customHeaders": [
{
"headerKey": "key",
"headerValue": "value"
}
],
"useAs2Restart": false,
"pauseIncoming": false,
"pauseOutgoing": false,
"sendTimeout": 60,
"flows": [
"EDIG"
]
}
]
11 Station API
11.1 Station list/search: GET /station
List all stations available in your AS2G account, optionally filtered by name or AS2 ID.
11.1.1 Query parameters
query
: string to use to filter stations, by assigned name or AS2 identifier (partial matches accepted)
11.1.2 Response
JSON array containing matching Station entries
[
{
"id": 2,
"as2Identifier": "bar",
"email": "bar@acme.com",
"certificate": {
"id": 4
},
"name": "Bar",
"pinned": false,
"sftpStructure": 0,
"emailNotifications": false,
"sendFailureEmails": true,
"sendMdnFailureEmails": true
}
]