Navigation

http.post()

Definition

http.post()

Sends an HTTP POST request to the specified URL.

Usage

Example

Note

This example assumes you have created an HTTP service called “myHttp”. If you do not need this HTTP action validated with Service Rules, you can use the context.http module.

exports = function() {
  const http = context.services.get("myHttp");
  return http.post({
      url: "https://www.example.com/messages",
      body: { msg: "This is in the body of a POST request!" },
      encodeBodyAsJSON: true
    })
    .then(response => {
      // The response body is encoded as raw BSON.Binary. Parse it to JSON.
      const ejson_body = EJSON.parse(response.body.text());
      return ejson_body;
    })
};

In the JavaScript Client SDKs, you call HTTP service actions by passing a configured and built HttpRequest object to the HTTP service client’s execute() method.

You configure the HTTPRequest object by instantiating a new HTTP request builder and passing parameters to its builder methods. Once you’ve configured a request, you build it by calling the builder’s .build() method.

import { Stitch } from 'mongodb-stitch-browser-sdk';
import {
  HttpServiceClient,
  HttpRequest,
  HttpMethod
} from 'mongodb-stitch-browser-services-http';

// 1. Instantiate an HTTP Service Client
const app = Stitch.defaultAppClient;
const http = app.getServiceClient(HttpServiceClient.factory, "myHttp");

// 2. Build a new HttpRequest
const request = new HttpRequest.Builder()
  .withMethod(HttpMethod.POST)
  .withUrl("https://www.example.com/messages")
  .withBody({ msg: "This is in the body of a POST request!" })
  .build();

// 3. Execute the built request
http.execute(request)
  .then(console.log)
  .catch(console.error)

In the Java/Android Client SDK, you call HTTP service actions by passing a configured and built HttpRequest object to the HTTP service client’s execute() method.

You configure the HTTPRequest object by instantiating a new HttpRequest.Builder and passing parameters to its builder methods. Once you’ve configured a request, you build it by calling the builder’s .build() method.

// 1. Instantiate an HTTP Service Client
StitchAppClient client = Stitch.getDefaultAppClient();
StitchServiceClient http = client.getServiceClient(HttpServiceClient.factory, "myHttp");

// 2. Build a new HttpRequest
HttpRequest request = new HttpRequest.Builder()
  .withMethod(HttpMethod.POST)
  .withUrl("https://www.example.com/diff.txt")
  .withBody(Document("msg", "This is in the body of a POST request!"))
  .build();

// 3. Execute the built request
http.execute(request)
  .addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull final Task<Void> task) {
      if (task.isSuccessful()) { Log.d("stitch", "Successfully sent POST request!"); } else { Log.e("stitch", "Error sending POST request:", task.getException()); }
    }
  });

In the Swift/iOS Client SDK, you call HTTP Service actions by passing a configured and built HTTPRequest object to the HTTP service client’s execute() method.

You configure the HTTPRequest object by instantiating a new HTTPRequestBuilder and passing parameters to its builder methods. Once you’ve configured a request, you build it by calling the builder’s .build() method.

// 1. Instantiate an HTTP Service Client
let app = Stitch.defaultAppClient!
let http: HTTPServiceClient = app.serviceClient(
  fromFactory: httpServiceClientFactory,
  withName: "myHttp"
)

// 2. Build a new HTTPRequest
let request: HTTPRequest = HTTPRequestBuilder()
  .with(method: HTTPMethod.post)
  .with(url: "https://www.example.com/diff.txt")
  .with(body: ["msg", "This is in the body of a POST request!"])
  .build()

// 3. Execute the built request
http.execute(request) { result in
  switch result {
  case .success:
    print("Successfully sent POST request!")
  case .failure(let error):
    print("Error sending POST request: \(error)")
  }
}

Parameters

The http.post() action accepts one argument of the following form:

{
    "url": <string>,
    "headers": <document>,
    "body": <string>,
    "form": <document>,
    "cookies": <string>,
    "authUrl": <string>,
    "followRedirects": <boolean>
}
Field Description

Request URL

url: <string>
Required. The target URL for the HTTP request. Alternatively, you can specify the components of the URL as root-level fields. See Alternative URL Arguments.

Request Body

body: <string>
Required. The stringified body of the HTTP request. If the request payload has a content type of multipart/form-data, use the form parameter instead of body.

Form Request Body

form: <document>

A document where each field maps to a field in a multipart/form-data request. This parameter cannot be used at the same time as the body parameter.

Note

Requests that use the form parameter should also include a Content-Type: multipart/form-data header.

Example

"form": {
  "to-address": "name@example.com",
  "from-address": "other-name@example.com",
  "subject": "test subject please ignore",
  "message-body": "hello from the message body"
}

Request Headers

headers: <document>

Optional. A document where each field name corresponds to a type of HTTP header and each field value is an array of one or more string values for that header.

Example

