NAV
JSON Shell Browser Node.js Python Ruby PHP Go C# Java

Moesif API Reference

Moesif is an API analytics and monetization service to grow your API products. With Moesif, you can quickly get started with API observability, API monetization and usage-based billing.

With Moesif, you cam This reference is for v1 of the Moesif APIs. For an overview on the Moesif platform, see the developer docs or implementation guides

There are two APIs:

Name Host Authentication
Collector API api.moesif.net Retrieve your Collector Application Id by logging into Moesif and going to API keys from bottom left menu. Place in the request X-Moesif-Application-Id header. More info
Management API api.moesif.com Generate a Management API key by logging into Moesif and going to API keys from bottom left menu. Add it as a Bearer token to the request Authorization header. More info

API definitions

The Collector API enables you to log raw data to Moesif at high volume such as events and user profiles. It's a write-only, high-volume data collection network and is also used by the Moesif server integrations and plugins.

The Management API enables you to query and manage data in your Moesif account such as to embed charts in customer-facing applications.

Overview

Data Model

The Moesif data model includes two types of events (API Calls and Custom Actions) and three type of entities (Users, Companies, and Subscriptions). A full diagram is below.

Moesif Data Model

For more info, view docs on Moesif data structure.

Filtering

Query Params

Some endpoints require a date range for data to look at. This is done via the from and the to query parameters. There is also an optional time_zone query parameter if you want the calendar dates aligned to your local time zone. Time zone is UTC by default and must be a TZ Database Name such as America/Los_Angeles

Relative dates support the following units:

symbol unit
s seconds
m minutes
h hours
d days
w weeks
M months
now current UTC time

Dates can optionally be prepended with a - or a +

Some examples:

From Date To Date Description
-24h now from 24 hours ago to now
-1d now from 1 day ago to now
-1w now from 1 week ago to now
-2w -1w frm 2 weeks ago to 1 week ago
-1M 1M from 1 month ago to 1 month in the future

Elasticsearch DSL

The Moesif Search APIs supports majority of the Elasticsearch/Opensearch Search DSL, which makes it super flexible to generate the report you're looking for. Only the DSL for search is supported. Other APIs outside of search are not supported. You can generate a query quickly within the Moesif UI by clicking the orange "Embed" button on any report. Then select "Search API". The generated CURL command will be for the exact report you are looking at. If you change filters or other criteria, you can go back and click "Embed" again to see how it changes. For help building a query for your business requirements, contact us.

Example: Getting most recent 500 errors

If you wanted to get the most recent API errors, you can filter by API calls with response status 500 and sort by request time in descending order.

POST https://api.moesif.com/search/~/search/events?from=-1d&to=now

Example Request
{
  "post_filter": {
    "bool": {
      "should": {
        "term": {
          "response.status": "500"
        }
      }
    }
  },
  "size": 50,
  "sort": [
    {
      "request.time": "desc"
    }
  ]
}
curl -XPOST \
    -d '{"post_filter":{"bool":{"should":{"term":{"response.status":"500"}}}},"size":50,"sort":[{"request.time":"desc"}]}' \
    -H 'Accept: application/json' \
    -H 'Authorization: Bearer {access-token}' \
    "https://api.moesif.com/search/~/search/events?from=-1d&to=now"

Example: Getting API usage per customer

Another popular use case is to get the monthly API usage for a specific customer so you can display current usage vs. plan quota in your customer facing portal. This can be done easily by looking at past month and getting a count for the user_id

POST https://api.moesif.com/search/~/search/count?from=-1M&to=now

Example Request
{
  "post_filter": {
    "bool": {
      "should": {
        "term": {
          "user_id.raw": "123456"
        }
      }
    }
  }
}
curl -XPOST \
    -d '{"post_filter":{"bool":{"should":{"term":{"user_id.raw":"123456"}}}}}' \
    -H 'Accept: application/json' \
    -H 'Authorization: Bearer {access-token}' \
    "https://api.moesif.com/search/~/count/events?from=-1M&to=now"

Pagination

Sorting List of Items

To rapidly generate your query, it's strongly recommended using the query builder within the Moesif UI. This can be found by clicking orange "Embed" button and selecting "Search API". Set up your sort field and click the next page to see an example for pagination.

Moesif's search APIs (such as to get list of events of users) use a combination of keyset and seek pagination to ensure APIs are performant for very large offset values. For an overview of different types, see this blog post on pagination.

For pagination, the search API allows for three request body fields:

For the request, we need to define the last item seen in the ordered list. This can be obtained by looking at the previous response's hits.hits.sort field.

Sorting items by request time For example, let's say we want to return the most recent events in descending order in batches of 100 items. For each page after the first, we should set the last event already seen as the request.time.

POST https://api.moesif.com/search/~/search/events?from=-7d&to=now

Sorting items by request time
{
    "size": 10,
    "search_after": [
        1694190464456
    ],
    "sort": [
        {
            "request.time": {
                "order": "desc",
                "unmapped_type": "string"
            }
        }
    ]
}

Sorting items by low cardinality key

For lower cardinality keys (likes response.status), many events may match the same status code. In order to have a stable sort, you must use a high cardinality key as well such that it's a sort on a compound key. Below is an example using both the response.status as well as the _id field (which is guaranteed to be unique)

POST https://api.moesif.com/search/~/search/events?from=-7d&to=now

Sorting items by low cardinality key
{
    "size": 50,
    "search_after": [
        "12345",
        "AYpjf3Gow2BIxAOLPgx4"
    ],
    "sort": [
        {
            "user_id.raw": {
                "order": "desc",
                "unmapped_type": "string"
            }
        },
        {
            "_id": "desc"
        }
    ]
}

Sorting Metric Terms

To rapidly generate your query, t's strongly recommended using the query builder within the Moesif UI. This can be found by clicking orange "Embed" button and selecting "Search API".

Metrics APIs (such as to get a time series or segmentation report) do not support pagination as the response is already aggregated and contains the required dataset. However, Moesif does support sorting by "top X" and "Bottom X" for when a "group by" is present. This is important to define whether you want the top terms or bottom terms and what is the metric to order the group by terms.

Sorting group by terms

In the below example, we have a segmentation report that gets the total event count for the top 10 companies. The query has a "group by" on company_id.raw. The group by will return the top 10 terms sorted by the company's event count (weight) in descending order (desc).

POST https://api.moesif.com/search/~/search/events?from=-7d&to=now

Sorting group by term
{
    "aggs": {
        "seg": {
            "filter": {
                "match_all": {}
            },
            "aggs": {
                "company_id.raw": {
                    "terms": {
                        "field": "company_id.raw",
                        "size": "20",
                        "min_doc_count": 1,
                        "order": {
                            "weight|sum": "desc"
                        },
                        "missing": "(none)"
                    },
                    "aggs": {
                        "weight|sum": {
                            "sum": {
                                "field": "weight",
                                "missing": 1
                            }
                        }
                    }
                },
                "weight|sum": {
                    "sum": {
                        "field": "weight",
                        "missing": 1
                    }
                }
            }
        }
    },
    "size": 0
}

Sorting by a different metric

The metric returned and the sort order can be different. In the below example, the metric returned is 90th percentile latency, but we still want to sort by the top 10 APIs by volume so we ignore the small volume APIs.

POST https://api.moesif.com/search/~/search/events?from=-7d&to=now

Sorting by a different metric
{
    "aggs": {
        "seg": {
            "filter": {
                "match_all": {}
            },
            "aggs": {
                "request.route.raw": {
                    "terms": {
                        "field": "request.route.raw",
                        "size": "10",
                        "min_doc_count": 1,
                        "order": {
                            "duration_ms|percentiles(90).90": "desc"
                        },
                        "missing": "(none)"
                    },
                    "aggs": {
                        "duration_ms|percentiles(90)": {
                            "percentiles": {
                                "field": "duration_ms",
                                "percents": [
                                    90
                                ]
                            }
                        }
                    }
                },
                "duration_ms|percentiles(90)": {
                    "percentiles": {
                        "field": "duration_ms",
                        "percents": [
                            90
                        ]
                    }
                }
            }
        }
    },
    "size": 0
}

Idempotency

Moesif Collector API support idempotent requests. This ensures Moesif does not create duplicate events even if the same event was sent twice to the Moesif Collector API. For users and companies APIs, this is automatic. For events and actions APIs, ensure you set the transaction_id for each event to a random UUID. This should be a 36 character UUID such as 123e4567-e89b-12d3-a456-426614174000. Moesif uses the transaction_id for ensuring duplicate events are not created. Setting the transaction_id is strongly recommended if you can replay processing from a pipeline like logstash.

Deduplication for Batches

Because each event has it's own transaction_id, Moesif will still deduplicate even if the batches are different. For example, let's say you send the following batches:

  1. Send a batch of two events containing transaction_id's A, B
  2. Send a batch of one event containing transaction_id C
  3. Send a batch of three events containing transaction_id's A, C, D

At the end, Moesif will only contain 4 events (A, B, C, D)

Request Format

For POST, PUT, and PATCH requests, the request body should be JSON. The Content-Type header should be set to application/json

Response Format

The response body format is always JSON. Successful operations are seen via 2xx status code. Successful creation of new objects will be seen via 201. 4xx status implies client error.

The REST API JSON payload uses underscore format (i.e some_key). Many of the API libs may use camelCase, PascalCase, or other as their model entities. Please select the respective language tab.

CORS

CORS is enabled on this API. Access-Control-Allow-Origin is set to *

Errors

Error Code Meaning
400 Bad Request -- Your request has an incorrect parameter
401 Unauthorized -- Your X-Moesif-Application-Id or Authorization header is incorrect or missing required scopes
402 Payment Required -- Your subscription is not active or has been cancelled
404 Not Found -- The specified endpoint could not be found
405 Method Not Allowed -- You tried to access a resource with an invalid HTTP method
406 Not Acceptable -- You requested a format that is not JSON format, Moesif's API supports JSON
410 Gone -- The resource requested has been removed from our servers
429 Too Many Requests -- You are hitting a rate limit such as too many queries at same time.
500 Internal Server Error -- We had a problem with our server. Please contact us
502 Bad Gateway -- A transient error when no server is available to handle your request, retry again or contact us if problem persists.
503 Service Unavailable -- A transient error when no server is available to handle your request, retry again or contact us if problem persists.

Limits and Restrictions

Moesif has certain limits to ensure performance and stability for all Moesif customers. The Management APIs are rate limited to protect service degradation. Moesif also has limits on event size to ensure performance of your account.

Moesif does not rate limit data ingestion via the collector APIs. However, you can still be throttled due to security reasons to product Moesif infrastructure. This may happen when unusual behavior is detected such as exceeding your quota by a wide margin

Maximum Event Size

Collected events have size limits to ensure performance and stability of the Moesif platform for customers.

Limit Value
Maximum size of single event 1MB
Maximum size of a batch of events 50MB
Truncation size of request.body or response.body 450KB

The maximum size of an event (one API call or user action) is 1MB, which is a hard limit due to how the Moesif platform was architected for scale. Majority of APIs we see have an average event size of 1Kb to 5Kb so it would be unusual to reach this limit. With that said, there are a couple of things you can try:

  1. Don't log non API traffic using skip functionality (i.e. HTML, pictures, etc). Moesif is not designed for monitoring access to large files nor provides much usefulness.
  2. Remove large keys from payload using mask data. This can be helpful if you have a JSON key that's large but not valuable.

If you're sending a batch of events to the batch API, the maximum batch size is 50MB regardless if compression is used. For batches of events greater than 50MB, you should break up the batch into smaller batches.

Moesif will still try to log events over 1MB by truncating the request or response body to 450Kb and base64 encoded it. The logged body won't be valid JSON but at least the event is logged for later inspection. A warning is also displayed in the Moesif app so you can identify when this is occurring. The partial body will not be analyzed by Moesif's body analytics feature so filters may not match on body fields, etc.

Management API Rate Limits

To ensure performance of search queries, the Management API has a rate limit of 500 queries/minute, but can burst higher based on your history and pattern. The Management API will return 429 Too Many Requests once you hit this limit. This operates on a fixed calendar minute period. Moesif reserves the right to modify these limits to protect the reliability of the Moesif Platform.

The search APIs are intended for interactive workflows such as logging into Moesif UI or to integrate Moesif into your applications. If you need to transfer large amounts of data to cloud object storage (like Azure Storage) or to your data warehouse, you should use the bulk export APIs and not the search API.

Moesif does not rate limit data ingestion via the collector APIs. However, you can still be throttled due to security reasons to product Moesif infrastructure. This may happen when unusual behavior is detected such as exceeding your quota by a wide margin

Late Events

Moesif server integrations stream events to the collector API in real-time. If you build a custom integration, you should also send events in real-time.

However, we understand you may have special circumstances that cause events to be sent later than expected. By default, Moesif can process events that are up to 30 days in the past. By default, events older than 30 days are rejected by the collector API. If you need an exception to backfill more historical data, please contact us so we can enable your account for backfill.

While Moesif will process the events, events that are more than 5 minutes old are considered "late events". Certain workflows with strict deadlines like alerting and billing may be impacted. If you're using a native Moesif server integrations, this shouldn't be an issue as they stream events to Moesif in real-time within milliseconds. If you have an ingestion delay in the minutes it likely implies something wrong with your server integration. Server clock can be another issue if incorrectly set. We do track ingestion delays internally, so we'll reach out if we see such issues happening on your account.

API Libs

THese are low-level libraries to access the Moesif Collector API directly. For logging API calls at scale, most customers should integrate with one of Moesif's API monitoring agents which instrument your API automatically and handle batching. Likewise, Moesif has client integrations for tracking users and their actions in your UI.

How to Install

Pick a language at the bottom left


Source Code:

https://github.com/moesif/moesifapi-java
// Add the dependency

<dependency>
    <groupId>com.moesif.api</groupId>
    <artifactId>moesifapi</artifactId>
    <version>1.6.9</version>
</dependency>
Source Code:

https://github.com/moesif/moesifapi-nodejs


Package:

https://www.npmjs.com/package/moesifapi
// To Install Moesif Lib, run in your terminal

npm install --save moesifapi
Source Code:

https://github.com/moesif/moesifapi-python


Package:

https://pypi.python.org/pypi/moesifapi
# To Install Moesif Lib, run in your terminal

pip install moesifapi
Source Code:

https://github.com/moesif/moesifapi-ruby


Package:

https://rubygems.org/gems/moesif_api
# To Install Moesif Lib, run in your terminal

gem install moesif_api
Source Code:

https://github.com/moesif/moesifapi-csharp


Package:

https://www.nuget.org/packages/Moesif.Api/
// Install the Nuget Package via Package Manager Console:

Install-Package Moesif.Api
Source Code:

https://github.com/Moesif/moesifapi-go

go get github.com/moesif/moesifapi-go;
Source Code:

https://github.com/Moesif/moesifapi-php
// Install via Composer

composer require moesif/moesifapi-php
Install via NPM:
var moesif = require('moesif-browser-js');

moesif.init({
  applicationId: 'YOUR_COLLECTOR_APPLICATION_ID'
  // add other option here.
});
Install via CDN
<script src="//unpkg.com/moesif-browser-js@^1/moesif.min.js"></script>
<script type="text/javascript">
moesif.init({
  applicationId: 'YOUR_COLLECTOR_APPLICATION_ID'
});
</script>

Select your language on the right:

The SDKs are open-source and available on GitHub.

Collector API v1

The Collector API enables you to log data to Moesif at high volumes. This is also what the Moesif server integrations use. For more info, check out an overview of our analytics infrastructure.

Base URL (Public) Base URL (When using Secure Proxy)
api.moesif.net/v1 localhost:9500/collector/v1

If you're using the Moesif secure proxy for client-side encryption, the base URL is http://localhost:9500/collector/v1 assuming it's running on port 9500. See accessing Collector API

Terms of service

Moesif's official SDKs and plugins only use HTTPS, but the API does support HTTP for very specific applications like legacy embedded devices (uncommon). It's strongly recommended to ensure all communication is HTTPS.

Authentication

Authentication is handled by adding the HTTP header X-Moesif-Application-Id to all requests. Moesif recommends using the same Application Id for all integrations within the same application environment (i.e. product, staging, etc) so your analytics data is unified.

X-Moesif-Application-Id: YOUR_COLLECTOR_APPLICATION_ID

API Calls

Log an API Call

POST https://api.moesif.net/v1/events

Log a single API call to Moesif as an event. The request payload is a single API event containing the API request, the API response, and any custom event metadata.

POST https://api.moesif.net/v1/events

Example Request
  {
    "request": {
      "time": "2024-02-06T04:45:42.914",
      "uri": "https://api.acmeinc.com/items/12345/reviews/",
      "verb": "POST",
      "api_version": "1.1.0",
      "ip_address": "61.48.220.123",
      "headers": {
        "Host": "api.acmeinc.com",
        "Accept": "*/*",
        "Connection": "Keep-Alive",
        "Content-Type": "application/json",
        "Content-Length": "126",
        "Accept-Encoding": "gzip"
      },
      "body": {
        "items": [
          {
            "direction_type": 1,
            "item_id": "hello",
            "liked": false
          },
          {
            "direction_type": 2,
            "item_id": "world",
            "liked": true
          }
        ]
      },
      "transfer_encoding": ""
    },
    "response": {
      "time": "2024-02-06T04:45:42.914",
      "status": 500,
      "headers": {
        "Vary": "Accept-Encoding",
        "Pragma": "no-cache",
        "Expires": "-1",
        "Content-Type": "application/json; charset=utf-8",
        "Cache-Control": "no-cache"
      },
      "body": {
        "Error": "InvalidArgumentException",
        "Message": "Missing field location"
      },
      "transfer_encoding": ""
    },
    "user_id": "12345",
    "company_id": "67890",
    "transaction_id": "a3765025-46ec-45dd-bc83-b136c8d1d257",
    "metadata": {
        "some_string": "I am a string",
        "some_int": 77,
        "some_object": {
            "some_sub_field": "some_value"
        }
    }
  }
# You can also use wget
curl -X POST https://api.moesif.net/v1/events \
  -H 'Content-Type: application/json' \
  -H 'X-Moesif-Application-Id: YOUR_COLLECTOR_APPLICATION_ID'
  -d '{"request":{"time":"2024-02-06T04:45:42.914","uri":"https://api.acmeinc.com/items/12345/reviews/","verb":"POST","api_version":"1.1.0","ip_address":"61.48.220.123","headers":{"Host":"api.acmeinc.com","Accept":"*/*","Connection":"Keep-Alive","Content-Type":"application/json","Content-Length":"126","Accept-Encoding":"gzip"},"body":{"items":[{"direction_type":1,"item_id":"hello","liked":false},{"direction_type":2,"item_id":"world","liked":true}]},"transfer_encoding":""},"response":{"time":"2024-02-06T04:45:42.914","status":500,"headers":{"Vary":"Accept-Encoding","Pragma":"no-cache","Expires":"-1","Content-Type":"application/json; charset=utf-8","Cache-Control":"no-cache"},"body":{"Error":"InvalidArgumentException","Message":"Missing field location"},"transfer_encoding":""},"user_id":"12345","company_id":"67890","transaction_id":"a3765025-46ec-45dd-bc83-b136c8d1d257","metadata":{"some_string":"I am a string","some_int":77,"some_object":{"some_sub_field":"some_value"}}}'
// Import the Library
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
APIController api = getClient().getAPI();

// Generate the event
Map<String, String> reqHeaders = new HashMap<String, String>();
reqHeaders.put("Host", "api.acmeinc.com");
reqHeaders.put("Accept", "*/*");
reqHeaders.put("Connection", "Keep-Alive");
reqHeaders.put("User-Agent", "Apache-HttpClient");
reqHeaders.put("Content-Type", "application/json");
reqHeaders.put("Content-Length", "126");
reqHeaders.put("Accept-Encoding", "gzip");

Object reqBody = APIHelper.deserialize("{" +
  "\"items\": [" +
    "{" +
      "\"type\": 1," +
      "\"id\": \"hello\"" +,
    "}," +
    "{" +
      "\"type\": 2," +
       "\"id\": \"world\"" +
     "}" +
  "]" +
  "}");

Map<String, String> rspHeaders = new HashMap<String, String>();
rspHeaders.put("Vary", "Accept-Encoding");
rspHeaders.put("Pragma", "no-cache");
rspHeaders.put("Expires", "-1");
rspHeaders.put("Content-Type", "application/json; charset=utf-8");
rspHeaders.put("Cache-Control","no-cache");

Object rspBody = APIHelper.deserialize("{" +
    "\"Error\": \"InvalidArgumentException\"," +
    "\"Message\": \"Missing field field_a\"" +
  "}");


EventRequestModel eventReq = new EventRequestBuilder()
        .time(new Date())
        .uri("https://api.acmeinc.com/items/reviews/")
        .verb("PATCH")
        .apiVersion("1.1.0")
        .ipAddress("61.48.220.123")
        .headers(reqHeaders)
        .body(reqBody)
        .build();


EventResponseModel eventRsp = new EventResponseBuilder()
        .time(new Date(System.currentTimeMillis() + 1000))
        .status(500)
        .headers(rspHeaders)
        .body(rspBody)
        .build();

EventModel eventModel = new EventBuilder()
        .request(eventReq)
        .response(eventRsp)
        .userId("12345")
        .companyId("67890")
        .build();

// Asynchronous Call to Create Event
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
APIController api = getClient().getAPI();

APICallBack<Object> callBack = new APICallBack<Object>() {
    public void onSuccess(HttpContext context, Object response) {
        // Do something
    }

    public void onFailure(HttpContext context, Throwable error) {
        // Do something else
    }
};

api.createEventsBatchAsync(eventsList, callBack);

