Navigation

http.post()

Definition

http.post()

Sends an HTTP POST request to the specified URL.

Usage Examples

Call from a Function

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

Call from a Client SDK

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

const app = Stitch.defaultAppClient;
const http = app.getServiceClient(HttpServiceClient.factory, "http");

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();

http.execute(request)
  .then(console.log)
  .catch(console.error)
StitchAppClient client = Stitch.getDefaultAppClient();
StitchServiceClient http = client.getServiceClient(HttpServiceClient.factory, "http");

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();

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()); }
    }
  });
let app = Stitch.defaultAppClient!
let http = app.serviceClient(
  fromFactory: httpServiceClientFactory,
  withName: "http"
)

let request = HTTPRequest(
  url: "https://www.example.com/diff.txt",
  method: HTTPMethod.post,
  body: ["msg", "This is in the body of a POST 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)")
  }
}

Include Form Data in a Request

If you need to include content of type multipart/form-data with your HTTP request, use the form argument instead of a body argument.

  • The form argument takes a document where each field maps to a form field.
  • Form requests should include a content-type header set to multipart/form-data.

The following is an example of a form argument with multiple fields:

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

Parameters

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

{
    "url": <mixed>,
    "authUrl": <mixed>,
    "headers": <document>,
    "cookies": <string>,
    "followRedirects": <boolean>
}
Argument Type Description
url string or document The URL string for the HTTP request. Alternatively, you can specify the components of the URL. See Alternative URL Arguments.
authUrl string or document Optional. The auth URL (i.e. URL that grants a cookie) for the HTTP request.
body string Corresponds to the body of the HTTP request. For form content, see Include Form Data in a Request.
headers document Optional. Corresponds to the HTTP header fields and the corresponding values are an array of values (e.g. "Content-Type": [ "application/json" ]) for the request.
cookies string Optional. Cookie name and value pairs.
followRedirects boolean Optional. Determines whether or not to follow redirects.

Alternative URL Arguments

As an alternative to passing the url or authUrl argument as a single string, you can instead specify the individual components of the URL in a document.

Given the URL of the form:

<scheme>://<host>/<path>?<query>#<fragment>

The url argument is a document with the fields:

{
   "scheme": <string>,
   "host": <string>,
   "path": <string>,
   "query": <string>,
   "fragment": <string>,
   "username": <string>,
   "password": <string>
}
Name Contents
scheme Required. Defaults to https. Permissible values are https and http.
host Required. The hostname for the request. In the URL https://mongodb.example.net/api/v1.0/entity, the hostname is mongodb.example.net.
path The path portion of the URL. In https://mongodb.example.net/api/v1.0/entity, the path portion is /api/v1.0/entity.
query

Document containing keys and values which map to the URL’s query string. Each key must be a string and each value must be an array of strings, even if the array contains only one element. For example, given the query document:

{ "x": ["hello"], "y": ["world"] }

The query is appended to the outgoing request as ?x=hello&y=world.

If an array contains more than one element, all the elements are included with the same key. For example, given the query document:

{ "cars": ["Porsche", "Audi"], "bikes": ["Trek", "Marin"] }

The query is appended to the outgoing request as ?cars=Porsche&cars=Audi&bikes=Trek&bikes=Marin.

fragment The portion of the URL which comes after the anchor (#).
username A username used in conjunction with the password argument. Allows the action to access the given URL with basic authentication.
password A password used in conjunction with the username argument. Allows the action to access the given URL with basic authentication.

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 A string representing the HTTP status.
statusCode integer The HTTP status code.
contentLength integer The length of the content returned in body.
headers document Corresponds to the HTTP header fields and the corresponding values are an array of values (e.g. "Content-Type": [ "application/json" ]) for the request.
cookies document Optional. Cookie name and value pairs.
body binary Optional. The raw 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.delete()  →