{
  "Content-Type": [ "application/json" ]
}

Request Cookies

cookies: <document>

Optional. A document where each field name corresponds to a cookie name and each field value is that cookie’s string value.

Example

{
  "favoriteTeam": "Chicago Cubs"
}

Request Authentication URL

authUrl: <string>
Optional. A URL that grants authorization cookies for the HTTP request.

Follow Redirects

followRedirects: <boolean>
Optional. If true, the request will follow any HTTP redirects it receives for the target URL.

You can configure HTTP POST request parameters with the following builder methods:

Builder Method Description

HTTP Method

.withMethod(<HttpMethod>)
.withMethod(<HttpMethod>)
.with(method: <HTTPMethod>)

Required. The HTTP method of the request. For POST requests, use the following:

.withMethod(HttpMethod.POST)
.withMethod(HttpMethod.POST)
.with(method: HTTPMethod.post)

Request URL

.withUrl(<string>)
.withUrl(<string>)
.with(url: <string>)
Required. The target URL for the HTTP request.

Request Body

.withBody(<Any>)
.withBody(<Object>)
.with(body: <Data>)

Required. The body of the HTTP request.

If encodeBodyAsJson is not set (or is set to false) the request body must be either a string or a binary.

If the request payload has a content type of multipart/form-data, use the form parameter instead of body.

Form Request Body

.withForm(<document>)
.withForm(<document>)
.with(form: <document>)

A document where each field maps to a field in a multipart/form-data request. This parameter cannot be used at the same time as the body parameter.

Note

Requests that use the form parameter should also include a Content-Type: multipart/form-data header.

Example

"form": {
  "to-address": "name@example.com",
  "from-address": "other-name@example.com",
  "subject": "test subject please ignore",
  "message-body": "hello from the message body"
}

Request Headers

.withHeaders(<document>)
.withHeaders(<document>)
.with(headers: <document>)

Optional. A document where each field name corresponds to a type of HTTP header and each field value is an array of one or more string values for that header.

Example

{
  "Content-Type": [ "application/json" ]
}

Request Cookies

.withCookies(<document>)
.withCookies(<document>)
.with(cookies: <document>)

Optional. A document where each field name corresponds to a cookie name and each field value is that cookie’s string value.

Example

{
  "favoriteTeam": "Chicago Cubs"
}

Request Authentication URL

.withAuthUrl(<string>)
.withAuthUrl(<string>)
.with(authURL: <string>)
Optional. A URL that grants authorization cookies for the HTTP request.

Follow Redirects

.withFollowRedirects(<boolean>)
.withFollowRedirects(<boolean>)
.with(followRedirects: <boolean>)
Optional. If true, the request will follow any HTTP redirects it receives for the target URL.

You can configure HTTP POST request parameters with the following builder methods:

Builder Method Description

HTTP Method

.withMethod(<HttpMethod>)
.withMethod(<HttpMethod>)
.with(method: <HTTPMethod>)

Required. The HTTP method of the request. For POST requests, use the following:

.withMethod(HttpMethod.POST)
.withMethod(HttpMethod.POST)
.with(method: HTTPMethod.post)

Request URL

.withUrl(<string>)
.withUrl(<string>)
.with(url: <string>)
Required. The target URL for the HTTP request.

Request Body

.withBody(<Any>)
.withBody(<Object>)
.with(body: <Data>)

Required. The body of the HTTP request.

If encodeBodyAsJson is not set (or is set to false) the request body must be either a string or a binary.

If the request payload has a content type of multipart/form-data, use the form parameter instead of body.

Form Request Body

.withForm(<document>)
.withForm(<document>)
.with(form: <document>)

A document where each field maps to a field in a multipart/form-data request. This parameter cannot be used at the same time as the body parameter.

Note

Requests that use the form parameter should also include a Content-Type: multipart/form-data header.

Example

"form": {
  "to-address": "name@example.com",
  "from-address": "other-name@example.com",
  "subject": "test subject please ignore",
  "message-body": "hello from the message body"
}

Request Headers

.withHeaders(<document>)
.withHeaders(<document>)
.with(headers: <document>)

Optional. A document where each field name corresponds to a type of HTTP header and each field value is an array of one or more string values for that header.

Example

{
  "Content-Type": [ "application/json" ]
}

Request Cookies

.withCookies(<document>)
.withCookies(<document>)
.with(cookies: <document>)

Optional. A document where each field name corresponds to a cookie name and each field value is that cookie’s string value.

Example

{
  "favoriteTeam": "Chicago Cubs"
}

Request Authentication URL

.withAuthUrl(<string>)
.withAuthUrl(<string>)
.with(authURL: <string>)
Optional. A URL that grants authorization cookies for the HTTP request.

Follow Redirects

.withFollowRedirects(<boolean>)
.withFollowRedirects(<boolean>)
.with(followRedirects: <boolean>)
Optional. If true, the request will follow any HTTP redirects it receives for the target URL.