// Synchronous Call to Create Event
api.createEventsBatch(eventsList, callBack);
// 1. Import the module
var moesifapi = require('moesifapi');
var EventModel = moesifapi.UserModel;
var api = moesifapi.ApiController;

// 2. Configure the ApplicationId
var config = moesifapi.configuration;
config.ApplicationId = "YOUR_COLLECTOR_APPLICATION_ID";

// 3. Generate an API Event Model
var reqHeaders = JSON.parse('{' +
        '"Host": "api.acmeinc.com",' +
        '"Accept": "*/*",' +
        '"Connection": "Keep-Alive",' +
        '"User-Agent": "Apache-HttpClient",' +
        '"Content-Type": "application/json",' +
        '"Content-Length": "126",' +
        '"Accept-Encoding": "gzip"' +
    '}');

var reqBody = JSON.parse( '{' +
        '"items": [' +
            '{' +
                '"type": 1,' +
                '"id": "hello"' +
            '},' +
            '{' +
                '"type": 2,' +
                '"id": "world"' +
            '}' +
        ']' +
    '}');

var rspHeaders = JSON.parse('{' +
        '"Vary": "Accept-Encoding",' +
        '"Pragma": "no-cache",' +
        '"Expires": "-1",' +
        '"Content-Type": "application/json; charset=utf-8",' +
        '"Cache-Control": "no-cache"' +
    '}');

var rspBody = JSON.parse('{' +
        '"Error": "InvalidArgumentException",' +
        '"Message": "Missing field field_a"' +
    '}');

var reqDate = new Date();
var eventReq = {
    time: reqDate,
    uri: "https://api.acmeinc.com/items/reviews/",
    verb: "PATCH",
    apiVersion: "1.1.0",
    ipAddress: "61.48.220.123",
    headers: reqHeaders,
    body: reqBody
};

var eventRsp = {
    time: (new Date()).setMilliseconds(reqDate.getMilliseconds() + 500),
    status: 500,
    headers: rspHeaders,
    body: rspBody
};

var eventModel = {
    request: eventReq,
    response: eventRsp,
    userId: "12345",
    companyId: "67890"
};

var events = [new EventModel(eventModel),
  new EventModel(eventModel),
  new EventModel(eventModel),
  new EventModel(eventModel)];

// 4. Send batch of events
api.createEventsBatch(events, function(error, response, context) {
  // Do Something
});

from __future__ import print_function
from moesifapi.moesif_api_client import *
from moesifapi.models import *
from datetime import *

client = MoesifAPIClient(YOUR_COLLECTOR_APPLICATION_ID)
api = client.api

# Note: we recommend sending all API calls via MVC framework middleware.

req_headers = APIHelper.json_deserialize("""  {
  "Host": "api.acmeinc.com",
  "Accept": "*/*",
  "Connection": "Keep-Alive",
  "User-Agent": "Apache-HttpClient",
  "Content-Type": "application/json",
  "Content-Length": "126",
  "Accept-Encoding": "gzip"
} """)

req_body = APIHelper.json_deserialize( """{
  "items": [
    {
      "type": 1,
      "id": "hello"
    },
    {
      "type": 2,
      "id": "world"
    }
  ]
}""")

rsp_headers = APIHelper.json_deserialize("""  {
    "Date": "Mon, 05 Feb 2024 23:46:49 GMT",
    "Vary": "Accept-Encoding",
    "Pragma": "no-cache",
    "Expires": "-1",
    "Content-Type": "application/json; charset=utf-8"
    "Cache-Control": "no-cache"
  } """)

rsp_body = APIHelper.json_deserialize( """{
    "Error": "InvalidArgumentException",
    "Message": "Missing field field_a"
  }""")


event_req = EventRequestModel(time = datetime.utcnow() - timedelta(seconds=-1),
    uri = "https://api.acmeinc.com/items/reviews/",
    verb = "PATCH",
    api_version = "1.1.0",
    ip_address = "61.48.220.123",
    headers = req_headers,
    body = req_body)

event_rsp = EventResponseModel(time = datetime.utcnow(),
    status = 500,
    headers = rsp_headers,
    body = rsp_body)

event_model = EventModel(request = event_req,
    response = event_rsp,
    user_id = "12345",
    company_id = "67890",
     = "XXXXXXXXX")


# Perform the API call through the SDK function
api.create_event(event_model)
require 'moesif_api'

client = MoesifApi::MoesifAPIClient.new(YOUR_COLLECTOR_APPLICATION_ID)
api = client.api_controller

req_headers = JSON.parse('{'\
  '"Host": "api.acmeinc.com",'\
  '"Accept": "*/*",'\
  '"Connection": "Keep-Alive",'\
  '"User-Agent": "Apache-HttpClient",'\
  '"Content-Type": "application/json",'\
  '"Content-Length": "126",'\
  '"Accept-Encoding": "gzip"'\
'}')

req_body = JSON.parse( '{'\
  '"items": ['\
    '{'\
      '"type": 1,'\
      '"id": "hello"'\
    '},'\
    '{'\
      '"type": 2,'\
      '"id": "world"'\
    '}'\
  ']'\
'}')

rsp_headers = JSON.parse('{'\
  '"Date": "Mon, 05 Feb 2024 23:46:49 GMT",'\
                '"Vary": "Accept-Encoding",'\
  '"Pragma": "no-cache",'\
  '"Expires": "-1",'\
  '"Content-Type": "application/json; charset=utf-8",'\
                '"Cache-Control": "no-cache"'\
'}')

rsp_body = JSON.parse('{'\
  '"Error": "InvalidArgumentException",'\
  '"Message": "Missing field field_a"'\
'}')


event_req = EventRequestModel.new()
event_req.time = "2024-02-06T04:45:42.914"
event_req.uri = "https://api.acmeinc.com/items/reviews/"
event_req.verb = "PATCH"
event_req.api_version = "1.1.0"
event_req.ip_address = "61.48.220.123"
event_req.headers = req_headers
event_req.body = req_body

event_rsp = EventResponseModel.new()
event_rsp.time = "2024-02-06T04:45:42.914"
event_rsp.status = 500
event_rsp.headers = rsp_headers
event_rsp.body = rsp_body

event_model = EventModel.new()
event_model.request = event_req
event_model.response = event_rsp
event_model.user_id ="12345"
event_model.company_id ="67890"
event_model. = "XXXXXXXXX"

# Perform the API call through the SDK function
response = api.create_event(event_model)

using Moesif.Api;
using Moesif.Api.Helpers;

// Create client instance using your ApplicationId
var client = new MoesifApiClient("YOUR_COLLECTOR_APPLICATION_ID");
var apiClient = GetClient().Api;

// Parameters for the API call
var reqHeaders = APIHelper.JsonDeserialize<object>(@" {
        ""Host"": ""api.acmeinc.com"",
        ""Accept"": ""*/*"",
        ""Connection"": ""Keep-Alive"",
        ""User-Agent"": ""Apache-HttpClient"",
        ""Content-Type"": ""application/json"",
        ""Content-Length"": ""126"",
        ""Accept-Encoding"": ""gzip""
    }");

var reqBody = APIHelper.JsonDeserialize<object>(@" {
        ""items"": [
            {
                ""type"": 1,
                ""id"": ""hello""
            },
            {
                ""type"": 2,
                ""id"": ""world""
            }
        ]
    }");

var rspHeaders = APIHelper.JsonDeserialize<object>(@" {
        ""Date"": ""Mon, 05 Feb 2024 23:46:49 GMT"",
        ""Vary"": ""Accept-Encoding"",
        ""Pragma"": ""no-cache"",
        ""Expires"": ""-1"",
        ""Content-Type"": ""application/json; charset=utf-8"",
        ""Cache-Control"": ""no-cache""
    } ");

var rspBody = APIHelper.JsonDeserialize<object>(@" {
        ""Error"": ""InvalidArgumentException"",
        ""Message"": ""Missing field field_a""
    }");


var eventReq = new EventRequestModel()
{
    Time = DateTime.Parse("2024-02-06T04:45:42.914"),
    Uri = "https://api.acmeinc.com/items/reviews/",
    Verb = "PATCH",
    ApiVersion = "1.1.0",
    IpAddress = "61.48.220.123",
    Headers = reqHeaders,
    Body = reqBody
};

var eventRsp = new EventResponseModel()
{
    Time = DateTime.Parse("2024-02-06T04:45:42.914"),
    Status = 500,
    Headers = rspHeaders,
    Body = rspBody
};

var eventModel = new EventModel()
{
    Request = eventReq,
    Response = eventRsp,
    UserId = "12345",
    CompanyId = "67890"
};

//////////////////////////////////////
// Example for making an async call //     
//////////////////////////////////////
try
{
    await controller.CreateEventAsync(eventModel);
}
catch(APIException)
{
    // Handle Error
};

///////////////////////////////////////////
// Example for making a synchronous call //
///////////////////////////////////////////
try
{
    controller.CreateEvent(eventModel);
}
catch(APIException)
{
    // Handle Error
};

import "github.com/moesif/moesifapi-go"
import "github.com/moesif/moesifapi-go/models"
import "time"

apiClient := moesifapi.NewAPI("YOUR_COLLECTOR_APPLICATION_ID")

reqTime := time.Now().UTC()
apiVersion := "1.0"
ipAddress := "61.48.220.123"

req := models.EventRequestModel{
  Time:       &reqTime,
  Uri:        "https://api.acmeinc.com/widgets",
  Verb:       "GET",
  ApiVersion: &apiVersion,
  IpAddress:  &ipAddress,
  Headers: map[string]interface{}{
    "ReqHeader1": "ReqHeaderValue1",
  },
  Body: nil,
}

rspTime := time.Now().UTC().Add(time.Duration(1) * time.Second)

rsp := models.EventResponseModel{
  Time:      &rspTime,
  Status:    500,
  IpAddress: nil,
  Headers: map[string]interface{}{
    "RspHeader1":     "RspHeaderValue1",
    "Content-Type":   "application/json",
    "Content-Length": "1000",
  },
  Body: map[string]interface{}{
    "Key1": "Value1",
    "Key2": 12,
    "Key3": map[string]interface{}{
      "Key3_1": "SomeValue",
    },
  },
}

userId := "12345"
companyId: := "67890"

event := models.EventModel{
  Request:      req,
  Response:     rsp,
  SessionToken: nil,
  Tags:         nil,
  UserId:       &userId,
  CompanyId:    &companyId,
}


// Queue the event (will queue the requests into batches and flush buffers periodically.)
err := apiClient.QueueEvent(&event)

// Create the event synchronously
err := apiClient.CreateEvent(&event)

<?php
// Depending on your project setup, you might need to include composer's
// autoloader in your PHP code to enable autoloading of classes.

require_once "vendor/autoload.php";

// Import the SDK client in your project:

use MoesifApi\MoesifApiClient;

// Instantiate the client. After this, you can now access the Moesif API
// and call the respective methods:

$client = new MoesifApiClient("YOUR_COLLECTOR_APPLICATION_ID");
$api = $client->getApi();

$event = new Models\EventModel();
$reqdate = new DateTime();
$rspdate = new DateTime();

$event->request = array(
       "time" => $reqdate->format(DateTime::ISO8601), 
       "uri" => "https://api.acmeinc.com/items/reviews/", 
       "verb" => "PATCH", 
       "api_version" => "1.1.0", 
       "ip_address" => "61.48.220.123", 
       "headers" => array(
         "Host" => "api.acmeinc.com", 
         "Accept" => "_/_", 
         "Connection" => "Keep-Alive", 
         "User-Agent" => "moesifapi-php/1.1.5",
         "Content-Type" => "application/json", 
         "Content-Length" => "126", 
         "Accept-Encoding" => "gzip"), 
        "body" => array(
          "review_id" => 132232, 
          "item_id" => "ewdcpoijc0", 
          "liked" => false)
        );

 $event->response = array(
           "time" => $rspdate->format(DateTime::ISO8601), 
           "status" => 500, 
           "headers" => array(
             "Date" => "Tue, 1 Mar 2022 23:46:49 GMT", 
             "Vary" => "Accept-Encoding", 
             "Pragma" => "no-cache", 
             "Expires" => "-1", 
             "Content-Type" => "application/json; charset=utf-8", 
             "X-Powered-By" => "ARR/3.0", 
             "Cache-Control" => "no-cache", 
             "Arr-Disable-Session-Affinity" => "true"), 
             "body" => array(
               "item_id" => "13221", 
               "title" => "Red Brown Chair",
               "description" => "Red brown chair for sale",
               "price" => 22.23
             )
        );
$event->metadata = array(
          "foo" => "bar" 
        );

$event->user_id = "12345";
$event->company_id = "67890";
$event-> = "XXXXXXXXX";

$api->createEvent($event);
Name Type Required Description
request object true The object that specifies the API request.

time

string(date-time) true Timestamp for the request in ISO 8601 format.

uri

string true Full uri such as https://api.acmeinc.com/?query=string including protocol, host, and query string.

verb

string true HTTP method used such as GET or POST.

api_version

string false API Version you want to tag this request with such as 1.0.0.

ip_address

string false IP address of the requester, If not set, we extract the remote IP address.

headers

object true Headers of the request as a Map<string, string>. Multiple headers with the same key name should be combined together such that the values are joined by a comma. HTTP Header Protocol on w3.org.

body

object false Payload of the request in either JSON or a base64 encoded string.

transfer_encoding

string false Specifies the transfer encoding of request.body field. If set to json then the response.body must be a JSON object. If set to base64, then request.body must be a base64 encoded string. Helpful for binary payloads. If not set, the body is assumed to be json.
response object false The object that specifies the API response. The response object can be undefined such as a request timeouts.

time

string(date-time) true Timestamp for the response in ISO 8601 format.

status

integer true HTTP status code as number such as 200 or 500.

ip_address

string false IP address of the responding server.

headers

object true Headers of the response as a Map<string, string>. Multiple headers with the same key name should be combined together such that the values are joined by a comma. HTTP Header Protocol on w3.org

body

object false Payload of the response in either JSON or a base64 encoded string.

transfer_encoding

string false Specifies the transfer encoding of response.body field. If set to json then the response.body must be a JSON object. If set to base64, then response.body must be a base64 encoded string. Helpful for binary payloads. If not set, the body is assumed to be json.
transaction_id string false A random 36 char UUID for this event. If set, Moesif will deduplicate events using this id and ensure idempotency.
session_token string false Set the API key/session token used for this API call. Moesif will auto-detect API sessions if not set.
user_id string false Associate this API call to a user. Typically, a real person.
company_id string false Associate this API call to a company (Required for metered billing).
subscription_id string false Associate this API call to a specific subscription of a company. Not needed unless same company can have multiple subscriptions to the same plan. When set, usage will be reported to only this subscription.
direction string false The direction of this API call which can be Incoming or Outgoing.
metadata object false An object containing any custom event metadata you want to store with this event.

Log API Calls in Batch

POST https://api.moesif.net/v1/events/batch

Creates and logs a batch of API calls to Moesif. The request payload is an array API calls entities, each consisting of the API request, the API response, and any custom event metadata.

This API takes a list form of the same model defined in create single event.

The maximum batch size is 50MB. Break up larger batches into smaller batches.

POST https://api.moesif.net/v1/events/batch

Example Request
  [
    {
        "request": {
          "time": "2024-02-06T04:45:42.914",
          "uri": "https://api.acmeinc.com/items/83738/reviews/",
          "verb": "POST",
          "api_version": "1.1.0",
          "ip_address": "61.48.220.123",
          "headers": {
            "Host": "api.acmeinc.com",
            "Accept": "*/*",
            "Connection": "Keep-Alive",
            "Content-Type": "application/json",
            "Content-Length": "126",
            "Accept-Encoding": "gzip"
          },
          "body": {
            "items": [
              {
                "direction_type": 1,
                "item_id": "hello",
                "liked": false
              },
              {
                "direction_type": 2,
                "item_id": "world",
                "liked": true
              }
            ]
          },
          "transfer_encoding": ""
        },
        "response": {
          "time": "2024-02-06T04:45:42.914",
          "status": 500,
          "headers": {
            "Vary": "Accept-Encoding",
            "Pragma": "no-cache",
            "Expires": "-1",
            "Content-Type": "application/json; charset=utf-8",
            "Cache-Control": "no-cache"
          },
          "body": {
            "Error": "InvalidArgumentException",
            "Message": "Missing field location"
          },
          "transfer_encoding": ""
        },
        "user_id": "12345",
        "company_id": "67890",
        "transaction_id": "a3765025-46ec-45dd-bc83-b136c8d1d257",
        "metadata": {
            "some_string": "I am a string",
            "some_int": 77,
            "some_object": {
                "some_sub_field": "some_value"
            }
        }
    }
  ]
# You can also use wget
curl -X POST https://api.moesif.net/v1/events/batch \
  -H 'Content-Type: application/json' \
  -H 'X-Moesif-Application-Id: YOUR_COLLECTOR_APPLICATION_ID'
  -d '[{"request":{"time":"2024-02-06T04:45:42.914","uri":"https://api.acmeinc.com/items/83738/reviews/","verb":"POST","api_version":"1.1.0","ip_address":"61.48.220.123","headers":{"Host":"api.acmeinc.com","Accept":"*/*","Connection":"Keep-Alive","Content-Type":"application/json","Content-Length":"126","Accept-Encoding":"gzip"},"body":{"items":[{"direction_type":1,"item_id":"hello","liked":false},{"direction_type":2,"item_id":"world","liked":true}]},"transfer_encoding":""},"response":{"time":"2024-02-06T04:45:42.914","status":500,"headers":{"Vary":"Accept-Encoding","Pragma":"no-cache","Expires":"-1","Content-Type":"application/json; charset=utf-8","Cache-Control":"no-cache"},"body":{"Error":"InvalidArgumentException","Message":"Missing field location"},"transfer_encoding":""},"user_id":"12345","company_id":"67890","transaction_id":"a3765025-46ec-45dd-bc83-b136c8d1d257","metadata":{"some_string":"I am a string","some_int":77,"some_object":{"some_sub_field":"some_value"}}}]'
// Import the Library
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
APIController api = getClient().getAPI();

// Generate the events
Map<String, String> reqHeaders = new HashMap<String, String>();
reqHeaders.put("Host", "api.acmeinc.com");
reqHeaders.put("Accept", "*/*");
reqHeaders.put("Connection", "Keep-Alive");
reqHeaders.put("User-Agent", "Apache-HttpClient");
reqHeaders.put("Content-Type", "application/json");
reqHeaders.put("Content-Length", "126");
reqHeaders.put("Accept-Encoding", "gzip");

Object reqBody = APIHelper.deserialize("{" +
  "\"items\": [" +
    "{" +
      "\"type\": 1," +
      "\"id\": \"hello\"" +
    "}," +
    "{" +
      "\"type\": 2," +
      "\"id\": \"world\"" +
    "}" +
  "]" +
  "}");

Map<String, String> rspHeaders = new HashMap<String, String>();
rspHeaders.put("Date", "Mon, 05 Feb 2024 23:46:49 GMT");
rspHeaders.put("Vary", "Accept-Encoding");
rspHeaders.put("Pragma", "no-cache");
rspHeaders.put("Expires", "-1");
rspHeaders.put("Content-Type", "application/json; charset=utf-8");
rspHeaders.put("Cache-Control","no-cache");

Object rspBody = APIHelper.deserialize("{" +
    "\"Error\": \"InvalidArgumentException\"," +
    "\"Message\": \"Missing field field_a\"" +
  "}");


EventRequestModel eventReq = new EventRequestBuilder()
        .time(new Date())
        .uri("https://api.acmeinc.com/items/reviews/")
        .verb("PATCH")
        .apiVersion("1.1.0")
        .ipAddress("61.48.220.123")
        .headers(reqHeaders)
        .body(reqBody)
        .build();


EventResponseModel eventRsp = new EventResponseBuilder()
        .time(new Date(System.currentTimeMillis() + 1000))
        .status(500)
        .headers(rspHeaders)
        .body(rspBody)
        .build();

EventModel eventModel = new EventBuilder()
        .request(eventReq)
        .response(eventRsp)
        .userId("12345")
        .companyId("67890")
        .build();

List<EventModel> events = new ArrayList<EventModel>();
events.add(eventModel);
events.add(eventModel);
events.add(eventModel);
events.add(eventModel);

// Asynchronous Call to create new event
MoesifAPIClient client = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");
APIController api = getClient().getAPI();

APICallBack<Object> callBack = new APICallBack<Object>() {
    public void onSuccess(HttpContext context, Object response) {
      // Do something
    }

    public void onFailure(HttpContext context, Throwable error) {
      // Do something else
    }
};

api.createEventsBatchAsync(events, callBack);

// Synchronous Call to create new event
api.createEventsBatch(events, callBack);
// Import the module:
var moesifapi = require('moesifapi');

// Set your application id
var config = moesifapi.configuration;
config.ApplicationId = 'YOUR_COLLECTOR_APPLICATION_ID';

// Create API Event Models and set fields
var reqHeaders = JSON.parse('{' +
        '"Host": "api.acmeinc.com",' +
        '"Accept": "*/*",' +
        '"Connection": "Keep-Alive",' +
        '"User-Agent": "Apache-HttpClient",' +
        '"Content-Type": "application/json",' +
        '"Content-Length": "126",' +
        '"Accept-Encoding": "gzip"' +
    '}');

var reqBody = JSON.parse( '{' +
        '"items": [' +
            '{' +
                '"type": 1,' +
                '"id": "hello"' +
            '},' +
            '{' +
                '"type": 2,' +
                '"id": "world"' +
            '}' +
        ']' +
    '}');