You can configure HTTP POST request parameters with the following builder methods:

Builder Method Description

HTTP Method

.withMethod(<HttpMethod>)
.withMethod(<HttpMethod>)
.with(method: <HTTPMethod>)

Required. The HTTP method of the request. For POST requests, use the following:

.withMethod(HttpMethod.POST)
.withMethod(HttpMethod.POST)
.with(method: HTTPMethod.post)

Request URL

.withUrl(<string>)
.withUrl(<string>)
.with(url: <string>)
Required. The target URL for the HTTP request.

Request Body

.withBody(<Any>)
.withBody(<Object>)
.with(body: <Data>)

Required. The body of the HTTP request.

If encodeBodyAsJson is not set (or is set to false) the request body must be either a string or a binary.

If the request payload has a content type of multipart/form-data, use the form parameter instead of body.

Form Request Body

.withForm(<document>)
.withForm(<document>)
.with(form: <document>)

A document where each field maps to a field in a multipart/form-data request. This parameter cannot be used at the same time as the body parameter.

Note

Requests that use the form parameter should also include a Content-Type: multipart/form-data header.

Example

"form": {
  "to-address": "name@example.com",
  "from-address": "other-name@example.com",
  "subject": "test subject please ignore",
  "message-body": "hello from the message body"
}

Request Headers

.withHeaders(<document>)
.withHeaders(<document>)
.with(headers: <document>)

Optional. A document where each field name corresponds to a type of HTTP header and each field value is an array of one or more string values for that header.

Example

{
  "Content-Type": [ "application/json" ]
}

Request Cookies

.withCookies(<document>)
.withCookies(<document>)
.with(cookies: <document>)

Optional. A document where each field name corresponds to a cookie name and each field value is that cookie’s string value.

Example

{
  "favoriteTeam": "Chicago Cubs"
}

Request Authentication URL

.withAuthUrl(<string>)
.withAuthUrl(<string>)
.with(authURL: <string>)
Optional. A URL that grants authorization cookies for the HTTP request.

Follow Redirects

.withFollowRedirects(<boolean>)
.withFollowRedirects(<boolean>)
.with(followRedirects: <boolean>)
Optional. If true, the request will follow any HTTP redirects it receives for the target URL.

Alternative URL Parameters

If you need to specify the individual components of the request’s target URL, omit the url field and specify the components as root-level fields. The following URL component fields are available:

<scheme>://<host>/<path>?<query>#<fragment>
{
   "scheme": <string>,
   "host": <string>,
   "path": <string>,
   "query": <document>,
   "fragment": <string>,
   "username": <string>,
   "password": <string>
}
Name Contents
scheme
Optional. Default: "http".
Valid options: https, http

The URL scheme.

Example

// https://www.example.com/
{ scheme: "https" }
host
Required.

The hostname of the target resource.

Example

// https://www.example.com/
{ host: "www.example.com" }
path
Optional.

The path of the target resource.

Example

// https://www.example.com/api/v1/users
{ path: "/api/v1/users" }
query
Optional.

A document where each field maps to a parameter in the URL query string. The value of each field is an array of strings that contains all arguments for the parameter.

Example

// https://www.example.com/?id=8675309&color=red&color=blue
{
  query: {
    "id": ["8675309"],
    "color": ["red", "blue"]
  }
}
fragment
Optional.

The URL fragment. This portion of the URL includes everything after the hash (#) symbol.

Example

// https://www.example.com/?id=8675309#someFragment
{ fragment: "someFragment" }
username
Optional.

A basic authentication username used in conjunction with the password argument.

password
Optional.

A basic authentication password used in conjunction with the username argument.

Return Value

The http.post() action returns a promise that resolves to a document with the following form:

{
   "status": <string>,
   "statusCode": <integer>,
   "contentLength": <integer>,
   "headers": <document>,
   "cookies": <array>,
   "body": <binary>
}
Field Type Description
status string The HTTP Request status message.
statusCode integer The HTTP Request status code.
contentLength integer The number of bytes returned in the response body.
headers document

A document where each field name corresponds to a type of HTTP header and each field value is an array of one or more string values for that header.

Example

{
  "Content-Type": [ "application/json" ]
}
cookies document

A document where each field name corresponds to a cookie name and each field value is that cookie’s string value.

Example

{
  "favoriteTeam": "Chicago Cubs"
}
body binary The binary-encoded body of the HTTP response.

Rule Templates

Users Can Only Send Requests to a Specific Host

{
  "%%args.url.host": "example.com"
}

Requests URLs Must Include a Specific Query Parameter

{
  "%%args.url.query.someParameter": "importantValue"
}

Request Bodies Must Include a Specific Field

{
  "body.name": { "%exists": 1 }
}

Request Bodies Must Include Fields With Specific Values

{
  "body.city": "New York City"
}
←   http.get() http.put()  →