var rspHeaders = JSON.parse('{' +
        '"Vary": "Accept-Encoding",' +
        '"Pragma": "no-cache",' +
        '"Expires": "-1",' +
        '"Content-Type": "application/json; charset=utf-8",' +
        '"Cache-Control": "no-cache"' +
    '}');

var rspBody = JSON.parse('{' +
        '"Error": "InvalidArgumentException",' +
        '"Message": "Missing field field_a"' +
    '}');

var reqDate = new Date();
var eventReq = {
    time: reqDate,
    uri: "https://api.acmeinc.com/items/reviews/",
    verb: "PATCH",
    apiVersion: "1.1.0",
    ipAddress: "61.48.220.123",
    headers: reqHeaders,
    body: reqBody
};

var eventRsp = {
    time: (new Date()).setMilliseconds(reqDate.getMilliseconds() + 500),
    status: 500,
    headers: rspHeaders,
    body: rspBody
};

var eventA = {
    request: eventReq,
    response: eventRsp,
    userId: "12345",
    companyId: "67890"
};

var myEventModels = [ eventA ]

//Access various controllers by:
var controller = moesifapi.ApiController;

// Send the actual events
controller.createEventsBatch(myEventModels, function(error, response, context) {
  //  Handle Errors
});

from __future__ import print_function
from moesifapi.moesif_api_client import *
from moesifapi.models import *
from datetime import *

# Setup API Client
client = MoesifAPIClient(YOUR_COLLECTOR_APPLICATION_ID)
api = client.api_controller


# Create API Event Models and set fields
req_headers = APIHelper.json_deserialize("""  {
  "Host": "api.acmeinc.com",
  "Accept": "*/*",
  "Connection": "Keep-Alive",
  "User-Agent": "Apache-HttpClient",
  "Content-Type": "application/json",
  "Content-Length": "126",
  "Accept-Encoding": "gzip"
} """)

req_body = APIHelper.json_deserialize( """{
  "items": [
    {
      "type": 1,
      "id": "hello"
    },
    {
      "type": 2,
      "id": "world"
    }
  ]
}""")

rsp_headers = APIHelper.json_deserialize("""  {
    "Date": "Mon, 05 Feb 2024 23:46:49 GMT",
    "Vary": "Accept-Encoding",
    "Pragma": "no-cache",
    "Expires": "-1",
    "Content-Type": "application/json; charset=utf-8"
    "Cache-Control": "no-cache"
  } """)

rsp_body = APIHelper.json_deserialize( """{
    "Error": "InvalidArgumentException",
    "Message": "Missing field field_a"
  }""")


event_req = EventRequestModel(time = datetime.utcnow() - timedelta(seconds=-1),
    uri = "https://api.acmeinc.com/items/reviews/",
    verb = "PATCH",
    api_version = "1.1.0",
    ip_address = "61.48.220.123",
    headers = req_headers,
    body = req_body)

event_rsp = EventResponseModel(time = datetime.utcnow(),
    status = 500,
    headers = rsp_headers,
    body = rsp_body)

event_a = EventModel(request = event_req,
    response = event_rsp,
    user_id = "12345",
    company_id = "67890"

my_events = [ event_a ]

# Send the actual events
api.create_events_batch(my_events)

require 'moesif_api'

# Setup API Client
client = MoesifApi::MoesifAPIClient.new(YOUR_COLLECTOR_APPLICATION_ID)
api = client.api_controller

# Create API Event Models and set fields
event_a = EventModel.new()
event_a.user_id = "12345"
event_a.company_id = "67890"
my_event_models = [ event_a ]

# Send the actual events
api.create_events_batch(my_event_models)

using Moesif.Api;
using Moesif.Api.Helpers;

// Create client instance using your ApplicationId
var client = new MoesifApiClient("YOUR_COLLECTOR_APPLICATION_ID");
var apiClient = GetClient().Api;

// Parameters for the API call
var reqHeaders = APIHelper.JsonDeserialize<object>(@" {
        ""Host"": ""api.acmeinc.com"",
        ""Accept"": ""*/*"",
        ""Connection"": ""Keep-Alive"",
        ""User-Agent"": ""Apache-HttpClient"",
        ""Content-Type"": ""application/json"",
        ""Content-Length"": ""126"",
        ""Accept-Encoding"": ""gzip""
    }");

var reqBody = APIHelper.JsonDeserialize<object>(@" {
        ""items"": [
            {
                ""type"": 1,
                ""id"": ""hello""
            },
            {
                ""type"": 2,
                ""id"": ""world""
            }
        ]
    }");

var rspHeaders = APIHelper.JsonDeserialize<object>(@" {
        ""Date"": ""Mon, 05 Feb 2024 23:46:49 GMT"",
        ""Vary"": ""Accept-Encoding"",
        ""Pragma"": ""no-cache"",
        ""Expires"": ""-1"",
        ""Content-Type"": ""application/json; charset=utf-8"",
        ""Cache-Control"": ""no-cache""
    } ");

var rspBody = APIHelper.JsonDeserialize<object>(@" {
        ""Error"": ""InvalidArgumentException"",
        ""Message"": ""Missing field field_a""
    }");

var reqDate = new Date();
var eventReq = new EventRequestModel()
{
    Time = DateTime.Parse("2024-02-06T04:45:42.914"),
    Uri = "https://api.acmeinc.com/items/reviews/",
    Verb = "PATCH",
    ApiVersion = "1.1.0",
    IpAddress = "61.48.220.123",
    Headers = reqHeaders,
    Body = reqBody
};

var eventRsp = new EventResponseModel()
{
    Time = DateTime.Parse("2024-02-06T04:45:42.914"),
    Status = 500,
    Headers = rspHeaders,
    Body = rspBody
};

var eventModel = new EventModel()
{
    Request = eventReq,
    Response = eventRsp,
    UserId = "12345",
    CompanyId = "67890"
};

// Create a List
var events = new List<EventModel>();
events.Add(eventModel);
events.Add(eventModel);
events.Add(eventModel);

//////////////////////////////////////
// Example for making an async call //  
//////////////////////////////////////
try
{
    await controller.CreateEventsBatchAsync(events);
}
catch(APIException)
{
    // Handle Error
};

///////////////////////////////////////////
// Example for making a synchronous call //
///////////////////////////////////////////
try
{
    controller.CreateEventsBatch(events);
}
catch(APIException)
{
    // Handle Error
};

import "github.com/moesif/moesifapi-go"
import "github.com/moesif/moesifapi-go/models"
import "time"

apiClient := moesifapi.NewAPI("YOUR_COLLECTOR_APPLICATION_ID")

reqTime := time.Now().UTC()
apiVersion := "1.0"
ipAddress := "61.48.220.123"

req := models.EventRequestModel{
  Time:       &reqTime,
  Uri:        "https://api.acmeinc.com/widgets",
  Verb:       "GET",
  ApiVersion: &apiVersion,
  IpAddress:  &ipAddress,
  Headers: map[string]interface{}{
    "ReqHeader1": "ReqHeaderValue1",
  },
  Body: nil,
}

rspTime := time.Now().UTC().Add(time.Duration(1) * time.Second)

rsp := models.EventResponseModel{
  Time:      &rspTime,
  Status:    500,
  IpAddress: nil,
  Headers: map[string]interface{}{
    "RspHeader1": "RspHeaderValue1",
  },
  Body: map[string]interface{}{
    "Key1": "Value1",
    "Key2": 12,
    "Key3": map[string]interface{}{
      "Key3_1": "SomeValue",
    },
  },
}

userId := "12345"
companyId := "6789"

event := models.EventModel{
  Request:      req,
  Response:     rsp,
  SessionToken: nil,
  Tags:         nil,
  UserId:       &userId,
  CompanyId:    &companyId,
}

events := make([]*models.EventModel, 20)
for i := 0; i < 20; i++ {
  events[i] = &event
}

// Queue the events
err := apiClient.QueueEvents(events)

// Create the events batch synchronously
err := apiClient.CreateEventsBatch(event)

<?php
// Depending on your project setup, you might need to include composer's
// autoloader in your PHP code to enable autoloading of classes.

require_once "vendor/autoload.php";

// Import the SDK client in your project:

use MoesifApi\MoesifApiClient;

// Instantiate the client. After this, you can now access the Moesif API
// and call the respective methods:

$client = new MoesifApiClient("Your application Id");
$api = $client->getApi();
Name Type Required Description
request object true The object that specifies the API request.

time

string(date-time) true Timestamp for the request in ISO 8601 format.

uri

string true Full uri such as https://api.acmeinc.com/?query=string including protocol, host, and query string.

verb

string true HTTP method used such as GET or POST.

api_version

string false API Version you want to tag this request with such as 1.0.0.

ip_address

string false IP address of the requester, If not set, we extract the remote IP address.

headers

object true Headers of the request as a Map<string, string>. Multiple headers with the same key name should be combined together such that the values are joined by a comma. HTTP Header Protocol on w3.org.

body

object false Payload of the request in either JSON or a base64 encoded string.

transfer_encoding

string false Specifies the transfer encoding of request.body field. If set to json then the response.body must be a JSON object. If set to base64, then request.body must be a base64 encoded string. Helpful for binary payloads. If not set, the body is assumed to be json.
response object false The object that specifies the API response. The response object can be undefined such as a request timeouts.

time

string(date-time) true Timestamp for the response in ISO 8601 format.

status

integer true HTTP status code as number such as 200 or 500.

ip_address

string false IP address of the responding server.

headers

object true Headers of the response as a Map<string, string>. Multiple headers with the same key name should be combined together such that the values are joined by a comma. HTTP Header Protocol on w3.org

body

object false Payload of the response in either JSON or a base64 encoded string.

transfer_encoding

string false Specifies the transfer encoding of response.body field. If set to json then the response.body must be a JSON object. If set to base64, then response.body must be a base64 encoded string. Helpful for binary payloads. If not set, the body is assumed to be json.
transaction_id string false A random 36 char UUID for this event. If set, Moesif will deduplicate events using this id and ensure idempotency. Moesif will still deduplicate even across different size batches.
session_token string false Set the API key/session token used for this API call. Moesif will auto-detect API sessions if not set.
user_id string false Associate this API call to a user. Typically, a real person.
company_id string false Associate this API call to a company (Required for metered billing).
subscription_id string false Associate this API call to a specific subscription of a company. Not needed unless same company can have multiple subscriptions to the same plan. When set, usage will be reported to only this subscription.
direction string false The direction of this API call which can be Incoming or Outgoing.
metadata object false An object containing any custom event metadata you want to store with this event.

Actions

Track a User Action

POST https://api.moesif.net/v1/actions

Log a single user action to Moesif. An action represents something a customer performed on your website such as Sign In or Purchased Subscription. Each action consists of an Action Name and optional Metadata.

An example tracking actions using moesif-browser-js:

var moesif = require('moesif-browser-js');

moesif.init({
  applicationId: 'YOUR_COLLECTOR_APPLICATION_ID'
});

// The first argument (required) contains the action name string. 
// The second argument (optional) contains event metadata.
moesif.track('Clicked Sign Up', {
  button_label: 'Get Started',
  sign_up_method: 'Google SSO'
});

POST https://api.moesif.net/v1/actions

Example Request
{
  "action_name": "Clicked Sign Up",
  "user_id": "12345",
  "company_id": "67890",
  "transaction_id": "a3765025-46ec-45dd-bc83-b136c8d1d257",
  "request": {
    "uri": "https://acmeinc.com/pricing",
    "user_agent_string": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
  },
  "metadata": {
    "button_label": "Get Started",
    "sign_up_method": "Google SSO"
  }
}
# You can also use wget
curl -X POST https://api.moesif.net/v1/actions \
  -H 'Content-Type: application/json' \
  -H 'X-Moesif-Application-Id: YOUR_COLLECTOR_APPLICATION_ID' \
  -d '{"action_name":"Clicked Sign Up","user_id":"12345","company_id":"67890","transaction_id": "a3765025-46ec-45dd-bc83-b136c8d1d257","request":{"uri":"https://acmeinc.com/pricing","user_agent_string":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"},"metadata":{"button_label":"Get Started","sign_up_method":"Google SSO"}}'
var moesif = require('moesif-browser-js');

moesif.init({
  applicationId: 'YOUR_COLLECTOR_APPLICATION_ID'
});

// The first argument (required) contains the action name string. 
// The second argument (optional) contains event metadata.
moesif.track('Clicked Sign Up', {
  button_label: 'Get Started',
  sign_up_method: 'Google SSO'
});
Name Type Required Description
transaction_id string false A random 36 char UUID for this event. If set, Moesif will deduplicate events using this id and ensure idempotency.
action_name string true A recognizable name such as Clicked Sign Up or Purchased Subscription
session_token string false The customer's current session token as a string.
user_id string false Associate this API call to a user. Typically, a real person.
company_id string false Associate this API call to a company (Required for metered billing).
subscription_id string false Associate this API call to a specific subscription of a company. Not needed unless same company can have multiple subscriptions to the same plan. When set, usage will be reported to only this subscription.
metadata object false An object containing any custom event metadata you want to store with this event.
request object true The object containing the action's request context.

time

string(date-time) false Timestamp for the action in ISO 8601 format. Set by server automatically if not set.

uri

string true Full uri customer is on such as https://wwww.acmeinc.com/pricing?utm_source=adwords including protocol, host, and query string.

ip_address

string false IP address of the customer, If not set, we extract the remote IP address.

user_agent_string

string false The customer's browser agent string for device context.

Track User Actions in Batch

POST https://api.moesif.net/v1/actions/batch

Log a batch of user action to Moesif. An action represents something a customer performed on your website such as Sign In or Purchased Subscription. Each action consists of an Action Name and optional Metadata.

This API takes an array form of the same model defined for track single action. The maximum batch size is 12MB. Break up larger batches.

An example tracking actions using moesif-browser-js:

var moesif = require('moesif-browser-js');

moesif.init({
  applicationId: 'YOUR_COLLECTOR_APPLICATION_ID'
});

// The first argument (required) contains the action name string. 
// The second argument (optional) contains event metadata.
moesif.track('Clicked Sign Up', {
  button_label: 'Get Started',
  sign_up_method: 'Google SSO'
});

POST https://api.moesif.net/v1/actions/batch

Example Request
[
  {
    "action_name": "Clicked Sign Up",
    "user_id": "12345",
    "company_id": "67890",
    "transaction_id": "a3765025-46ec-45dd-bc83-b136c8d1d257",
    "request": {
      "uri": "https://acmeinc.com/pricing",
      "user_agent_string": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
    },
    "metadata": {
      "button_label": "Get Started",
      "sign_up_method": "Google SSO"
    }
  },
  {
    "action_name": "Purchased Subscription",
    "user_id": "12345",
    "company_id": "67890",
    "transaction_id": "a90cbabb-2dfc-4290-a368-48ce1a1af7ba",
    "request": {
      "uri": "https://acmeinc.com/pricing",
      "user_agent_string": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
    },
    "metadata": {
      "plan_name": "Pay As You Go",
      "plan_revenue": 5000
    }
  }
]
# You can also use wget
curl -X POST https://api.moesif.net/v1/actions/batch \
  -H 'Content-Type: application/json' \
  -H 'X-Moesif-Application-Id: YOUR_COLLECTOR_APPLICATION_ID' \
  -d '[{"action_name":"Clicked Sign Up","user_id":"12345","company_id":"67890","transaction_id": "a3765025-46ec-45dd-bc83-b136c8d1d257","request":{"uri":"https://acmeinc.com/pricing","user_agent_string":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"},"metadata":{"button_label":"Get Started","sign_up_method":"Google SSO"}},{"action_name":"Purchased Subscription","user_id":"12345","company_id":"67890","transaction_id": "a90cbabb-2dfc-4290-a368-48ce1a1af7ba","request":{"uri":"https://acmeinc.com/pricing","user_agent_string":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"},"metadata":{"plan_name":"Pay As You Go","plan_revenue":5000}}]'
var moesif = require('moesif-browser-js');

moesif.init({
  applicationId: 'YOUR_COLLECTOR_APPLICATION_ID'
});

// The first argument (required) contains the action name string. 
// The second argument (optional) contains event metadata.
moesif.track('Clicked Sign Up', {
  button_label: 'Get Started',
  sign_up_method: 'Google SSO'
});
Name Type Required Description
transaction_id string false A random 36 char UUID for this event. If set, Moesif will deduplicate events using this id and ensure idempotency. Moesif will still deduplicate even across different size batches.
action_name string true A recognizable name such as Clicked Sign Up or Purchased Subscription
session_token string false The customer's current session token as a string.
user_id string false Associate this API call to a user. Typically, a real person.
company_id string false Associate this API call to a company (Required for metered billing).
subscription_id string false Associate this API call to a specific subscription of a company. Not needed unless same company can have multiple subscriptions to the same plan. When set, usage will be reported to only this subscription.
metadata object false An object containing any custom event metadata you want to store with this event.
request object true The object containing the action's request context.

time

string(date-time) false Timestamp for the action in ISO 8601 format. Set by server automatically if not set.

uri

string true Full uri customer is on such as https://wwww.acmeinc.com/pricing?utm_source=adwords including protocol, host, and query string.

ip_address

string false IP address of the customer, If not set, we extract the remote IP address.

user_agent_string

string false The customer's browser agent string for device context.

Users

Update a User

POST https://api.moesif.net/v1/users

Updates a user profile in Moesif, which is typically a single person or API consumer. For updating customer profiles such as for monetization use cases, see companies and subscriptions.

You can also track users automatically using a Moesif client integration like moesif-browser-js or Segment.

User properties can be stored via the metadata object.

We’ve reserved some metadata fields that have semantic meanings for users, and we handle them in special ways. For example, we expect email to be a string containing the user’s email address which is used to look up a user's demographic enrichment data and send behavioral emails.

Reserved metadata fields include:

Create vs update

If the user does not exist, Moesif will create a new one.

If a user exists, the new user properties will be merged with the existing properties recursively. This means you don't need to resend the entire user object if you are only updating a single field.

Do not call identifyUser for anonymous visitors. The SDK automatically tracks these via a generated anonymousId in localStorage. Once you call identifyUser, Moesif automatically merges multiple user profiles if needed.
POST https://api.moesif.net/v1/users

Example Request
  {
    "user_id": "12345",
    "company_id": "67890",
    "metadata": {
      "email": "john@acmeinc.com",
      "first_name": "John",
      "last_name": "Doe",
      "title": "Software Engineer",
      "sales_info": {
          "stage": "Customer",
          "lifetime_value": 24000,
          "account_owner": "mary@contoso.com"
      }
    }
  }
# You can also use wget
curl -X POST https://api.moesif.net/v1/users \
  -d '{"user_id":"12345","company_id":"67890","metadata":{"email":"john@acmeinc.com","first_name":"John","last_name":"Doe","title":"Software Engineer","sales_info":{"stage":"Customer","lifetime_value":24000,"account_owner":"mary@contoso.com"}}}' \
  -H 'Accept: application/json' \
  -H 'X-Moesif-Application-Id: YOUR_COLLECTOR_APPLICATION_ID'
var moesifapi = require('moesifapi');
var apiClient = moesifapi.ApiController;

moesifapi.configuration.ApplicationId = "YOUR_COLLECTOR_APPLICATION_ID";

// Only userId is required.
// metadata can be any custom object
var user = {
  userId: '12345',
  companyId: '67890'
  metadata: {
    email: 'john@acmeinc.com',
    firstName: 'John',
    lastName: 'Doe',
    title: 'Software Engineer',
    salesInfo: {
        stage: 'Customer',
        lifetimeValue: 24000,
        accountOwner: 'mary@contoso.com',
    },
  }
};
// 4. Create a single user
apiClient.updateUser(new moesifapi.UserModel(user), function(error, response, context) {
  // Do Something
});
from moesifapi.moesif_api_client import *
from moesifapi.models import *

api_client = MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID").api

# Only user_id is required.
# metadata can be any custom object
user = {
  'user_id': '12345',
  'company_id': '67890', # If set, associate user with a company object
  'metadata': {
    'email': 'john@acmeinc.com',
    'first_name': 'John',
    'last_name': 'Doe',
    'title': 'Software Engineer',
    'sales_info': {
        'stage': 'Customer',
        'lifetime_value': 24000,
        'account_owner': 'mary@contoso.com'
    },
  }
}

update_user = api_client.update_user(user)
api_client = MoesifApi::MoesifAPIClient.new('YOUR_COLLECTOR_APPLICATION_ID').api

metadata => {
  :email => 'john@acmeinc.com',
  :first_name => 'John',
  :last_name => 'Doe',
  :title => 'Software Engineer',
  :salesInfo => {
      :stage => 'Customer',
      :lifetime_value => 24000,
      :accountOwner => 'mary@contoso.com',
  }
}

# Only user_id is required.
# metadata can be any custom object
user = UserModel.new()
user.user_id = "12345"
user.company_id = "67890" # If set, associate user with a company object
user.metadata = metadata

update_user = api_client.update_user(user)
<?php
// Depending on your project setup, you might need to include composer's
// autoloader in your PHP code to enable autoloading of classes.
require_once "vendor/autoload.php";

// Import the SDK client in your project:
use MoesifApi\MoesifApiClient;
$apiClient = new MoesifApiClient("YOUR_COLLECTOR_APPLICATION_ID")->getApi();;

// metadata can be any custom object
$user->metadata = array(
        "email" => "john@acmeinc.com",
        "first_name" => "John",
        "last_name" => "Doe",
        "title" => "Software Engineer",
        "sales_info" => array(
            "stage" => "Customer",
            "lifetime_value" => 24000,
            "account_owner" => "mary@contoso.com"
        )
    );

$user = new Models\UserModel();
$user->userId = "12345";
$user->companyId = "67890"; // If set, associate user with a company object
$user->metadata = $metadata;

$apiClient->updateUser($user);
import "github.com/moesif/moesifapi-go"
import "github.com/moesif/moesifapi-go/models"

apiClient := moesifapi.NewAPI("YOUR_COLLECTOR_APPLICATION_ID")

// metadata can be any custom dictionary
metadata := map[string]interface{}{
  "email", "john@acmeinc.com",
  "first_name", "John",
  "last_name", "Doe",
  "title", "Software Engineer",
  "sales_info", map[string]interface{}{
      "stage", "Customer",
      "lifetime_value", 24000,
      "account_owner", "mary@contoso.com",
  },
}

// Only UserId is required
user := models.UserModel{
  UserId:  "12345",
  CompanyId:  "67890", // If set, associate user with a company object
  Metadata:  &metadata,
}

// Queue the user asynchronously
err := apiClient.QueueUser(&user)

// Update the user synchronously
err := apiClient.UpdateUser(&user)
var apiClient = new MoesifApiClient("YOUR_COLLECTOR_APPLICATION_ID").Api;;

// metadata can be any custom dictionary
var metadata = new Dictionary<string, object>
{
    {"email", "john@acmeinc.com"},
    {"first_name", "John"},
    {"last_name", "Doe"},
    {"title", "Software Engineer"},
    {"sales_info", new Dictionary<string, object> {
        {"stage", "Customer"},
        {"lifetime_value", 24000},
        {"account_owner", "mary@contoso.com"}
    }
};

// Only user_id is required
var user = new UserModel()
{
    UserId = "12345",
  CompanyId = "67890",
    Metadata = metadata
};

// Update the user asynchronously
await apiClient.UpdateUserAsync(user);

// Update the user synchronously
apiClient.UpdateUser(user);
MoesifAPIClient apiClient = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");

// Only userId is required
// metadata can be any custom object
UserModel user = new UserBuilder()
    .userId("12345")
    .companyId("67890") // If set, associate user with a company object
    .metadata(APIHelper.deserialize("{" +
        "\"email\": \"johndoe@acmeinc.com\"," +
        "\"first_name\": \"John\"," +
        "\"last_name\": \"Doe\"," +
        "\"title\": \"Software Engineer\"," +
        "\"sales_info\": {" +
            "\"stage\": \"Customer\"," +
            "\"lifetime_value\": 24000," +
            "\"account_owner\": \"mary@contoso.com\"" +
          "}" +
        "}"))
    .build();

// Synchronous Call to update user
apiClient.updateUser(user);

// Asynchronous Call to update user
apiClient.updateUserAsync(user, callBack);
var moesif = require('moesif-browser-js');

moesif.init({
  applicationId: 'YOUR_COLLECTOR_APPLICATION_ID'
  // add other option here.
});

// The second argument containing user metatdata is optional,
// but useful to store customer properties like email and name.
moesif.identifyUser('12345', {
  email: 'john@acmeinc.com',
  firstName: 'John',
  lastName: 'Doe',
  title: 'Software Engineer',
  salesInfo: {
      stage: 'Customer',
      lifetimeValue: 24000,
      accountOwner: 'mary@contoso.com',
  },
});

User id

Users in Moesif are identified via a user_id and should be a permanent and robust identifier, like a database id. We recommend not using values that can change like email addresses or usernames. The user_id matches the identifyUser hook in your API monitoring agent.

Users can also be associated to a company by setting the company_id field when you update a user. This enables tracking API usage for individual users along with account-level usage.

Name Type Required Description
user_id string true The unique identifier for this user.
company_id string false Associate the user with a company (Helpful for B2B companies)
session_token string false Associate this user with a new API key/session token. This field is append only meaning when you set this field, previously set tokens are not removed.
modified_time string(date-time) false Last modified time of user profile. Set automatically by Moesif if not provided.
ip_address string false Set the user's last known ip address. Moesif sets this automatically from the user's most recent API activity if not provided.
user_agent_string string false Set the user's last known user agent. Moesif sets this automatically from the user's most recent API activity if not provided.
campaign object false Referrer and UTM parameters to track effectiveness of your acquisition channels. Set automatically by moesif-browser-js, but not with server side SDKs

utm_source

string false UTM parameter that identifies which site sent the traffic

utm_medium

string false UTM parameter that identifies what type of link was used, such as cost per click or email.

utm_campaign

string false UTM parameter that identifies a specific product promotion or strategic campaign.

utm_term

string false UTM parameter that identifies search terms.

utm_content

string false UTM parameter that identifies what specifically was clicked to bring the user to the site, such as a banner ad or a text link.

referrer

string false The referring URI before your domain.

referring_domain

string false The referring domain of the page that linked to your domain.

gclid

string false Google click Identifier to track Google Ads
metadata object false An object containing user demographics or other properties you want to store with this profile.

Update Users in Batch

POST https://api.moesif.net/v1/users/batch

Updates a list of user profiles in a single batch. Users are typically a single person or API consumer. For updating customer profiles such as for monetization use cases, see companies and subscriptions.

You can also track users automatically using a Moesif client integration like moesif-browser-js or Segment.

Any custom user properties can be stored via the metadata object.

We’ve reserved some fields names in the metadata object that have semantic meanings for users, and we handle them in special ways. For example, we expect email to be a string containing the user’s email address which is used to sync with external CRMs and to look up a user's Gravatar and demographics.

Reserved metadata fields include:

Create vs update

If the user does not exist, Moesif will create a new one.

If a user exists, the new user properties will be merged with the existing properties recursively. This means you don't need to resend the entire user object if you are only updating a single field.

POST https://api.moesif.net/v1/users/batch

Example Request
[
  {
    "user_id": "12345",
    "company_id": "67890",
    "metadata": {
      "email": "john@acmeinc.com",
      "first_name": "John",
      "last_name": "Doe",
      "title": "Software Engineer",
      "sales_info": {
        "stage": "Customer",
        "lifetime_value": 24000,
        "account_owner": "mary@contoso.com"
      }
    }
  },
  {
    "user_id": "54321",
    "company_id": "67890",
    "metadata": {
      "email": "mary@acmeinc.com",
      "first_name": "Mary",
      "last_name": "Jane",
      "title": "Software Engineer",
      "sales_info": {
        "stage": "Customer",
        "lifetime_value": 24000,
        "account_owner": "mary@contoso.com"
      }
    }
  }
]
# You can also use wget
curl -X POST https://api.moesif.net/v1/users/batch \
  -d '[{"user_id":"12345","company_id":"67890","metadata":{"email":"john@acmeinc.com","first_name":"John","last_name":"Doe","title":"Software Engineer","sales_info":{"stage":"Customer","lifetime_value":24000,"account_owner":"mary@contoso.com"}}},{"user_id":"54321","company_id":"67890","metadata":{"email":"mary@acmeinc.com","first_name":"Mary","last_name":"Jane","title":"Software Engineer","sales_info":{"stage":"Customer","lifetime_value":24000,"account_owner":"mary@contoso.com"}}}]' \
  -H 'Accept: application/json' \
  -H 'X-Moesif-Application-Id: YOUR_COLLECTOR_APPLICATION_ID'


var moesifapi = require('moesifapi');
var apiClient = moesifapi.ApiController;

moesifapi.configuration.ApplicationId = "YOUR_COLLECTOR_APPLICATION_ID";

// 3. Generate a User Model
var userA = {
  userId: '12345',
  companyId: '67890'
  metadata: {
    email: 'john@acmeinc.com',
    firstName: 'John',
    lastName: 'Doe',
    title: 'Software Engineer',
    salesInfo: {
        stage: 'Customer',
        lifetimeValue: 24000,
        accountOwner: 'mary@contoso.com',
    },
  }
};

var userB = {
  userId: '67890',
  companyId: '67890'
  metadata: {
    email: 'mary@contoso.com',
    firstName: 'Mary',
    lastName: 'Jane',
    title: 'Software Engineer',
    salesInfo: {
        stage: 'Customer',
        lifetimeValue: 24000,
        accountOwner: 'mary@contoso.com',
    },
  }
};

var users = [
  new moesifapi.UserModel(userA),
  new moesifapi.UserModel(userB)
];

// 4. Send batch of users
apiClient.updateUsersBatch(users, function(error, response, context) {
  // Do Something
});
from moesifapi.moesif_api_client import *
from moesifapi.models import *

api_client = MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID").api

userA = {
  'user_id': '12345',
  'company_id': '67890', # If set, associate user with a company object
  'metadata': {
    'email': 'john@acmeinc.com',
    'first_name': 'John',
    'last_name': 'Doe',
    'title': 'Software Engineer',
    'sales_info': {
        'stage': 'Customer',
        'lifetime_value': 24000,
        'account_owner': 'mary@contoso.com'
    },
  }
}

userB = {
  'user_id': '54321',
  'company_id': '67890', # If set, associate user with a company object
  'metadata': {
    'email': 'mary@acmeinc.com',
    'first_name': 'Mary',
    'last_name': 'Jane',
    'title': 'Software Engineer',
    'sales_info': {
        'stage': 'Customer',
        'lifetime_value': 48000,
        'account_owner': 'mary@contoso.com'
    },
  }
}
update_users = api_client.update_users_batch([userA, userB])
api_client = MoesifApi::MoesifAPIClient.new('YOUR_COLLECTOR_APPLICATION_ID').api

users = []

metadata => {
  :email => 'john@acmeinc.com',
  :first_name => 'John',
  :last_name => 'Doe',
  :title => 'Software Engineer',
  :salesInfo => {
      :stage => 'Customer',
      :lifetime_value => 24000,
      :accountOwner => 'mary@contoso.com',
  }
}

# Only user_id is required.
# metadata can be any custom object
user = UserModel.new()
user.user_id = "12345"
user.company_id = "67890" # If set, associate user with a company object
user.metadata = metadata

users << user

api_client = api_controller.update_users_batch(user_model)
<?php
// Depending on your project setup, you might need to include composer's
// autoloader in your PHP code to enable autoloading of classes.
require_once "vendor/autoload.php";

use MoesifApi\MoesifApiClient;
$apiClient = new MoesifApiClient("YOUR_COLLECTOR_APPLICATION_ID")->getApi();

// metadata can be any custom object
$userA->metadata = array(
        "email" => "john@acmeinc.com",
        "first_name" => "John",
        "last_name" => "Doe",
        "title" => "Software Engineer",
        "sales_info" => array(
            "stage" => "Customer",
            "lifetime_value" => 24000,
            "account_owner" => "mary@contoso.com"
        )
    );

$userA = new Models\UserModel();
$userA->userId = "12345";
$userA->companyId = "67890"; // If set, associate user with a company object
$userA->metadata = $metadata;

// metadata can be any custom object
$userB->metadata = array(
        "email" => "mary@acmeinc.com",
        "first_name" => "Mary",
        "last_name" => "Jane",
        "title" => "Software Engineer",
        "sales_info" => array(
            "stage" => "Customer",
            "lifetime_value" => 24000,
            "account_owner" => "mary@contoso.com"
        )
    );

$userB = new Models\UserModel();
$userB->userId = "12345";
$userB->companyId = "67890"; // If set, associate user with a company object
$userB->metadata = $metadata;

$users = array($userA, $userB)
$apiClient->updateUsersBatch($user);
import "github.com/moesif/moesifapi-go"
import "github.com/moesif/moesifapi-go/models"

apiClient := moesifapi.NewAPI("YOUR_COLLECTOR_APPLICATION_ID")

// List of Users
var users []*models.UserModel

// metadata can be any custom dictionary
metadata := map[string]interface{}{
  "email", "john@acmeinc.com",
  "first_name", "John",
  "last_name", "Doe",
  "title", "Software Engineer",
  "sales_info", map[string]interface{}{
      "stage", "Customer",
      "lifetime_value", 24000,
      "account_owner", "mary@contoso.com",
  },
}

// Only UserId is required
userA := models.UserModel{
  UserId:  "12345",
  CompanyId:  "67890", // If set, associate user with a company object
  Metadata:  &metadata,
}

users = append(users, &userA)

// Queue the user asynchronously
err := apiClient.QueueUsers(&users)

// Update the user synchronously
err := apiClient.UpdateUsersBatch(&users)
var apiClient = new MoesifApiClient("YOUR_COLLECTOR_APPLICATION_ID").Api;;

var users = new List<UserModel>();

var metadataA = new Dictionary<string, object>
{
    {"email", "john@acmeinc.com"},
    {"first_name", "John"},
    {"last_name", "Doe"},
    {"title", "Software Engineer"},
    {"sales_info", new Dictionary<string, object> {
        {"stage", "Customer"},
        {"lifetime_value", 24000},
        {"account_owner", "mary@contoso.com"}
    }
};

// Only user_id is required
var userA = new UserModel()
{
    UserId = "12345",
  CompanyId = "67890", // If set, associate user with a company object
    Metadata = metadataA
};

var metadataB = new Dictionary<string, object>
{
    {"email", "mary@acmeinc.com"},
    {"first_name", "Mary"},
    {"last_name", "Jane"},
    {"title", "Software Engineer"},
    {"sales_info", new Dictionary<string, object> {
        {"stage", "Customer"},
        {"lifetime_value", 24000},
        {"account_owner", "mary@contoso.com"}
    }
};

// Only user_id is required
var userB = new UserModel()
{
    UserId = "54321",
  CompanyId = "67890",
    Metadata = metadataA
};


users.Add(userA);
users.Add(userB);

// Update the users asynchronously
await apiClient.UpdateUsersBatchAsync(users);

// Update the users synchronously
apiClient.UpdateUsersBatch(users);
MoesifAPIClient apiClient = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID");

List<UserModel> users = new ArrayList<UserModel>();

UserModel userA = new UserBuilder()
        .userId("12345")
        .companyId("67890")
        .metadata(APIHelper.deserialize("{" +
            "\"email\": \"johndoe@acmeinc.com\"," +
            "\"first_name\": \"John\"," +
            "\"last_name\": \"Doe\"," +
            "\"title\": \"Software Engineer\"," +
            "\"sales_info\": {" +
                "\"stage\": \"Customer\"," +
                "\"lifetime_value\": 24000," +
                "\"account_owner\": \"mary@contoso.com\"" +
              "}" +
            "}"))
        .build();
users.add(userA);

UserModel userB = new UserBuilder()
        .userId("54321")
        .companyId("67890")
        .metadata(APIHelper.deserialize("{" +
            "\"email\": \"johndoe@acmeinc.com\"," +
            "\"first_name\": \"John\"," +
            "\"last_name\": \"Doe\"," +
            "\"title\": \"Software Engineer\"," +
            "\"sales_info\": {" +
                "\"stage\": \"Customer\"," +
                "\"lifetime_value\": 24000," +
                "\"account_owner\": \"mary@contoso.com\"" +
              "}" +
            "}"))
        .build();
users.add(userB);

// Asynchronous call to update users
APICallBack<Object> callBack = new APICallBack<Object>() {
    public void onSuccess(HttpContext context, Object response) {
      // Do something
    }

    public void onFailure(HttpContext context, Throwable error) {
      // Do something else
    }
};

// Asynchronous call to update users
apiClient.updateUsersBatchAsync(users, callBack);


// Synchronous call to update users
apiClient.updateUsersBatch(users, callBack);
Since this is a client side SDK, you cannot save a batch of users with moesif-browser-js.

User id

Users in Moesif are identified via a user_id and should be a permanent and robust identifier, like a database id. We recommend not using values that can change like email addresses or usernames. The user_id matches the identifyUser hook in your API monitoring agent.

Users can also be associated to a company by setting the company_id field when you update a user. This enables tracking API usage for individual users along with account-level usage.

Name Type Required Description
user_id string true The unique identifier for this user.
company_id string false Associate the user with a company (Helpful for B2B companies).
session_token string false Associate this user with a new API key/session token. This field is append only meaning when you set this field, previously set tokens are not removed.
modified_time string(date-time) false Last modified time of user profile. Set automatically by Moesif if not provided.
ip_address string false Set the user's last known ip address. Moesif sets this automatically from the user's most recent API activity if not provided.
user_agent_string string false Set the user's last known user agent. Moesif sets this automatically from the user's most recent API activity if not provided.
campaign object false Referrer and UTM parameters to track effectiveness of your acquisition channels. Set automatically by moesif-browser-js, but not with server side SDKs.

utm_source

string false UTM parameter that identifies which site sent the traffic.

utm_medium

string false UTM parameter that identifies what type of link was used, such as cost per click or email.

utm_campaign

string false UTM parameter that identifies a specific product promotion or strategic campaign.

utm_term

string false UTM parameter that identifies search terms.

utm_content

string false UTM parameter that identifies what specifically was clicked to bring the user to the site, such as a banner ad or a text link.

referrer

string false The referring URI before your domain.

referring_domain

string false The referring domain of the page that linked to your domain.

gclid

string false Google click Identifier to track Google Ads.
metadata object false An object containing user demographics or other properties you want to store with this profile.

Companies

Update a Company

POST https://api.moesif.net/v1/companies

Updates a company profile in Moesif. A company is your direct customer paying for your service. A company can have one or more users and one or more subscriptions. More info on the Moesif data model.

You can save custom properties to a company via the metadata object. While optional, it's also recommended to set the company_domain. When set, Moesif will enrich the company with publicly available information.

If company does not exist, a new one will be created. If a company exists, it will be merged on top of existing fields. Any new field set will override the existing fields. This is done via recursive merge which merges inner objects.

Create vs update

If the company does not exist, Moesif will create a new one.

If a company exists, the new company properties will be merged with the existing properties recursively. This means you don't need to resend the entire company object if you are only updating a single field.

If you call both identifyUser() and identifyCompany() in the same session, then Moesif will automatically associate the user with the company.
POST https://api.moesif.net/v1/companies

Example Request
{
  "company_id": "12345",
  "company_domain": "acmeinc.com",
  "metadata": {
    "org_name": "Acme, Inc",
    "plan_name": "Free",
    "deal_stage": "Lead",
    "mrr": 24000,
    "demographics": {
      "alexa_ranking": 500000,
      "employee_count": 47
    }
  }
}
# You can also use wget
curl -X POST https://api.moesif.net/v1/companies \
  -d '{"company_id":"12345","company_domain":"acmeinc.com","metadata":{"org_name":"Acme, Inc","plan_name":"Free","deal_stage":"Lead","mrr":24000,"demographics":{"alexa_ranking":500000,"employee_count":47}}}' \
  -H 'Accept: application/json' \
  -H 'X-Moesif-Application-Id: YOUR_COLLECTOR_APPLICATION_ID'
var moesifapi = require('moesifapi');
var apiClient = moesifapi.ApiController;

moesifapi.configuration.ApplicationId = "YOUR_COLLECTOR_APPLICATION_ID";


// Only companyId is required.
// metadata can be any custom object
var company = {
  companyId: '67890',
  companyDomain: 'acmeinc.com', // If domain is set, Moesif will enrich your profiles with publicly available info 
  metadata: {
    orgName: 'Acme, Inc',
    planName: 'Free Plan',
    dealStage: 'Lead',
    mrr: 24000,
    demographics: {
      alexaRanking: 500000,
      employeeCount: 47
    }
  }
};

apiClient.updateCompany(company, function(error, response, context) {
  // Do Something
});
from moesifapi.moesif_api_client import *
from moesifapi.models import *

api_client = MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID").api

# Only company_id is required.
# metadata can be any custom object
company = {
  'company_id': '12345',
  'company_domain': 'acmeinc.com', # If domain is set, Moesif will enrich your profiles with publicly available info 
  'metadata': {
    'org_name': 'Acme, Inc',
    'plan_name': 'Free',
    'deal_stage': 'Lead',
    'mrr': 24000,
    'demographics': {
        'alexa_ranking': 500000,
        'employee_count': 47
    },
  }
}

update_company = api_client.update_company(company)
api_client = MoesifApi::MoesifAPIClient.new('YOUR_COLLECTOR_APPLICATION_ID').api

metadata => {
  :org_name => 'Acme, Inc',
  :plan_name => 'Free',
  :deal_stage => 'Lead',
  :mrr => 24000,
  :demographics => {
      :alexa_ranking => 500000,
      :employee_count => 47
  }
}

# Only company_id is required.
# metadata can be any custom object
company = CompanyModel.new()
company.company_id = "67890"
company.company_domain = "acmeinc.com" # If domain is set, Moesif will enrich your profiles with publicly available info 
company.metadata = metadata

update_company = api_client.update_company(company)
<?php
// Depending on your project setup, you might need to include composer's
// autoloader in your PHP code to enable autoloading of classes.

require_once "vendor/autoload.php";

use MoesifApi\MoesifApiClient;
$apiClient = new MoesifApiClient("YOUR_COLLECTOR_APPLICATION_ID")->getApi();


$company = new Models\CompanyModel();
$company->companyId = "67890";
$company->companyDomain = "acmeinc.com";

// metadata can be any custom object
$company->metadata = array(
        "org_name" => "Acme, Inc",
        "plan_name" => "Free",
        "deal_stage" => "Lead",
        "mrr" => 24000,
        "demographics" => array(
            "alexa_ranking" => 500000,
            "employee_count" => 47
        )
    );

$apiClient->updateCompany($company);
import "github.com/moesif/moesifapi-go"
import "github.com/moesif/moesifapi-go/models"

apiClient := moesifapi.NewAPI("YOUR_COLLECTOR_APPLICATION_ID")

// metadata can be any custom dictionary
metadata := map[string]interface{}{
  "org_name", "Acme, Inc",
  "plan_name", "Free",
  "deal_stage", "Lead",
  "mrr", 24000,
  "demographics", map[string]interface{}{
      "alexa_ranking", 500000,
      "employee_count", 47,
  },
}

// Prepare company model
company := models.CompanyModel{
    CompanyId:        "67890",  // The only required field is your company id
    CompanyDomain:    "acmeinc.com", // If domain is set, Moesif will enrich your profiles with publicly available info 
    Metadata:         &metadata,
}

// Queue the company asynchronously
apiClient.QueueCompany(&company)

// Update the company synchronously
err := apiClient.UpdateCompany(&company)
var apiClient = new MoesifApiClient("YOUR_COLLECTOR_APPLICATION_ID").Api;;

// metadata can be any custom dictionary
var metadata = new Dictionary<string, object>
{
    {"org_name", "Acme, Inc"},
    {"plan_name", "Free"},
    {"deal_stage", "Lead"},
    {"mrr", 24000},
    {"demographics", new Dictionary<string, object> {
        {"alexa_ranking", 500000},
        {"employee_count", 47}
    }
};

// Only company id is required
var company = new CompanyModel()
{
  CompanyId = "67890",
  CompanyDomain = "acmeinc.com", // If domain is set, Moesif will enrich your profiles with publicly available info 
    Metadata = metadata
};

// Update the company asynchronously
await apiClient.UpdateCompanyAsync(company);

// Update the company synchronously
apiClient.UpdateCompany(company);
MoesifAPIClient apiClient = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID").Api;

// Only companyId is required
// metadata can be any custom object
CompanyModel company = new CompanyBuilder()
    .companyId("67890")
    .companyDomain("acmeinc.com") // If set, Moesif will enrich your profiles with publicly available info 
    .metadata(APIHelper.deserialize("{" +
        "\"org_name\": \"Acme, Inc\"," +
        "\"plan_name\": \"Free\"," +
        "\"deal_stage\": \"Lead\"," +
        "\"mrr\": 24000," +
        "\"demographics\": {" +
            "\"alexa_ranking\": 500000," +
            "\"employee_count\": 47" +
          "}" +
        "}"))
    .build();

// Asynchronous Call to update company
apiClient.updateCompanyAsync(company, callBack);

// Synchronous Call to update company
apiClient.updateCompany(company, callBack);
var moesif = require('moesif-browser-js');

moesif.init({
  applicationId: 'YOUR_COLLECTOR_APPLICATION_ID'
  // add other option here.
});

// Only the first argument is a string containing the company id. 
// This is the only required field. 
//
// The second argument is a object used to store a company info like plan, 
// MRR, and company demographics.
// 
// The third argument is a string containing company website or email domain. 
// If set, Moesif will enrich your profiles with publicly available info.  
metadata = {
  orgName: 'Acme, Inc',
  planName: 'Free Plan',
  dealStage: 'Lead',
  mrr: 24000,
  demographics: {
    alexaRanking: 500000,
    employeeCount: 47
  }
};

moesif.identifyCompany('67890', metadata, 'acmeinc.com');

Company ids

Users in Moesif are identified via a company_id and should be a permanent and robust identifier, like a database id. We recommend not using values that can change like website domain or company name. The company_id matches the identifyCompany hook in your API monitoring agent.

Users can also be associated to a company by setting the company_id field when you update a user. This enables tracking API usage for individual users along with account-level usage.

Name Type Required Description
company_id string true The unique identifier for this company.
company_domain string false If set, Moesif will enrich your company profile with publicly available info
session_token string false Associate this company with a new API key/session token. This field is append only meaning when you set this field, previously set tokens are not removed.
modified_time string(date-time) false Last modified time of company profile. Set automatically by Moesif if not provided.
ip_address string false Set the company's last known ip address. Moesif sets this automatically from the user's most recent API activity if not provided.
campaign object false Referrer and UTM parameters to track effectiveness of your acquisition channels. Set automatically by moesif-browser-js, but not with server side SDKs

utm_source

string false UTM parameter that identifies which site sent the traffic

utm_medium

string false UTM parameter that identifies what type of link was used, such as cost per click or email.

utm_campaign

string false UTM parameter that identifies a specific product promotion or strategic campaign.

utm_term

string false UTM parameter that identifies search terms.

utm_content

string false UTM parameter that identifies what specifically was clicked to bring the company to the site, such as a banner ad or a text link.

referrer

string false The referring URI before your domain.

referring_domain

string false The referring domain of the page that linked to your domain.

gclid

string false Google click Identifier to track Google Ads
metadata object false An object containing company demographics or other properties you want to store with this profile.

Update Companies in Batch

POST https://api.moesif.net/v1/companies/batch

Updates a list of companies profile in Moesif.

A custom JSON object can be placed in the metadata object of each company which will be stored as part of the company profile.

A company is your direct customer paying for your service. A company can have one or more users and one or more subscriptions. More info on the Moesif data model.

You can save custom properties to a company via the metadata object. While optional, it's also recommended to set the company_domain. When set, Moesif will enrich the company with publicly available information.

If company does not exist, a new one will be created. If a company exists, it will be merged on top of existing fields. Any new field set will override the existing fields. This is done via recursive merge which merges inner objects.

POST https://api.moesif.net/v1/companies/batch

Example Request
[
  {
    "company_id": "12345",
    "company_domain": "acmeinc.com",
    "metadata": {
      "org_name": "Acme, Inc",
      "plan_name": "Free",
      "deal_stage": "Lead",
      "mrr": 24000,
      "demographics": {
        "alexa_ranking": 500000,
        "employee_count": 47
      }
    }
  },
  {
    "company_id": "54321",
    "company_domain": "contoso.com",
    "metadata": {
      "org_name": "Contoso, Inc",
      "plan_name": "Paid",
      "deal_stage": "Lead",
      "mrr": 48000,
      "demographics": {
        "alexa_ranking": 500000,
        "employee_count": 47
      }
    }
  }
]
# You can also use wget
curl -X POST https://api.moesif.net/v1/companies/batch \
  -d '[{"company_id":"12345","company_domain":"acmeinc.com","metadata":{"org_name":"Acme, Inc","plan_name":"Free","deal_stage":"Lead","mrr":24000,"demographics":{"alexa_ranking":500000,"employee_count":47}}},{"company_id":"54321","company_domain":"contoso.com","metadata":{"org_name":"Contoso, Inc","plan_name":"Paid","deal_stage":"Lead","mrr":48000,"demographics":{"alexa_ranking":500000,"employee_count":47}}}]' \
  -H 'Accept: application/json' \
  -H 'X-Moesif-Application-Id: YOUR_COLLECTOR_APPLICATION_ID'
var moesifapi = require('moesifapi');
var apiClient = moesifapi.ApiController;

moesifapi.configuration.ApplicationId = "YOUR_COLLECTOR_APPLICATION_ID";


// Only companyId is required.
// metadata can be any custom object
var companies = [{
    companyId: '67890',
    companyDomain: 'acmeinc.com', // If domain is set, Moesif will enrich your profiles with publicly available info 
    metadata: {
      orgName: 'Acme, Inc',
      planName: 'Free Plan',
      dealStage: 'Lead',
      mrr: 24000,
      demographics: {
        alexaRanking: 500000,
        employeeCount: 47
      }
    }
  },
  {
    companyId: '09876',
    companyDomain: 'contoso.com', // If domain is set, Moesif will enrich your profiles with publicly available info 
    metadata: {
      orgName: 'Contoso, Inc',
      planName: 'Paid Plan',
      dealStage: 'Lead',
      mrr: 48000,
      demographics: {
        alexaRanking: 500000,
        employeeCount: 53
      }
    }
  }
]

apiClient.updateCompanies(companies, function(error, response, context) {
  // Do Something
});
from moesifapi.moesif_api_client import *
from moesifapi.models import *

api_client = MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID").api

# Only company_id is required.
# metadata can be any custom object
companies = [{
  'company_id': '67890',
  'company_domain': 'acmeinc.com', # If domain is set, Moesif will enrich your profiles with publicly available info 
  'metadata': {
    'org_name': 'Acme, Inc',
    'plan_name': 'Free',
    'deal_stage': 'Lead',
    'mrr': 24000,
    'demographics': {
        'alexa_ranking': 500000,
        'employee_count': 47
    },
  }
},
{
  'company_id': '09876',
  'company_domain': 'contoso.com', # If domain is set, Moesif will enrich your profiles with publicly available info 
  'metadata': {
    'org_name': 'Contoso, Inc',
    'plan_name': 'Paid',
    'deal_stage': 'Lead',
    'mrr': 48000,
    'demographics': {
        'alexa_ranking': 500000,
        'employee_count': 53
    },
  }
}]

update_company = api_client.update_companies(companies)
api_client = MoesifApi::MoesifAPIClient.new('YOUR_COLLECTOR_APPLICATION_ID').api

companies = []

metadata => {
  :org_name => 'Acme, Inc',
  :plan_name => 'Free',
  :deal_stage => 'Lead',
  :mrr => 24000,
  :demographics => {
      :alexa_ranking => 500000,
      :employee_count => 47
  }
}

# Only company_id is required.
# metadata can be any custom object
company = CompanyModel.new()
company.company_id = "67890"
company.company_domain = "acmeinc.com" # If domain is set, Moesif will enrich your profiles with publicly available info 
company.metadata = metadata

companies << company

update_company = api_client.update_companies(companies)
<?php
// Depending on your project setup, you might need to include composer's
// autoloader in your PHP code to enable autoloading of classes.

require_once "vendor/autoload.php";

use MoesifApi\MoesifApiClient;
$apiClient = new MoesifApiClient("YOUR_COLLECTOR_APPLICATION_ID")->getApi();

$companyA = new Models\CompanyModel();
$companyA->companyId = "67890";
$companyA->companyDomain = "acmeinc.com";

// metadata can be any custom object
$companyB->metadata = array(
        "org_name" => "Acme, Inc",
        "plan_name" => "Free",
        "deal_stage" => "Lead",
        "mrr" => 24000,
        "demographics" => array(
            "alexa_ranking" => 500000,
            "employee_count" => 47
        )
    );

$companyB = new Models\CompanyModel();
$companyB->companyId = "67890";
$companyB->companyDomain = "acmeinc.com";

// metadata can be any custom object
$companyB->metadata = array(
        "org_name" => "Acme, Inc",
        "plan_name" => "Free",
        "deal_stage" => "Lead",
        "mrr" => 24000,
        "demographics" => array(
            "alexa_ranking" => 500000,
            "employee_count" => 47
        )
    );

$companies = array($companyA, $companyB)
$apiClient->updateCompaniesBatch(array($companies));
import "github.com/moesif/moesifapi-go"
import "github.com/moesif/moesifapi-go/models"

apiClient := moesifapi.NewAPI("YOUR_COLLECTOR_APPLICATION_ID")

// List of Companies
var companies []*models.CompanyModel

// metadata can be any custom dictionary
metadata := map[string]interface{}{
  "org_name", "Acme, Inc",
  "plan_name", "Free",
  "deal_stage", "Lead",
  "mrr", 24000,
  "demographics", map[string]interface{}{
      "alexa_ranking", 500000,
      "employee_count", 47,
  },
}

// Prepare company model
companyA := models.CompanyModel{
    CompanyId:        "67890",  // The only required field is your company id
    CompanyDomain:  "acmeinc.com", // If domain is set, Moesif will enrich your profiles with publicly available info 
    Metadata:           &metadata,
}

companies = append(companies, &companyA)

// Queue the company asynchronously
apiClient.QueueCompanies(&companies)

// Update the company synchronously
err := apiClient.UpdateCompaniesBatch(&companies)
var apiClient = new MoesifApiClient("YOUR_COLLECTOR_APPLICATION_ID").Api;;

var companies = new List<CompanyModel>();

// metadata can be any custom dictionary
var metadataA = new Dictionary<string, object>
{
    {"org_name", "Acme, Inc"},
    {"plan_name", "Free"},
    {"deal_stage", "Lead"},
    {"mrr", 24000},
    {"demographics", new Dictionary<string, object> {
        {"alexa_ranking", 500000},
        {"employee_count", 47}
    }
};

// Only company id is required
var companyA = new CompanyModel()
{
  CompanyId = "67890",
  CompanyDomain = "acmeinc.com", // If domain is set, Moesif will enrich your profiles with publicly available info 
    Metadata = metadata
};

// metadata can be any custom dictionary
var metadataB = new Dictionary<string, object>
{
    {"org_name", "Contoso, Inc"},
    {"plan_name", "Paid"},
    {"deal_stage", "Lead"},
    {"mrr", 48000},
    {"demographics", new Dictionary<string, object> {
        {"alexa_ranking", 500000},
        {"employee_count", 53}
    }
};

// Only company id is required
var companyB = new CompanyModel()
{
  CompanyId = "09876",
  CompanyDomain = "contoso.com", // If domain is set, Moesif will enrich your profiles with publicly available info 
    Metadata = metadata
};


companies.Add(companyA);
companies.Add(companyB);

// Update the companies asynchronously
await apiClient.UpdateCompaniesBatchAsync(companies);

// Update the companies synchronously
apiClient.UpdateCompaniesBatch(companies);
MoesifAPIClient apiClient = new MoesifAPIClient("YOUR_COLLECTOR_APPLICATION_ID").Api;

// Only companyId is required
// metadata can be any custom object
CompanyModel company = new CompanyBuilder()
    .companyId("67890")
    .companyDomain("acmeinc.com") // If set, Moesif will enrich your profiles with publicly available info 
    .metadata(APIHelper.deserialize("{" +
        "\"org_name\": \"Acme, Inc\"," +
        "\"plan_name\": \"Free\"," +
        "\"deal_stage\": \"Lead\"," +
        "\"mrr\": 24000," +
        "\"demographics\": {" +
            "\"alexa_ranking\": 500000," +
            "\"employee_count\": 47" +
          "}" +
        "}"))
    .build();

// Asynchronous Call to update company
apiClient.updateCompanyAsync(company, callBack);

// Synchronous Call to update company
apiClient.updateCompany(company, callBack);
Since this is a client side SDK, you cannot save a batch of companies with moesif-browser-js.

Company ids

Users in Moesif are identified via a company_id and should be a permanent and robust identifier, like a database id. We recommend not using values that can change like website domain or company name. The company_id matches the identifyCompany hook in your API monitoring agent.

Users can also be associated to a company by setting the company_id field when you update a user. This enables tracking API usage for individual users along with account-level usage.

Name Type Required Description
company_id string true The unique identifier for this company.
company_domain string false If set, Moesif will enrich your company profile with publicly available info
session_token string false Associate this company with a new API key/session token. This field is append only meaning when you set this field, previously set tokens are not removed.
modified_time string(date-time) false Last modified time of company profile. Set automatically by Moesif if not provided.
ip_address string false Set the company's last known ip address. Moesif sets this automatically from the user's most recent API activity if not provided.
campaign object false Referrer and UTM parameters to track effectiveness of your acquisition channels. Set automatically by moesif-browser-js, but not with server side SDKs

utm_source

string false UTM parameter that identifies which site sent the traffic

utm_medium

string false UTM parameter that identifies what type of link was used, such as cost per click or email.

utm_campaign

string false UTM parameter that identifies a specific product promotion or strategic campaign.

utm_term

string false UTM parameter that identifies search terms.

utm_content

string false UTM parameter that identifies what specifically was clicked to bring the company to the site, such as a banner ad or a text link.

referrer

string false The referring URI before your domain.

referring_domain

string false The referring domain of the page that linked to your domain.

gclid

string false Google click Identifier to track Google Ads
metadata object false An object containing company demographics or other properties you want to store with this profile.

Subscriptions

Update a Subscription

POST https://api.moesif.net/v1/subscriptions

Updates a subscription for a subscription in Moesif. A subscription represents a single plan a customer is subscribed to and paying for. A company can have one or more subscriptions. Any custom subscription properties can be stored via the metadata object.

Create vs update

If the subscription does not exist, Moesif will create a new one.

If a subscription exists, the new subscription properties will be merged with the existing properties recursively. This means you don't need to resend the entire subscription object if you are only updating a single field.

POST https://api.moesif.net/v1/subscriptions

Example Request
{
    "subscription_id": "12345", // Subscription Id
    "company_id": "67890", // Company Id
    "current_period_start": "2024-02-21T17:32:28.000Z",
    "current_period_end": "2024-11-21T17:32:28.000Z",
    "status": "active",
    "metadata": {
        "subscription_type": "PAYG",
        "subscription_tier": "Pro",
        "quota": {
            "quota_limit": 1000000,
            "quota_period": "Year"
        }
    }
}
# You can also use wget
curl --location 'https://api.moesif.net/v1/subscriptions' \
--header 'X-Moesif-Application-Id: YOUR_COLLECTOR_APPLICATION_ID' \
--header 'Content-Type: application/json' \
--data '{
    "subscription_id": "12345",
    "company_id": "67890",
    "current_period_start": "2024-02-21T17:32:28.000Z",
    "current_period_end": "2024-11-21T17:32:28.000Z",
    "status": "active",
    "metadata": {
        "subscription_type": "PAYG",
        "subscription_tier": "Pro",
        "quota": {
            "quota_limit": 1000000,
            "quota_period": "YEAR"
        }
    }
}'

Subscription ids

Subscriptions in Moesif are identified via a subscription_id and should be a permanent and robust identifier, like a database id. We recommend not using values that can change like website domain or subscription name.

Name Type Required Description
subscription_id string true The unique identifier for this subscription.
company_id string true The unique identifier for the company this subscription should be associated with.
current_period_start string(date-time) false The start time of the current billing term. This can be yearly, monthly, or other billing term. Required for quota and billing management.
current_period_end string(date-time) false The end time of the current billing term. This can be yearly, monthly, or other billing term. Required for quota and billing management.
status string true One of [active, cancelled, paused, trialing, pending, draft, future]. This can be used to drive governance rules that the subscription status in Moesif such as blocking access to cancelled subscriptions.
metadata object false An object containing subscription demographics or other properties you want to store with this profile.

Update Subscriptions in Batch

POST https://api.moesif.net/v1/subscriptions/batch

Updates a list of subscriptions profile in Moesif.

A custom JSON object can be placed in the metadata object of each subscription which will be stored as part of the subscription profile.

If subscription does not exist, a new one will be created. If a subscription exists, it will be merged on top of existing fields. Any new field set will override the existing fields. This is done via recursive merge which merges inner objects.

POST https://api.moesif.net/v1/subscriptions/batch

Example Request
[
  {
    "subscription_id": "12345", // Subscription Id
    "company_id": "67890", // Company Id
    "current_period_start": "2024-02-21T17:32:28.000Z",
    "current_period_end": "2024-11-21T17:32:28.000Z",
    "status": "active",
    "metadata": {
        "subscription_type": "PAYG",
        "subscription_tier": "Pro",
        "quota": {
            "quota_limit": 1000000,
            "quota_period": "Year"
        }
    }
},
{
    "subscription_id": "abcde", // Subscription Id
    "company_id": "xyz", // Company Id
    "current_period_start": "2024-02-21T17:32:28.000Z",
    "current_period_end": "2024-11-21T17:32:28.000Z",
    "status": "active",
    "metadata": {
        "subscription_type": "PAYG",
        "subscription_tier": "Enterprise",
        "quota": {
            "quota_limit": 1000000,
            "quota_period": "YEAR"
        }
    }
}
]
# You can also use wget
curl --location 'https://api.moesif.net/v1/subscriptions/batch' \
--header 'X-Moesif-Application-Id: YOUR_COLLECTOR_APPLICATION_ID' \
--header 'Content-Type: application/json' \
--data '[{
    "subscription_id": "12345",
    "company_id": "67890",
    "current_period_start": "2024-02-21T17:32:28.000Z",
    "current_period_end": "2024-11-21T17:32:28.000Z",
    "status": "active",
    "metadata": {
        "subscription_type": "PAYG",
        "subscription_tier": "Pro",
        "quota": {
            "quota_limit": 1000000,
            "quota_period": "YEAR"
        }
    }
}]'

Subscription ids

Subscriptions in Moesif are identified via a subscription_id and should be a permanent and robust identifier, like a database id. We recommend not using values that can change like website domain or subscription name.

Name Type Required Description
subscription_id string true The unique identifier for this subscription.
company_id string true The unique identifier for the company this subscription should be associated with.
current_period_start string(date-time) false The start time of the current billing term. This can be yearly, monthly, or other billing term. Required for quota and billing management.
current_period_end string(date-time) false The end time of the current billing term. This can be yearly, monthly, or other billing term. Required for quota and billing management.
status string false One of [active, cancelled, paused, trialing, pending, draft, future]. This can be used to drive governance rules that the subscription status in Moesif such as blocking access to cancelled subscriptions.
metadata object false An object containing subscription demographics or other properties you want to store with this profile.

Config

Get Config

GET https://api.moesif.net/v1/config

Retrieves the configuration for governance rules and dynamic sampling rules.

POST https://api.moesif.net/v1/config

Example Response
{
    "sample_rate": 100,
    "user_sample_rate": {},
    "company_sample_rate": { },
    "user_rules": { },
    "company_rules": {  },
    "regex_config": [
        {
            "conditions": [
                {
                    "path": "request.route",
                    "value": "/health/.*"
                }
            ],
            "sample_rate": 0
        }
    ]
}

Get Rules

GET https://api.moesif.net/v1/rules

Retrieves the set of rules for quotas and behavior rules to block users/companies.

POST https://api.moesif.net/v1/rules

Example Response
[
    {
        "_id": "64ca685a833073c6b41b15f3",
        "created_at": "2024-02-01T00:00:00.000",
        "name": "Block Free Users who Exceeded their Monthly Quota",
        "block": true,
        "type": "user",
        "variables": [
            {
                "name": "0",
                "path": "body.plan_name"
            },
            {
                "name": "1",
                "path": "body.quota_amount"
            }
        ],
        "regex_config": [],
        "response": {
            "status": 429,
            "headers": {
                "X-Rate-Limit-Month": "{{1}}"
            },
            "body": {
                "error_code": "too_many_requests",
                "message": "You exceeded your monthly quota of {{1}} for the {{0}} plan. Please upgrade your plan."
            }
        }
    }
]

Management API v1

Scroll down for code samples, example requests and responses. Select a language for code samples from the tabs above or the mobile navigation menu.

Management API to query data in Moesif. You can use the management API to export data for custom reports or to build custom dashboards.

Base URLs:

If you're using the Moesif secure proxy, the base URL is http://localhost:9500/api/v1 assuming it's running on port 9500.

Terms of service

Authentication

Authorization: Bearer YOUR_MANAGEMENT_API_KEY

- Flow: password

- Token URL = https://api.moesif.com/v1/:orgId/oauth/access_tokens

Scope Scope Description
create:encrypted_keys Create encrypted Keys for the Moesif secure proxy
delete:dashboards Delete existing dashboards
update:dashboards Update existing dashboards
create:dashboards Create a new team dashboard that can be shared
read:public_workspaces Read public workspaces/shared links
read:virtual_eventtypes Read existing virtual events/tags
update:companies Update existing companies and associated company metadata
create:companies Create new companies and associated company metadata
create:reports Create a new report such as SmartDiff
delete:workspaces Delete existing workspaces
create:workspaces Create a new workspace/chart that can be shared
read:workspaces Read existing workspaces
update:virtual_eventtypes Update existing virtual events/tags
create:cohorts Save new customer cohorts
delete:encrypted_keys Delete encrypted Keys for the Moesif secure proxy
read:dashboards Read existing dashboards
read:events Read/query events and associated event metadata
create:events Create new events and associated event metadata
read:cohorts Read previously saved customer cohorts
read:encrypted_keys Read encrypted Keys for the Moesif secure proxy
update:apps Update an existing application
update:encrypted_keys Update encrypted Keys for the Moesif secure proxy
update:organizations Update an existing application
create:access_tokens Create new tokens to access the Management API or Collector API
create:users Create new users and associated user metadata
create:apps Create a new application/project under the organization
update:workspaces Update existing workspaces
delete:cohorts Delete previously saved customer cohorts
read:users Read/query users and associated user metadata
delete:virtual_eventtypes Delete existing virtual events/tags
read:reports Read reports such as SmartDiff
delete:reports Delete existing reports such as SmartDiff
update:users Update existing users and associated user metadata
update:cohorts Update previously saved customer cohorts
read:companies Read/query companies and associated company metadata
create:virtual_eventtypes Create virtual events/tags
delete:apps Delete an existing application
delete:companies Delete existing companies and associated company metadata
read:apps Read the organization's applications
create:eth_abi Create/upload new Ethereum ABI Entries
delete:users Delete existing users and associated user metadata

Companies

updateCompanies

Code samples

# You can also use wget
curl -X POST https://api.moesif.com/v1/search/~/companies \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'

  -d '{
  "company_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "session_token": "string",
  "company_domain": "string",
  "metadata": {}
}' 
const fetch = require('node-fetch');
const inputBody = {
  "company_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "session_token": "string",
  "company_domain": "string",
  "metadata": {}
};
const headers = {
  'Content-Type':'application/json',
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/companies',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}
input_body = {
  "company_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "session_token": "string",
  "company_domain": "string",
  "metadata": {}
}

r = requests.post('https://api.moesif.com/v1/search/~/companies', headers = headers, json = input_body)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Content-Type' => 'application/json',
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

input_payload = JSON.parse('{
  "company_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "session_token": "string",
  "company_domain": "string",
  "metadata": {}
}')

result = RestClient.post 'https://api.moesif.com/v1/search/~/companies',
  params: {
  }, 
  payload: input_payload.to_json, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$inputPayload = json_decode('{
  "company_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "session_token": "string",
  "company_domain": "string",
  "metadata": {}
}')

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('POST','https://api.moesif.com/v1/search/~/companies', array(
        'headers' => $headers,
        'json' => $inputPayload,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Content-Type": []string{"application/json"},
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }
    jsonPayload := `{
  "company_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "session_token": "string",
  "company_domain": "string",
  "metadata": {}
}`
    data := bytes.NewBuffer([]byte(jsonPayload))
    req, err := http.NewRequest("POST", "https://api.moesif.com/v1/search/~/companies", data)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }


    /// Make a dummy request
    public async Task MakePostRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/companies";

      string json = @"{
  ""company_id"": ""string"",
  ""modified_time"": ""2024-04-11T04:01:35.090Z"",
  ""session_token"": ""string"",
  ""company_domain"": ""string"",
  ""metadata"": {}
}";
      var content = JsonConvert.DeserializeObject(json);
      await PostAsync(content, url);


    }

    /// Performs a POST Request
    public async Task PostAsync(CompanyUpdate content, string url)
    {
        //Serialize Object
        StringContent jsonContent = SerializeObject(content);

        //Execute POST request
        HttpResponseMessage response = await Client.PostAsync(url, jsonContent);
    }



    /// Serialize an object to Json
    private StringContent SerializeObject(CompanyUpdate content)
    {
        //Serialize Object
        string jsonObject = JsonConvert.SerializeObject(content);

        //Create Json UTF8 String Content
        return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/companies");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-Type",'application/json');
con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

// Enable sending a request body
con.setDoOutput(true);

String jsonPayload = """{
  "company_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "session_token": "string",
  "company_domain": "string",
  "metadata": {}
}""";

// Write payload to the request
try(OutputStream os = con.getOutputStream()) {
    byte[] input = jsonPayload.getBytes("utf-8");
    os.write(input, 0, input.length);           
}

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

POST /search/~/companies

Update a Company

POST https://api.moesif.com/v1/search/~/companies

Example Request

{
  "company_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "session_token": "string",
  "company_domain": "string",
  "metadata": {}
}

Parameters

Name In Type Required Description
body body CompanyUpdate true none

Example responses

Responses

Status Meaning Description Schema
200 OK success None

Response Schema

batchUpdateCompanies

Code samples

# You can also use wget
curl -X POST https://api.moesif.com/v1/search/~/companies/batch \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'

  -d '[
  {
    "company_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "session_token": "string",
    "company_domain": "string",
    "metadata": {}
  }
]' 
const fetch = require('node-fetch');
const inputBody = [
  {
    "company_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "session_token": "string",
    "company_domain": "string",
    "metadata": {}
  }
];
const headers = {
  'Content-Type':'application/json',
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/companies/batch',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}
input_body = [
  {
    "company_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "session_token": "string",
    "company_domain": "string",
    "metadata": {}
  }
]

r = requests.post('https://api.moesif.com/v1/search/~/companies/batch', headers = headers, json = input_body)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Content-Type' => 'application/json',
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

input_payload = JSON.parse('[
  {
    "company_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "session_token": "string",
    "company_domain": "string",
    "metadata": {}
  }
]')

result = RestClient.post 'https://api.moesif.com/v1/search/~/companies/batch',
  params: {
  }, 
  payload: input_payload.to_json, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$inputPayload = json_decode('[
  {
    "company_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "session_token": "string",
    "company_domain": "string",
    "metadata": {}
  }
]')

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('POST','https://api.moesif.com/v1/search/~/companies/batch', array(
        'headers' => $headers,
        'json' => $inputPayload,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Content-Type": []string{"application/json"},
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }
    jsonPayload := `[
  {
    "company_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "session_token": "string",
    "company_domain": "string",
    "metadata": {}
  }
]`
    data := bytes.NewBuffer([]byte(jsonPayload))
    req, err := http.NewRequest("POST", "https://api.moesif.com/v1/search/~/companies/batch", data)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }


    /// Make a dummy request
    public async Task MakePostRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/companies/batch";

      string json = @"[
  {
    ""company_id"": ""string"",
    ""modified_time"": ""2024-04-11T04:01:35.090Z"",
    ""session_token"": ""string"",
    ""company_domain"": ""string"",
    ""metadata"": {}
  }
]";
      var content = JsonConvert.DeserializeObject(json);
      await PostAsync(content, url);


    }

    /// Performs a POST Request
    public async Task PostAsync(CompanyUpdate content, string url)
    {
        //Serialize Object
        StringContent jsonContent = SerializeObject(content);

        //Execute POST request
        HttpResponseMessage response = await Client.PostAsync(url, jsonContent);
    }



    /// Serialize an object to Json
    private StringContent SerializeObject(CompanyUpdate content)
    {
        //Serialize Object
        string jsonObject = JsonConvert.SerializeObject(content);

        //Create Json UTF8 String Content
        return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/companies/batch");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-Type",'application/json');
con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

// Enable sending a request body
con.setDoOutput(true);

String jsonPayload = """[
  {
    "company_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "session_token": "string",
    "company_domain": "string",
    "metadata": {}
  }
]""";

// Write payload to the request
try(OutputStream os = con.getOutputStream()) {
    byte[] input = jsonPayload.getBytes("utf-8");
    os.write(input, 0, input.length);           
}

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

POST /search/~/companies/batch

Update Companies in Batch

POST https://api.moesif.com/v1/search/~/companies/batch

Example Request

[
  {
    "company_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "session_token": "string",
    "company_domain": "string",
    "metadata": {}
  }
]

Parameters

Name In Type Required Description
body body CompanyUpdate true none

Example responses

Responses

Status Meaning Description Schema
200 OK success None

Response Schema

getCompany

Code samples

# You can also use wget
curl -X GET https://api.moesif.com/v1/search/~/companies/{id} \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'

const fetch = require('node-fetch');

const headers = {
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/companies/{id}',
{
  method: 'GET',

  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}

r = requests.get('https://api.moesif.com/v1/search/~/companies/{id}', headers = headers)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

result = RestClient.get 'https://api.moesif.com/v1/search/~/companies/{id}',
  params: {
  }, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('GET','https://api.moesif.com/v1/search/~/companies/{id}', array(
        'headers' => $headers,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }


    req, err := http.NewRequest("GET", "https://api.moesif.com/v1/search/~/companies/{id}")
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }

    /// Make a dummy request
    public async Task MakeGetRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/companies/{id}";
      var result = await GetAsync(url);
    }

    /// Performs a GET Request
    public async Task GetAsync(string url)
    {
        //Start the request
        HttpResponseMessage response = await Client.GetAsync(url);

        //Validate result
        response.EnsureSuccessStatusCode();

    }




    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/companies/{id}");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");

con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

GET /search/~/companies/{id}

Get a Company

GET https://api.moesif.com/v1/search/~/companies/{id}

Parameters

Name In Type Required Description
id path string true none

Example responses

Responses

Status Meaning Description Schema
200 OK success None

Response Schema

deleteCompany

Code samples

# You can also use wget
curl -X DELETE https://api.moesif.com/v1/search/~/companies/{id} \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'

const fetch = require('node-fetch');

const headers = {
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/companies/{id}',
{
  method: 'DELETE',

  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}

r = requests.delete('https://api.moesif.com/v1/search/~/companies/{id}', headers = headers)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

result = RestClient.delete 'https://api.moesif.com/v1/search/~/companies/{id}',
  params: {
  }, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('DELETE','https://api.moesif.com/v1/search/~/companies/{id}', array(
        'headers' => $headers,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }


    req, err := http.NewRequest("DELETE", "https://api.moesif.com/v1/search/~/companies/{id}")
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }




    /// Make a dummy request
    public async Task MakeDeleteRequest()
    {
      int id = 1;
      string url = "https://api.moesif.com/v1/search/~/companies/{id}";

      await DeleteAsync(id, url);
    }

    /// Performs a DELETE Request
    public async Task DeleteAsync(int id, string url)
    {
        //Execute DELETE request
        HttpResponseMessage response = await Client.DeleteAsync(url + $"/{id}");

        //Return response
        await DeserializeObject(response);
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/companies/{id}");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("DELETE");

con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

DELETE /search/~/companies/{id}

Delete a Company

DELETE https://api.moesif.com/v1/search/~/companies/{id}

Parameters

Name In Type Required Description
id path string true none
delete_events query boolean false Delete events associated with the company which can be set to true or false(default)

Responses

Status Meaning Description Schema
200 OK success None

countCompanies

Code samples

# You can also use wget
curl -X POST https://api.moesif.com/v1/search/~/count/companies?app_id=string \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'


const fetch = require('node-fetch');
const inputBody = false;
const headers = {
  'Content-Type':'application/json',
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/count/companies?app_id=string',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}
input_body = false

r = requests.post('https://api.moesif.com/v1/search/~/count/companies', params={
  'app_id': 'string'

}, headers = headers, json = input_body)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Content-Type' => 'application/json',
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

input_payload = JSON.parse('false')

result = RestClient.post 'https://api.moesif.com/v1/search/~/count/companies',
  params: {
  'app_id' => 'string'
  }, 
  payload: input_payload.to_json, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$inputPayload = json_decode('false')

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('POST','https://api.moesif.com/v1/search/~/count/companies', array(
        'headers' => $headers,
        'json' => $inputPayload,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Content-Type": []string{"application/json"},
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }
    jsonPayload := `false`
    data := bytes.NewBuffer([]byte(jsonPayload))
    req, err := http.NewRequest("POST", "https://api.moesif.com/v1/search/~/count/companies", data)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }


    /// Make a dummy request
    public async Task MakePostRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/count/companies";


      await PostAsync(null, url);

    }

    /// Performs a POST Request
    public async Task PostAsync(undefined content, string url)
    {
        //Serialize Object
        StringContent jsonContent = SerializeObject(content);

        //Execute POST request
        HttpResponseMessage response = await Client.PostAsync(url, jsonContent);
    }



    /// Serialize an object to Json
    private StringContent SerializeObject(undefined content)
    {
        //Serialize Object
        string jsonObject = JsonConvert.SerializeObject(content);

        //Create Json UTF8 String Content
        return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/count/companies?app_id=string");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-Type",'application/json');
con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

// Enable sending a request body
con.setDoOutput(true);

String jsonPayload = """false""";

// Write payload to the request
try(OutputStream os = con.getOutputStream()) {
    byte[] input = jsonPayload.getBytes("utf-8");
    os.write(input, 0, input.length);           
}

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

POST /search/~/count/companies

Count Companies

POST https://api.moesif.com/v1/search/~/count/companies

Example Request

false

Parameters

Name In Type Required Description

Example responses

Responses

Status Meaning Description Schema
200 OK success None

Response Schema

searchCompanyMetrics

Code samples

# You can also use wget
curl -X POST https://api.moesif.com/v1/search/~/search/companymetrics/companies \
  -H 'Content-Type: application/json' \
  -H 'Accept: 0' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'


const fetch = require('node-fetch');
const inputBody = false;
const headers = {
  'Content-Type':'application/json',
  'Accept':'0',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/search/companymetrics/companies',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Content-Type': 'application/json',
  'Accept': '0',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}
input_body = false

r = requests.post('https://api.moesif.com/v1/search/~/search/companymetrics/companies', headers = headers, json = input_body)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Content-Type' => 'application/json',
  'Accept' => '0',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

input_payload = JSON.parse('false')

result = RestClient.post 'https://api.moesif.com/v1/search/~/search/companymetrics/companies',
  params: {
  }, 
  payload: input_payload.to_json, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Content-Type' => 'application/json',
    'Accept' => '0',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$inputPayload = json_decode('false')

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('POST','https://api.moesif.com/v1/search/~/search/companymetrics/companies', array(
        'headers' => $headers,
        'json' => $inputPayload,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Content-Type": []string{"application/json"},
        "Accept": []string{"0"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }
    jsonPayload := `false`
    data := bytes.NewBuffer([]byte(jsonPayload))
    req, err := http.NewRequest("POST", "https://api.moesif.com/v1/search/~/search/companymetrics/companies", data)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }


    /// Make a dummy request
    public async Task MakePostRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/search/companymetrics/companies";


      await PostAsync(null, url);

    }

    /// Performs a POST Request
    public async Task PostAsync(undefined content, string url)
    {
        //Serialize Object
        StringContent jsonContent = SerializeObject(content);

        //Execute POST request
        HttpResponseMessage response = await Client.PostAsync(url, jsonContent);
    }



    /// Serialize an object to Json
    private StringContent SerializeObject(undefined content)
    {
        //Serialize Object
        string jsonObject = JsonConvert.SerializeObject(content);

        //Create Json UTF8 String Content
        return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/search/companymetrics/companies");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-Type",'application/json');
con.setRequestProperty("Accept",'0');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

// Enable sending a request body
con.setDoOutput(true);

String jsonPayload = """false""";

// Write payload to the request
try(OutputStream os = con.getOutputStream()) {
    byte[] input = jsonPayload.getBytes("utf-8");
    os.write(input, 0, input.length);           
}

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

POST /search/~/search/companymetrics/companies

Search CompanyMetrics/Companies

POST https://api.moesif.com/v1/search/~/search/companymetrics/companies

Example Request

false

Parameters

Name In Type Required Description
from query string(date-time) false The start date, which can be absolute such as 2023-07-01T00:00:00Z or relative such as -24h
to query string(date-time) false The end date, which can be absolute such as 2023-07-02T00:00:00Z or relative such as now

Example responses

Responses

Status Meaning Description Schema
200 OK success None

Response Schema

Subscriptions

getCompanySubscriptions

Code samples

# You can also use wget
curl -X GET https://api.moesif.com/v1/search/~/companies/{id}/subscriptions \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'

const fetch = require('node-fetch');

const headers = {
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/companies/{id}/subscriptions',
{
  method: 'GET',

  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}

r = requests.get('https://api.moesif.com/v1/search/~/companies/{id}/subscriptions', headers = headers)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

result = RestClient.get 'https://api.moesif.com/v1/search/~/companies/{id}/subscriptions',
  params: {
  }, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('GET','https://api.moesif.com/v1/search/~/companies/{id}/subscriptions', array(
        'headers' => $headers,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }


    req, err := http.NewRequest("GET", "https://api.moesif.com/v1/search/~/companies/{id}/subscriptions")
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }

    /// Make a dummy request
    public async Task MakeGetRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/companies/{id}/subscriptions";
      var result = await GetAsync(url);
    }

    /// Performs a GET Request
    public async Task GetAsync(string url)
    {
        //Start the request
        HttpResponseMessage response = await Client.GetAsync(url);

        //Validate result
        response.EnsureSuccessStatusCode();

    }




    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/companies/{id}/subscriptions");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");

con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

GET /search/~/companies/{id}/subscriptions

Get the Subscriptions of a Company

GET https://api.moesif.com/v1/search/~/companies/{id}/subscriptions

Parameters

Name In Type Required Description
id path string true none

Example responses

Responses

Status Meaning Description Schema
200 OK success None

Response Schema

createSubscription

Code samples

# You can also use wget
curl -X POST https://api.moesif.com/v1/search/~/subscriptions \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'

  -d '{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}' 
const fetch = require('node-fetch');
const inputBody = {
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
};
const headers = {
  'Content-Type':'application/json',
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/subscriptions',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}
input_body = {
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}

r = requests.post('https://api.moesif.com/v1/search/~/subscriptions', headers = headers, json = input_body)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Content-Type' => 'application/json',
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

input_payload = JSON.parse('{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}')

result = RestClient.post 'https://api.moesif.com/v1/search/~/subscriptions',
  params: {
  }, 
  payload: input_payload.to_json, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$inputPayload = json_decode('{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}')

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('POST','https://api.moesif.com/v1/search/~/subscriptions', array(
        'headers' => $headers,
        'json' => $inputPayload,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Content-Type": []string{"application/json"},
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }
    jsonPayload := `{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}`
    data := bytes.NewBuffer([]byte(jsonPayload))
    req, err := http.NewRequest("POST", "https://api.moesif.com/v1/search/~/subscriptions", data)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }


    /// Make a dummy request
    public async Task MakePostRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/subscriptions";

      string json = @"{
  ""trial_start"": ""2024-04-11T04:01:35.090Z"",
  ""company_id"": ""string"",
  ""start_date"": ""2024-04-11T04:01:35.090Z"",
  ""collection_method"": ""string"",
  ""provider"": ""string"",
  ""items"": [
    {
      ""item_price_id"": ""string"",
      ""price_id"": ""string"",
      ""is_metered"": true,
      ""plan_id"": ""string"",
      ""unit_of_measure"": ""string"",
      ""status"": ""string"",
      ""subscription_item_id"": ""string""
    }
  ],
  ""current_period_start"": ""2024-04-11T04:01:35.090Z"",
  ""company_external_id"": ""string"",
  ""payment_status"": ""string"",
  ""cancel_time"": ""2024-04-11T04:01:35.090Z"",
  ""status"": ""string"",
  ""trial_end"": ""2024-04-11T04:01:35.090Z"",
  ""external_id"": ""string"",
  ""metadata"": {},
  ""subscription_id"": ""string"",
  ""version_id"": ""string"",
  ""current_period_end"": ""2024-04-11T04:01:35.090Z"",
  ""created"": ""2024-04-11T04:01:35.090Z""
}";
      var content = JsonConvert.DeserializeObject(json);
      await PostAsync(content, url);


    }

    /// Performs a POST Request
    public async Task PostAsync(AddSubscription content, string url)
    {
        //Serialize Object
        StringContent jsonContent = SerializeObject(content);

        //Execute POST request
        HttpResponseMessage response = await Client.PostAsync(url, jsonContent);
    }



    /// Serialize an object to Json
    private StringContent SerializeObject(AddSubscription content)
    {
        //Serialize Object
        string jsonObject = JsonConvert.SerializeObject(content);

        //Create Json UTF8 String Content
        return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/subscriptions");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-Type",'application/json');
con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

// Enable sending a request body
con.setDoOutput(true);

String jsonPayload = """{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}""";

// Write payload to the request
try(OutputStream os = con.getOutputStream()) {
    byte[] input = jsonPayload.getBytes("utf-8");
    os.write(input, 0, input.length);           
}

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

POST /search/~/subscriptions

Create or Update a Subscription

POST https://api.moesif.com/v1/search/~/subscriptions

Example Request

{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}

Parameters

Name In Type Required Description
body body AddSubscription true none

Example responses

200 Response

{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "app_id": "string",
  "subscription_id": "string",
  "version_id": "string",
  "type": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "org_id": "string",
  "created": "2024-04-11T04:01:35.090Z"
}

Responses

Status Meaning Description Schema
200 OK success Subscription

batchCreateSubscriptions

Code samples

# You can also use wget
curl -X POST https://api.moesif.com/v1/search/~/subscriptions/batch \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'

  -d '{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}' 
const fetch = require('node-fetch');
const inputBody = {
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
};
const headers = {
  'Content-Type':'application/json',
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/subscriptions/batch',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}
input_body = {
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}

r = requests.post('https://api.moesif.com/v1/search/~/subscriptions/batch', headers = headers, json = input_body)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Content-Type' => 'application/json',
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

input_payload = JSON.parse('{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}')

result = RestClient.post 'https://api.moesif.com/v1/search/~/subscriptions/batch',
  params: {
  }, 
  payload: input_payload.to_json, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$inputPayload = json_decode('{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}')

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('POST','https://api.moesif.com/v1/search/~/subscriptions/batch', array(
        'headers' => $headers,
        'json' => $inputPayload,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Content-Type": []string{"application/json"},
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }
    jsonPayload := `{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}`
    data := bytes.NewBuffer([]byte(jsonPayload))
    req, err := http.NewRequest("POST", "https://api.moesif.com/v1/search/~/subscriptions/batch", data)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }


    /// Make a dummy request
    public async Task MakePostRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/subscriptions/batch";

      string json = @"{
  ""trial_start"": ""2024-04-11T04:01:35.090Z"",
  ""company_id"": ""string"",
  ""start_date"": ""2024-04-11T04:01:35.090Z"",
  ""collection_method"": ""string"",
  ""provider"": ""string"",
  ""items"": [
    {
      ""item_price_id"": ""string"",
      ""price_id"": ""string"",
      ""is_metered"": true,
      ""plan_id"": ""string"",
      ""unit_of_measure"": ""string"",
      ""status"": ""string"",
      ""subscription_item_id"": ""string""
    }
  ],
  ""current_period_start"": ""2024-04-11T04:01:35.090Z"",
  ""company_external_id"": ""string"",
  ""payment_status"": ""string"",
  ""cancel_time"": ""2024-04-11T04:01:35.090Z"",
  ""status"": ""string"",
  ""trial_end"": ""2024-04-11T04:01:35.090Z"",
  ""external_id"": ""string"",
  ""metadata"": {},
  ""subscription_id"": ""string"",
  ""version_id"": ""string"",
  ""current_period_end"": ""2024-04-11T04:01:35.090Z"",
  ""created"": ""2024-04-11T04:01:35.090Z""
}";
      var content = JsonConvert.DeserializeObject(json);
      await PostAsync(content, url);


    }

    /// Performs a POST Request
    public async Task PostAsync(AddSubscription content, string url)
    {
        //Serialize Object
        StringContent jsonContent = SerializeObject(content);

        //Execute POST request
        HttpResponseMessage response = await Client.PostAsync(url, jsonContent);
    }



    /// Serialize an object to Json
    private StringContent SerializeObject(AddSubscription content)
    {
        //Serialize Object
        string jsonObject = JsonConvert.SerializeObject(content);

        //Create Json UTF8 String Content
        return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/subscriptions/batch");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-Type",'application/json');
con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

// Enable sending a request body
con.setDoOutput(true);

String jsonPayload = """{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}""";

// Write payload to the request
try(OutputStream os = con.getOutputStream()) {
    byte[] input = jsonPayload.getBytes("utf-8");
    os.write(input, 0, input.length);           
}

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

POST /search/~/subscriptions/batch

Create or Update Subscriptions in Batch

POST https://api.moesif.com/v1/search/~/subscriptions/batch

Example Request

{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "subscription_id": "string",
  "version_id": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "created": "2024-04-11T04:01:35.090Z"
}

Parameters

Name In Type Required Description
body body AddSubscription true none

Example responses

200 Response

{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "app_id": "string",
  "subscription_id": "string",
  "version_id": "string",
  "type": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "org_id": "string",
  "created": "2024-04-11T04:01:35.090Z"
}

Responses

Status Meaning Description Schema
200 OK success Subscription

getSubscription

Code samples

# You can also use wget
curl -X GET https://api.moesif.com/v1/search/~/subscriptions/{id} \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'

const fetch = require('node-fetch');

const headers = {
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/subscriptions/{id}',
{
  method: 'GET',

  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}

r = requests.get('https://api.moesif.com/v1/search/~/subscriptions/{id}', headers = headers)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

result = RestClient.get 'https://api.moesif.com/v1/search/~/subscriptions/{id}',
  params: {
  }, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('GET','https://api.moesif.com/v1/search/~/subscriptions/{id}', array(
        'headers' => $headers,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }


    req, err := http.NewRequest("GET", "https://api.moesif.com/v1/search/~/subscriptions/{id}")
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }

    /// Make a dummy request
    public async Task MakeGetRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/subscriptions/{id}";
      var result = await GetAsync(url);
    }

    /// Performs a GET Request
    public async Task GetAsync(string url)
    {
        //Start the request
        HttpResponseMessage response = await Client.GetAsync(url);

        //Validate result
        response.EnsureSuccessStatusCode();

    }




    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/subscriptions/{id}");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");

con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

GET /search/~/subscriptions/{id}

Get a Subscription

GET https://api.moesif.com/v1/search/~/subscriptions/{id}

Parameters

Name In Type Required Description
id path string true none

Example responses

200 Response

{
  "trial_start": "2024-04-11T04:01:35.090Z",
  "company_id": "string",
  "start_date": "2024-04-11T04:01:35.090Z",
  "collection_method": "string",
  "provider": "string",
  "items": [
    {
      "item_price_id": "string",
      "price_id": "string",
      "is_metered": true,
      "plan_id": "string",
      "unit_of_measure": "string",
      "status": "string",
      "subscription_item_id": "string"
    }
  ],
  "current_period_start": "2024-04-11T04:01:35.090Z",
  "company_external_id": "string",
  "payment_status": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "cancel_time": "2024-04-11T04:01:35.090Z",
  "status": "string",
  "trial_end": "2024-04-11T04:01:35.090Z",
  "external_id": "string",
  "metadata": {},
  "app_id": "string",
  "subscription_id": "string",
  "version_id": "string",
  "type": "string",
  "current_period_end": "2024-04-11T04:01:35.090Z",
  "org_id": "string",
  "created": "2024-04-11T04:01:35.090Z"
}

Responses

Status Meaning Description Schema
200 OK success Subscription

Metrics

countEvents

Code samples

# You can also use wget
curl -X POST https://api.moesif.com/v1/search/~/count/events?from=2019-08-24T14%3A15%3A22Z&to=2019-08-24T14%3A15%3A22Z \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'


const fetch = require('node-fetch');
const inputBody = false;
const headers = {
  'Content-Type':'application/json',
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/count/events?from=2019-08-24T14%3A15%3A22Z&to=2019-08-24T14%3A15%3A22Z',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}
input_body = false

r = requests.post('https://api.moesif.com/v1/search/~/count/events', params={
  'from': '2024-04-11T04:01:35.090Z',  'to': '2024-04-11T04:01:35.090Z'

}, headers = headers, json = input_body)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Content-Type' => 'application/json',
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

input_payload = JSON.parse('false')

result = RestClient.post 'https://api.moesif.com/v1/search/~/count/events',
  params: {
  'from' => 'string(date-time)',
  'to' => 'string(date-time)'
  }, 
  payload: input_payload.to_json, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$inputPayload = json_decode('false')

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('POST','https://api.moesif.com/v1/search/~/count/events', array(
        'headers' => $headers,
        'json' => $inputPayload,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Content-Type": []string{"application/json"},
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }
    jsonPayload := `false`
    data := bytes.NewBuffer([]byte(jsonPayload))
    req, err := http.NewRequest("POST", "https://api.moesif.com/v1/search/~/count/events", data)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }


    /// Make a dummy request
    public async Task MakePostRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/count/events";


      await PostAsync(null, url);

    }

    /// Performs a POST Request
    public async Task PostAsync(undefined content, string url)
    {
        //Serialize Object
        StringContent jsonContent = SerializeObject(content);

        //Execute POST request
        HttpResponseMessage response = await Client.PostAsync(url, jsonContent);
    }



    /// Serialize an object to Json
    private StringContent SerializeObject(undefined content)
    {
        //Serialize Object
        string jsonObject = JsonConvert.SerializeObject(content);

        //Create Json UTF8 String Content
        return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/count/events?from=2019-08-24T14%3A15%3A22Z&to=2019-08-24T14%3A15%3A22Z");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-Type",'application/json');
con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

// Enable sending a request body
con.setDoOutput(true);

String jsonPayload = """false""";

// Write payload to the request
try(OutputStream os = con.getOutputStream()) {
    byte[] input = jsonPayload.getBytes("utf-8");
    os.write(input, 0, input.length);           
}

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

POST /search/~/count/events

Count Events

POST https://api.moesif.com/v1/search/~/count/events

Example Request

false

Parameters

Name In Type Required Description
from query string(date-time) true The start date, which can be absolute such as 2019-07-01T00:00:00Z or relative such as -24h
to query string(date-time) true The end date, which can be absolute such as 2019-07-02T00:00:00Z or relative such as now
track_total_hits query boolean false none

Example responses

Responses

Status Meaning Description Schema
200 OK success None

Response Schema

getEvent

Code samples

# You can also use wget
curl -X GET https://api.moesif.com/v1/search/~/events/{id}?event_time=2019-08-24T14%3A15%3A22Z \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'

const fetch = require('node-fetch');

const headers = {
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/events/{id}?event_time=2019-08-24T14%3A15%3A22Z',
{
  method: 'GET',

  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}

r = requests.get('https://api.moesif.com/v1/search/~/events/{id}', params={
  'event_time': '2024-04-11T04:01:35.090Z'

}, headers = headers)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

result = RestClient.get 'https://api.moesif.com/v1/search/~/events/{id}',
  params: {
  'event_time' => 'string(date-time)'
  }, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('GET','https://api.moesif.com/v1/search/~/events/{id}', array(
        'headers' => $headers,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }


    req, err := http.NewRequest("GET", "https://api.moesif.com/v1/search/~/events/{id}")
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }

    /// Make a dummy request
    public async Task MakeGetRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/events/{id}";
      var result = await GetAsync(url);
    }

    /// Performs a GET Request
    public async Task GetAsync(string url)
    {
        //Start the request
        HttpResponseMessage response = await Client.GetAsync(url);

        //Validate result
        response.EnsureSuccessStatusCode();

    }




    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/events/{id}?event_time=2019-08-24T14%3A15%3A22Z");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");

con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

GET /search/~/events/{id}

Get an Event

GET https://api.moesif.com/v1/search/~/events/{id}

Parameters

Name In Type Required Description
id path string true none
event_time query string(date-time) true none

Example responses

200 Response

{
  "_id": "AWF5M-FDTqLFD8l5y2f4",
  "_source": {
    "company_id": "67890",
    "duration_ms": 76,
    "request": {
      "body": "json",
      "uri": "https://api.github.com",
      "user_agent": {
        "patch": "1",
        "major": "7",
        "minor": "1",
        "name": "PostmanRuntime"
      },
      "geo_ip": {
        "ip": "73.189.235.253",
        "region_name": "CA",
        "continent_code": "NA",
        "location": [
          "["
        ],
        "latitude": 37.769,
        "timezone": "America/Los_Angeles",
        "area_code": 415,
        "longitude": -122.393,
        "real_region_name": "California",
        "dma_code": 807,
        "postal_code": "94107",
        "city_name": "San Francisco",
        "country_code2": "US",
        "country_code3": "USA",
        "country_name": "United States"
      },
      "ip_address": "73.189.235.253",
      "verb": "GET",
      "route": "/",
      "time": "2023-07-09T06:14:58.550",
      "headers": {}
    },
    "user_id": "123454",
    "company": {},
    "response": {
      "body": {},
      "transfer_encoding": "json",
      "status": 200,
      "time": "2023-07-09T06:14:58.626",
      "headers": {}
    },
    "id": "AWF5M-FDTqLFD8l5y2f4",
    "event_type": "api_call",
    "session_token": "rdfmnw3fu24309efjc534nb421UZ9-]2JDO[ME",
    "metadata": {},
    "app_id": "198:3",
    "org_id": "177:3",
    "user": {}
  },
  "sort": [
    0
  ]
}

Responses

Status Meaning Description Schema
200 OK success eventResponse

searchEvents

Code samples

# You can also use wget
curl -X POST https://api.moesif.com/v1/search/~/search/events?from=2019-08-24T14%3A15%3A22Z&to=2019-08-24T14%3A15%3A22Z \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'


const fetch = require('node-fetch');
const inputBody = false;
const headers = {
  'Content-Type':'application/json',
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/search/events?from=2019-08-24T14%3A15%3A22Z&to=2019-08-24T14%3A15%3A22Z',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}
input_body = false

r = requests.post('https://api.moesif.com/v1/search/~/search/events', params={
  'from': '2024-04-11T04:01:35.090Z',  'to': '2024-04-11T04:01:35.090Z'

}, headers = headers, json = input_body)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Content-Type' => 'application/json',
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

input_payload = JSON.parse('false')

result = RestClient.post 'https://api.moesif.com/v1/search/~/search/events',
  params: {
  'from' => 'string(date-time)',
  'to' => 'string(date-time)'
  }, 
  payload: input_payload.to_json, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$inputPayload = json_decode('false')

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('POST','https://api.moesif.com/v1/search/~/search/events', array(
        'headers' => $headers,
        'json' => $inputPayload,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Content-Type": []string{"application/json"},
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }
    jsonPayload := `false`
    data := bytes.NewBuffer([]byte(jsonPayload))
    req, err := http.NewRequest("POST", "https://api.moesif.com/v1/search/~/search/events", data)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }


    /// Make a dummy request
    public async Task MakePostRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/search/events";


      await PostAsync(null, url);

    }

    /// Performs a POST Request
    public async Task PostAsync(undefined content, string url)
    {
        //Serialize Object
        StringContent jsonContent = SerializeObject(content);

        //Execute POST request
        HttpResponseMessage response = await Client.PostAsync(url, jsonContent);
    }



    /// Serialize an object to Json
    private StringContent SerializeObject(undefined content)
    {
        //Serialize Object
        string jsonObject = JsonConvert.SerializeObject(content);

        //Create Json UTF8 String Content
        return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/search/events?from=2019-08-24T14%3A15%3A22Z&to=2019-08-24T14%3A15%3A22Z");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-Type",'application/json');
con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

// Enable sending a request body
con.setDoOutput(true);

String jsonPayload = """false""";

// Write payload to the request
try(OutputStream os = con.getOutputStream()) {
    byte[] input = jsonPayload.getBytes("utf-8");
    os.write(input, 0, input.length);           
}

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

POST /search/~/search/events

Search Events

POST https://api.moesif.com/v1/search/~/search/events

Example Request

false

Parameters

Name In Type Required Description
from query string(date-time) true The start date, which can be absolute such as 2023-07-01T00:00:00Z or relative such as -24h
to query string(date-time) true The end date, which can be absolute such as 2023-07-02T00:00:00Z or relative such as now

Example responses

201 Response

{
  "took": 358,
  "timed_out": false,
  "hits": {
    "total": 947,
    "hits": [
      {
        "_id": "AWF5M-FDTqLFD8l5y2f4",
        "_source": {
          "company_id": "[",
          "duration_ms": "[",
          "request": {},
          "user_id": "[",
          "company": {},
          "response": {},
          "id": "[",
          "event_type": "[",
          "session_token": "[",
          "metadata": {},
          "app_id": "[",
          "org_id": "[",
          "user": {}
        },
        "sort": [
          0
        ]
      }
    ]
  }
}

Responses

Status Meaning Description Schema
201 Created success searchEventsResponse

searchPublicWorkspaces

Code samples

# You can also use wget
curl -X POST https://api.moesif.com/v1/search/~/workspaces/{workspaceId}/search?from=2019-08-24T14%3A15%3A22Z&to=2019-08-24T14%3A15%3A22Z \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'


const fetch = require('node-fetch');
const inputBody = false;
const headers = {
  'Content-Type':'application/json',
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/workspaces/{workspaceId}/search?from=2019-08-24T14%3A15%3A22Z&to=2019-08-24T14%3A15%3A22Z',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}
input_body = false

r = requests.post('https://api.moesif.com/v1/search/~/workspaces/{workspaceId}/search', params={
  'from': '2024-04-11T04:01:35.090Z',  'to': '2024-04-11T04:01:35.090Z'

}, headers = headers, json = input_body)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Content-Type' => 'application/json',
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

input_payload = JSON.parse('false')

result = RestClient.post 'https://api.moesif.com/v1/search/~/workspaces/{workspaceId}/search',
  params: {
  'from' => 'string(date-time)',
  'to' => 'string(date-time)'
  }, 
  payload: input_payload.to_json, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$inputPayload = json_decode('false')

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('POST','https://api.moesif.com/v1/search/~/workspaces/{workspaceId}/search', array(
        'headers' => $headers,
        'json' => $inputPayload,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Content-Type": []string{"application/json"},
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }
    jsonPayload := `false`
    data := bytes.NewBuffer([]byte(jsonPayload))
    req, err := http.NewRequest("POST", "https://api.moesif.com/v1/search/~/workspaces/{workspaceId}/search", data)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }


    /// Make a dummy request
    public async Task MakePostRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/workspaces/{workspaceId}/search";


      await PostAsync(null, url);

    }

    /// Performs a POST Request
    public async Task PostAsync(undefined content, string url)
    {
        //Serialize Object
        StringContent jsonContent = SerializeObject(content);

        //Execute POST request
        HttpResponseMessage response = await Client.PostAsync(url, jsonContent);
    }



    /// Serialize an object to Json
    private StringContent SerializeObject(undefined content)
    {
        //Serialize Object
        string jsonObject = JsonConvert.SerializeObject(content);

        //Create Json UTF8 String Content
        return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/workspaces/{workspaceId}/search?from=2019-08-24T14%3A15%3A22Z&to=2019-08-24T14%3A15%3A22Z");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-Type",'application/json');
con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

// Enable sending a request body
con.setDoOutput(true);

String jsonPayload = """false""";

// Write payload to the request
try(OutputStream os = con.getOutputStream()) {
    byte[] input = jsonPayload.getBytes("utf-8");
    os.write(input, 0, input.length);           
}

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

POST /search/~/workspaces/{workspaceId}/search

Search Events in saved public Workspace

POST https://api.moesif.com/v1/search/~/workspaces/{workspaceId}/search

Example Request

false

Parameters

Name In Type Required Description
from query string(date-time) true The start date, which can be absolute such as 2023-07-01T00:00:00Z or relative such as -24h
to query string(date-time) true The end date, which can be absolute such as 2023-07-02T00:00:00Z or relative such as now
workspaceId path string true none
include_details query boolean false none
take query integer(int32) false none

Example responses

201 Response

{
  "took": 358,
  "timed_out": false,
  "hits": {
    "total": 947,
    "hits": [
      {
        "_id": "AWF5M-FDTqLFD8l5y2f4",
        "_source": {
          "company_id": "[",
          "duration_ms": "[",
          "request": {},
          "user_id": "[",
          "company": {},
          "response": {},
          "id": "[",
          "event_type": "[",
          "session_token": "[",
          "metadata": {},
          "app_id": "[",
          "org_id": "[",
          "user": {}
        },
        "sort": [
          0
        ]
      }
    ]
  }
}

Responses

Status Meaning Description Schema
201 Created success searchEventsResponse

Users

countUsers

Code samples

# You can also use wget
curl -X POST https://api.moesif.com/v1/search/~/count/users?app_id=string \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'


const fetch = require('node-fetch');
const inputBody = false;
const headers = {
  'Content-Type':'application/json',
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/count/users?app_id=string',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}
input_body = false

r = requests.post('https://api.moesif.com/v1/search/~/count/users', params={
  'app_id': 'string'

}, headers = headers, json = input_body)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Content-Type' => 'application/json',
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

input_payload = JSON.parse('false')

result = RestClient.post 'https://api.moesif.com/v1/search/~/count/users',
  params: {
  'app_id' => 'string'
  }, 
  payload: input_payload.to_json, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$inputPayload = json_decode('false')

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('POST','https://api.moesif.com/v1/search/~/count/users', array(
        'headers' => $headers,
        'json' => $inputPayload,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Content-Type": []string{"application/json"},
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }
    jsonPayload := `false`
    data := bytes.NewBuffer([]byte(jsonPayload))
    req, err := http.NewRequest("POST", "https://api.moesif.com/v1/search/~/count/users", data)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }


    /// Make a dummy request
    public async Task MakePostRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/count/users";


      await PostAsync(null, url);

    }

    /// Performs a POST Request
    public async Task PostAsync(undefined content, string url)
    {
        //Serialize Object
        StringContent jsonContent = SerializeObject(content);

        //Execute POST request
        HttpResponseMessage response = await Client.PostAsync(url, jsonContent);
    }



    /// Serialize an object to Json
    private StringContent SerializeObject(undefined content)
    {
        //Serialize Object
        string jsonObject = JsonConvert.SerializeObject(content);

        //Create Json UTF8 String Content
        return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/count/users?app_id=string");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-Type",'application/json');
con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

// Enable sending a request body
con.setDoOutput(true);

String jsonPayload = """false""";

// Write payload to the request
try(OutputStream os = con.getOutputStream()) {
    byte[] input = jsonPayload.getBytes("utf-8");
    os.write(input, 0, input.length);           
}

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

POST /search/~/count/users

Count Users

POST https://api.moesif.com/v1/search/~/count/users

Example Request

false

Parameters

Name In Type Required Description

Example responses

Responses

Status Meaning Description Schema
200 OK success None

Response Schema

searchUserMetrics

Code samples

# You can also use wget
curl -X POST https://api.moesif.com/v1/search/~/search/usermetrics/users \
  -H 'Content-Type: application/json' \
  -H 'Accept: 0' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'


const fetch = require('node-fetch');
const inputBody = false;
const headers = {
  'Content-Type':'application/json',
  'Accept':'0',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/search/usermetrics/users',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Content-Type': 'application/json',
  'Accept': '0',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}
input_body = false

r = requests.post('https://api.moesif.com/v1/search/~/search/usermetrics/users', headers = headers, json = input_body)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Content-Type' => 'application/json',
  'Accept' => '0',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

input_payload = JSON.parse('false')

result = RestClient.post 'https://api.moesif.com/v1/search/~/search/usermetrics/users',
  params: {
  }, 
  payload: input_payload.to_json, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Content-Type' => 'application/json',
    'Accept' => '0',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$inputPayload = json_decode('false')

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('POST','https://api.moesif.com/v1/search/~/search/usermetrics/users', array(
        'headers' => $headers,
        'json' => $inputPayload,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Content-Type": []string{"application/json"},
        "Accept": []string{"0"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }
    jsonPayload := `false`
    data := bytes.NewBuffer([]byte(jsonPayload))
    req, err := http.NewRequest("POST", "https://api.moesif.com/v1/search/~/search/usermetrics/users", data)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }


    /// Make a dummy request
    public async Task MakePostRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/search/usermetrics/users";


      await PostAsync(null, url);

    }

    /// Performs a POST Request
    public async Task PostAsync(undefined content, string url)
    {
        //Serialize Object
        StringContent jsonContent = SerializeObject(content);

        //Execute POST request
        HttpResponseMessage response = await Client.PostAsync(url, jsonContent);
    }



    /// Serialize an object to Json
    private StringContent SerializeObject(undefined content)
    {
        //Serialize Object
        string jsonObject = JsonConvert.SerializeObject(content);

        //Create Json UTF8 String Content
        return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/search/usermetrics/users");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-Type",'application/json');
con.setRequestProperty("Accept",'0');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

// Enable sending a request body
con.setDoOutput(true);

String jsonPayload = """false""";

// Write payload to the request
try(OutputStream os = con.getOutputStream()) {
    byte[] input = jsonPayload.getBytes("utf-8");
    os.write(input, 0, input.length);           
}

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

POST /search/~/search/usermetrics/users

Search UserMetrics/Users

POST https://api.moesif.com/v1/search/~/search/usermetrics/users

Example Request

false

Parameters

Name In Type Required Description
from query string(date-time) false The start date, which can be absolute such as 2023-07-01T00:00:00Z or relative such as -24h
to query string(date-time) false The end date, which can be absolute such as 2023-07-02T00:00:00Z or relative such as now

Example responses

Responses

Status Meaning Description Schema
200 OK success None

Response Schema

updateUsers

Code samples

# You can also use wget
curl -X POST https://api.moesif.com/v1/search/~/users \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'

  -d '{
  "company_id": "string",
  "first_name": "string",
  "name": "string",
  "email": "string",
  "photo_url": "string",
  "user_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "last_name": "string",
  "metadata": {},
  "user_name": "string",
  "phone": "string"
}' 
const fetch = require('node-fetch');
const inputBody = {
  "company_id": "string",
  "first_name": "string",
  "name": "string",
  "email": "string",
  "photo_url": "string",
  "user_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "last_name": "string",
  "metadata": {},
  "user_name": "string",
  "phone": "string"
};
const headers = {
  'Content-Type':'application/json',
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/users',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}
input_body = {
  "company_id": "string",
  "first_name": "string",
  "name": "string",
  "email": "string",
  "photo_url": "string",
  "user_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "last_name": "string",
  "metadata": {},
  "user_name": "string",
  "phone": "string"
}

r = requests.post('https://api.moesif.com/v1/search/~/users', headers = headers, json = input_body)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Content-Type' => 'application/json',
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

input_payload = JSON.parse('{
  "company_id": "string",
  "first_name": "string",
  "name": "string",
  "email": "string",
  "photo_url": "string",
  "user_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "last_name": "string",
  "metadata": {},
  "user_name": "string",
  "phone": "string"
}')

result = RestClient.post 'https://api.moesif.com/v1/search/~/users',
  params: {
  }, 
  payload: input_payload.to_json, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$inputPayload = json_decode('{
  "company_id": "string",
  "first_name": "string",
  "name": "string",
  "email": "string",
  "photo_url": "string",
  "user_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "last_name": "string",
  "metadata": {},
  "user_name": "string",
  "phone": "string"
}')

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('POST','https://api.moesif.com/v1/search/~/users', array(
        'headers' => $headers,
        'json' => $inputPayload,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Content-Type": []string{"application/json"},
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }
    jsonPayload := `{
  "company_id": "string",
  "first_name": "string",
  "name": "string",
  "email": "string",
  "photo_url": "string",
  "user_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "last_name": "string",
  "metadata": {},
  "user_name": "string",
  "phone": "string"
}`
    data := bytes.NewBuffer([]byte(jsonPayload))
    req, err := http.NewRequest("POST", "https://api.moesif.com/v1/search/~/users", data)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }


    /// Make a dummy request
    public async Task MakePostRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/users";

      string json = @"{
  ""company_id"": ""string"",
  ""first_name"": ""string"",
  ""name"": ""string"",
  ""email"": ""string"",
  ""photo_url"": ""string"",
  ""user_id"": ""string"",
  ""modified_time"": ""2024-04-11T04:01:35.090Z"",
  ""last_name"": ""string"",
  ""metadata"": {},
  ""user_name"": ""string"",
  ""phone"": ""string""
}";
      var content = JsonConvert.DeserializeObject(json);
      await PostAsync(content, url);


    }

    /// Performs a POST Request
    public async Task PostAsync(UserUpdate content, string url)
    {
        //Serialize Object
        StringContent jsonContent = SerializeObject(content);

        //Execute POST request
        HttpResponseMessage response = await Client.PostAsync(url, jsonContent);
    }



    /// Serialize an object to Json
    private StringContent SerializeObject(UserUpdate content)
    {
        //Serialize Object
        string jsonObject = JsonConvert.SerializeObject(content);

        //Create Json UTF8 String Content
        return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/users");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-Type",'application/json');
con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

// Enable sending a request body
con.setDoOutput(true);

String jsonPayload = """{
  "company_id": "string",
  "first_name": "string",
  "name": "string",
  "email": "string",
  "photo_url": "string",
  "user_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "last_name": "string",
  "metadata": {},
  "user_name": "string",
  "phone": "string"
}""";

// Write payload to the request
try(OutputStream os = con.getOutputStream()) {
    byte[] input = jsonPayload.getBytes("utf-8");
    os.write(input, 0, input.length);           
}

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

POST /search/~/users

Update a User

POST https://api.moesif.com/v1/search/~/users

Example Request

{
  "company_id": "string",
  "first_name": "string",
  "name": "string",
  "email": "string",
  "photo_url": "string",
  "user_id": "string",
  "modified_time": "2024-04-11T04:01:35.090Z",
  "last_name": "string",
  "metadata": {},
  "user_name": "string",
  "phone": "string"
}

Parameters

Name In Type Required Description
body body UserUpdate true none

Example responses

200 Response

{
  "_id": "123456",
  "_source": {
    "first_name": "John",
    "body": {},
    "name": "John Doe",
    "email": "john.doe@gmail.com",
    "first_seen_time": "2023-07-27T21:52:58.0990000Z",
    "user_agent": {
      "name": "Android",
      "os_major": "7",
      "os": "Android 7.0",
      "os_name": "Android",
      "os_minor": "0",
      "major": "7",
      "device": "Samsung SM-G955U",
      "minor": "0"
    },
    "geo_ip": {
      "ip": "107.200.85.196",
      "region_name": "South Carolina",
      "continent_code": "NA",
      "location": {
        "lon": -79.85489654541016,
        "lat": 32.822898864746094
      },
      "latitude": 32.822898864746094,
      "timezone": "America/New_York",
      "longitude": -79.85489654541016,
      "dma_code": 519,
      "postal_code": "29464",
      "region_code": "SC",
      "city_name": "Mt. Pleasant",
      "country_code2": "US",
      "country_code3": "US",
      "country_name": "United States"
    },
    "modified_time": "2023-07-27T21:55:19.464",
    "last_name": "Doe",
    "ip_address": "107.200.85.196",
    "session_token": [
      "e93u2jiry8fij8q09-tfZ9SIK9DERDXUYMF"
    ],
    "last_seen_time": "2023-07-27T21:52:58.0990000Z",
    "app_id": "198:3",
    "org_id": "177:3"
  },
  "sort": [
    1519768519464
  ]
}

Responses

Status Meaning Description Schema
200 OK success userResponse

batchUpdateUsers

Code samples

# You can also use wget
curl -X POST https://api.moesif.com/v1/search/~/users/batch \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'

  -d '[
  {
    "company_id": "string",
    "first_name": "string",
    "name": "string",
    "email": "string",
    "photo_url": "string",
    "user_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "last_name": "string",
    "metadata": {},
    "user_name": "string",
    "phone": "string"
  }
]' 
const fetch = require('node-fetch');
const inputBody = [
  {
    "company_id": "string",
    "first_name": "string",
    "name": "string",
    "email": "string",
    "photo_url": "string",
    "user_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "last_name": "string",
    "metadata": {},
    "user_name": "string",
    "phone": "string"
  }
];
const headers = {
  'Content-Type':'application/json',
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/users/batch',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}
input_body = [
  {
    "company_id": "string",
    "first_name": "string",
    "name": "string",
    "email": "string",
    "photo_url": "string",
    "user_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "last_name": "string",
    "metadata": {},
    "user_name": "string",
    "phone": "string"
  }
]

r = requests.post('https://api.moesif.com/v1/search/~/users/batch', headers = headers, json = input_body)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Content-Type' => 'application/json',
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

input_payload = JSON.parse('[
  {
    "company_id": "string",
    "first_name": "string",
    "name": "string",
    "email": "string",
    "photo_url": "string",
    "user_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "last_name": "string",
    "metadata": {},
    "user_name": "string",
    "phone": "string"
  }
]')

result = RestClient.post 'https://api.moesif.com/v1/search/~/users/batch',
  params: {
  }, 
  payload: input_payload.to_json, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$inputPayload = json_decode('[
  {
    "company_id": "string",
    "first_name": "string",
    "name": "string",
    "email": "string",
    "photo_url": "string",
    "user_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "last_name": "string",
    "metadata": {},
    "user_name": "string",
    "phone": "string"
  }
]')

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('POST','https://api.moesif.com/v1/search/~/users/batch', array(
        'headers' => $headers,
        'json' => $inputPayload,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Content-Type": []string{"application/json"},
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }
    jsonPayload := `[
  {
    "company_id": "string",
    "first_name": "string",
    "name": "string",
    "email": "string",
    "photo_url": "string",
    "user_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "last_name": "string",
    "metadata": {},
    "user_name": "string",
    "phone": "string"
  }
]`
    data := bytes.NewBuffer([]byte(jsonPayload))
    req, err := http.NewRequest("POST", "https://api.moesif.com/v1/search/~/users/batch", data)
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }


    /// Make a dummy request
    public async Task MakePostRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/users/batch";

      string json = @"[
  {
    ""company_id"": ""string"",
    ""first_name"": ""string"",
    ""name"": ""string"",
    ""email"": ""string"",
    ""photo_url"": ""string"",
    ""user_id"": ""string"",
    ""modified_time"": ""2024-04-11T04:01:35.090Z"",
    ""last_name"": ""string"",
    ""metadata"": {},
    ""user_name"": ""string"",
    ""phone"": ""string""
  }
]";
      var content = JsonConvert.DeserializeObject(json);
      await PostAsync(content, url);


    }

    /// Performs a POST Request
    public async Task PostAsync(UserUpdate content, string url)
    {
        //Serialize Object
        StringContent jsonContent = SerializeObject(content);

        //Execute POST request
        HttpResponseMessage response = await Client.PostAsync(url, jsonContent);
    }



    /// Serialize an object to Json
    private StringContent SerializeObject(UserUpdate content)
    {
        //Serialize Object
        string jsonObject = JsonConvert.SerializeObject(content);

        //Create Json UTF8 String Content
        return new StringContent(jsonObject, Encoding.UTF8, "application/json");
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/users/batch");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");

con.setRequestProperty("Content-Type",'application/json');
con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

// Enable sending a request body
con.setDoOutput(true);

String jsonPayload = """[
  {
    "company_id": "string",
    "first_name": "string",
    "name": "string",
    "email": "string",
    "photo_url": "string",
    "user_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "last_name": "string",
    "metadata": {},
    "user_name": "string",
    "phone": "string"
  }
]""";

// Write payload to the request
try(OutputStream os = con.getOutputStream()) {
    byte[] input = jsonPayload.getBytes("utf-8");
    os.write(input, 0, input.length);           
}

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

POST /search/~/users/batch

Update Users in Batch

POST https://api.moesif.com/v1/search/~/users/batch

Example Request

[
  {
    "company_id": "string",
    "first_name": "string",
    "name": "string",
    "email": "string",
    "photo_url": "string",
    "user_id": "string",
    "modified_time": "2024-04-11T04:01:35.090Z",
    "last_name": "string",
    "metadata": {},
    "user_name": "string",
    "phone": "string"
  }
]

Parameters

Name In Type Required Description
body body UserUpdate true none

Example responses

200 Response

{
  "_id": "123456",
  "_source": {
    "first_name": "John",
    "body": {},
    "name": "John Doe",
    "email": "john.doe@gmail.com",
    "first_seen_time": "2023-07-27T21:52:58.0990000Z",
    "user_agent": {
      "name": "Android",
      "os_major": "7",
      "os": "Android 7.0",
      "os_name": "Android",
      "os_minor": "0",
      "major": "7",
      "device": "Samsung SM-G955U",
      "minor": "0"
    },
    "geo_ip": {
      "ip": "107.200.85.196",
      "region_name": "South Carolina",
      "continent_code": "NA",
      "location": {
        "lon": -79.85489654541016,
        "lat": 32.822898864746094
      },
      "latitude": 32.822898864746094,
      "timezone": "America/New_York",
      "longitude": -79.85489654541016,
      "dma_code": 519,
      "postal_code": "29464",
      "region_code": "SC",
      "city_name": "Mt. Pleasant",
      "country_code2": "US",
      "country_code3": "US",
      "country_name": "United States"
    },
    "modified_time": "2023-07-27T21:55:19.464",
    "last_name": "Doe",
    "ip_address": "107.200.85.196",
    "session_token": [
      "e93u2jiry8fij8q09-tfZ9SIK9DERDXUYMF"
    ],
    "last_seen_time": "2023-07-27T21:52:58.0990000Z",
    "app_id": "198:3",
    "org_id": "177:3"
  },
  "sort": [
    1519768519464
  ]
}

Responses

Status Meaning Description Schema
200 OK success userResponse

getUser

Code samples

# You can also use wget
curl -X GET https://api.moesif.com/v1/search/~/users/{id} \
  -H 'Accept: application/json' \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'

const fetch = require('node-fetch');

const headers = {
  'Accept':'application/json',
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/users/{id}',
{
  method: 'GET',

  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Accept': 'application/json',
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}

r = requests.get('https://api.moesif.com/v1/search/~/users/{id}', headers = headers)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Accept' => 'application/json',
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

result = RestClient.get 'https://api.moesif.com/v1/search/~/users/{id}',
  params: {
  }, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Accept' => 'application/json',
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('GET','https://api.moesif.com/v1/search/~/users/{id}', array(
        'headers' => $headers,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Accept": []string{"application/json"},
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }


    req, err := http.NewRequest("GET", "https://api.moesif.com/v1/search/~/users/{id}")
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }

    /// Make a dummy request
    public async Task MakeGetRequest()
    {
      string url = "https://api.moesif.com/v1/search/~/users/{id}";
      var result = await GetAsync(url);
    }

    /// Performs a GET Request
    public async Task GetAsync(string url)
    {
        //Start the request
        HttpResponseMessage response = await Client.GetAsync(url);

        //Validate result
        response.EnsureSuccessStatusCode();

    }




    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj = new URL("https://api.moesif.com/v1/search/~/users/{id}");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");

con.setRequestProperty("Accept",'application/json');
con.setRequestProperty("Authorization",'Bearer YOUR_MANAGEMENT_API_KEY');

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println(response.toString());

GET /search/~/users/{id}

Get a User

GET https://api.moesif.com/v1/search/~/users/{id}

Parameters

Name In Type Required Description
id path string true none

Example responses

200 Response

{
  "_id": "123456",
  "_source": {
    "first_name": "John",
    "body": {},
    "name": "John Doe",
    "email": "john.doe@gmail.com",
    "first_seen_time": "2023-07-27T21:52:58.0990000Z",
    "user_agent": {
      "name": "Android",
      "os_major": "7",
      "os": "Android 7.0",
      "os_name": "Android",
      "os_minor": "0",
      "major": "7",
      "device": "Samsung SM-G955U",
      "minor": "0"
    },
    "geo_ip": {
      "ip": "107.200.85.196",
      "region_name": "South Carolina",
      "continent_code": "NA",
      "location": {
        "lon": -79.85489654541016,
        "lat": 32.822898864746094
      },
      "latitude": 32.822898864746094,
      "timezone": "America/New_York",
      "longitude": -79.85489654541016,
      "dma_code": 519,
      "postal_code": "29464",
      "region_code": "SC",
      "city_name": "Mt. Pleasant",
      "country_code2": "US",
      "country_code3": "US",
      "country_name": "United States"
    },
    "modified_time": "2023-07-27T21:55:19.464",
    "last_name": "Doe",
    "ip_address": "107.200.85.196",
    "session_token": [
      "e93u2jiry8fij8q09-tfZ9SIK9DERDXUYMF"
    ],
    "last_seen_time": "2023-07-27T21:52:58.0990000Z",
    "app_id": "198:3",
    "org_id": "177:3"
  },
  "sort": [
    1519768519464
  ]
}

Responses

Status Meaning Description Schema
200 OK success userResponse

deleteUser

Code samples

# You can also use wget
curl -X DELETE https://api.moesif.com/v1/search/~/users/{id} \
  -H 'Authorization: Bearer YOUR_MANAGEMENT_API_KEY'

const fetch = require('node-fetch');

const headers = {
  'Authorization':'Bearer YOUR_MANAGEMENT_API_KEY'
};

fetch('https://api.moesif.com/v1/search/~/users/{id}',
{
  method: 'DELETE',

  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

import requests
headers = {
  'Authorization': 'Bearer YOUR_MANAGEMENT_API_KEY'
}

r = requests.delete('https://api.moesif.com/v1/search/~/users/{id}', headers = headers)

print(r.json())

require 'rest-client'
require 'json'

headers = {
  'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY'
}

result = RestClient.delete 'https://api.moesif.com/v1/search/~/users/{id}',
  params: {
  }, 
  headers: headers

p JSON.parse(result)

<?php

require 'vendor/autoload.php';

$headers = array(
    'Authorization' => 'Bearer YOUR_MANAGEMENT_API_KEY',
);

$client = new \GuzzleHttp\Client();

try {
    $response = $client->request('DELETE','https://api.moesif.com/v1/search/~/users/{id}', array(
        'headers' => $headers,
       )
    );
    print_r($response->getBody()->getContents());
 }
 catch (\GuzzleHttp\Exception\BadResponseException $e) {
    // handle exception or api errors.
    print_r($e->getMessage());
 }

 // ...

package main

import (
       "bytes"
       "net/http"
)

func main() {

    headers := map[string][]string{
        "Authorization": []string{"Bearer YOUR_MANAGEMENT_API_KEY"},
    }


    req, err := http.NewRequest("DELETE", "https://api.moesif.com/v1/search/~/users/{id}")
    req.Header = headers

    client := &http.Client{}
    resp, err := client.Do(req)
    // ...
}

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

/// <<summary>>
/// Example of Http Client
/// <</summary>>
public class HttpExample
{
    private HttpClient Client { get; set; }

    /// <<summary>>
    /// Setup http client
    /// <</summary>>
    public HttpExample()
    {
      Client = new HttpClient();
    }




    /// Make a dummy request
    public async Task MakeDeleteRequest()
    {
      int id = 1;
      string url = "https://api.moesif.com/v1/search/~/users/{id}";

      await DeleteAsync(id, url);
    }

    /// Performs a DELETE Request
    public async Task DeleteAsync(int id, string url)
    {
        //Execute DELETE request
        HttpResponseMessage response = await Client.DeleteAsync(url + $"/{id}");

        //Return response
        await DeserializeObject(response);
    }

    /// Deserialize object from request response
    private async Task DeserializeObject(HttpResponseMessage response)
    {
        //Read body 
        string responseBody = await response.Content.ReadAsStringAsync();

        //Deserialize Body to object
        var result = JsonConvert.DeserializeObject(responseBody);
    }
}

URL obj