Connect to your online database

You can connect to your online RestDB database from any application using the secure HTTPS protocol. This document gives an overview and introduction to the various connection methods and programming language approaches.

To ensure a secure connection, RestDB will require some sort of secure access token. RestDB is compatible and similar to MongoDB in its query language, but you don't connect to your database with a MongoDB connection string over a network socket. With RestDB you always connect to the database API over HTTPS with an access token (API key or JWT token).

Any programming language, client or server application can securely connect to your database if provided with a valid access token.

An invalid access token will also result in a denial of access (HTTP response code 403) for that client using the revoked access token.

A secure connection to your online database can be performed with the following methods:

  • Full access API key
  • Limited web API key (CORS)
  • Auth0.com
  • JSON Web Token (JWT)
  • Valid user session

In addition you can also support custom access logic via RestDB dynamic Pages (supports Basic Authentication) or Custom JavaScript routes.

Connect to your online database from a cURL script

One simple way to connect to your online database is using the command line with cUrl and an API key from your database.

curl -k -i -H "Content-Type: application/json"\
-H "x-apikey: 560bd47058e7ab1b2648f4e7"\
-X GET 'https://inventory-fac4.restdb.io/rest/motorbikes'

Which will return some data in JSON format:

[
    {
        "_id": "557eb5ed345a1b27000005e7",
        "Model": "180 Super Sport",
        "Year": 2015
    },
    {
        "_id": "557eb5ed345a1b27000005ef",
        "Model": "50 S",
        "Year": 1998
    }, ...
]

Connect to your online database from a client web page

A common use case is to connect to your online database from a public web page. To allow access from a web page you can create a CORS API key.

What is CORS?

Lets pretend that you have a web page hosted at the domain:

https://examples.com/mypage.html

And that you from that page want to connect to your online RestDB database at:

https://inventory-fac4.restdb.io

The web browser will consider this connection request as outside of the origin (here: example.com), also known as a cross-origin request. These type of requests is by default not allowed. CORS (cross-origin resource sharing) manages cross-origin requests. With CORS, you can specify who can access the database and which HTTP request methods are allowed from external resources, i.e. GET, POST, PUT, PATCH, DELETE.

Follow this link to read the docs about how to create CORS API keys for your data collection resource.

CORS API key

The example code below shows how a JavaScript ajax call connects to the database using a CORS API key.

var myCorsApiKey = "5b45ebc4f0f7605ca49e916c";
var data = null;

var xhr = new XMLHttpRequest();
xhr.withCredentials = false;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "https://inventory-fac4.restdb.io");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("x-apikey", myCorsApiKey);
xhr.setRequestHeader("cache-control", "no-cache");

xhr.send(data);

Connect from a development web app running on localhost

Perhaps you develop a React, Angular or Vue.js single page application. And as part of your development workflow, you may want to run a local web server for rapid testing and development. Hence, you web page is loaded from a local domain, e.g.:

http://localhost:8080/mypage.html

Different web browsers handle the CORS part of connecting to a local domain differently. To avoid errors and confusion we recommend that you create a separate CORS API key with REST API path to /** and allowed domain set to *.

This enables you to develop local Single Page applications which uses your database REST API.

Connect with Facebook and Google using Auth0.com

RestDB integrates with Auth0.com, a leading authentication cloud service. This gives your users single-sign-on (SSO) to your database REST API by using a wide range of connection methods, including Facebook and Google. The example screenshot below shows the Auth0 lock screen that enables users to log in to your app and gain access to your API endpoint with a secure token.

Auth0.com lock screen

After a successful user authentication via the Auth0 lock screen, you can retrieve a valid JWT token from Auth0. This JWT token is used to get access to your RestDB database API.

/* Example JavaScript Auth0.com application using JQuery */

const AUTH0_CLIENT_ID = "DaIj3UPFDF2yGcZYwfwDV1VTfxN5p20p";
const AUTH0_DOMAIN = "marcon.eu.auth0.com";

// Set up Auth0 public account info
var lock = new Auth0Lock(AUTH0_CLIENT_ID, AUTH0_DOMAIN, {
    auth: {
    params: { scope: 'openid email' } // Details: https://auth0.com/docs/scopes
    }
});

// The user clicks on a login button
$('.btn-login').click(function(e) {
    e.preventDefault();
    lock.show();
    return false;
});


// A valid user, get the JWT token and use it to connect to the database REST API
lock.on("authenticated", function(authResult) {
    lock.getProfile(authResult.idToken, function(error, profile) {
        // remember the JWT token
        localStorage.setItem('id_token', authResult.idToken);

        // global ajax Authorization setup
        $.ajaxPrefilter(function( options ) {
            if ( !options.beforeSend) {
                options.beforeSend = function (xhr) { 
                    xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('id_token'));
                }
            }
        });
    });
});

To allow users to use single-sign-on via Auth.com you must also enable this in your database settings. Copy the credentials from Auth0.com into the database setup as shown below:

JWT setup in the database API

Read more in the docs here https://restdb.io/docs/authentication-of-external-users.

Connect from a server app you control

Connecting from server-to-server where you control both sides, does not require a CORS API key. A full access API key could be used here. A full access API key has complete access to all database operations (GET, POST, PUT, DELETE, PATCH).

full access apikey

Connect from a server others control

Connecting from server-to-server where you only control the database side requires a secure API key. You can use the same restrictions as with a CORS API key with respects to REST API path and REST methods. However, since the client is actually a server, the domain name will be ignored. E.g. you could create an API key for a specific server access that gives read access to a data collection. E.g. apikey: 55c348ee6fde358e3c00bb8a, Allow: GET, Path: /customers/**

Connect to realtime server events

Your RestDB database supports realtime message streaming for data events. You can connect to the url with any http-compatible libraries (with EventSource support).

To subscribe to event messages use the GET method. To publish event messages use the POST method.

Connect to realtime streams with the JavaScript API

Create a new database API connection using the auto generated JavaScript API for your database (read the JavaScript API docs here).

var db = new.db("your-CORS-apikey-here | JWT token", {realtime: true});

You must also enable realtime access to the web API-key you use.

Connect to realtime streams with cUrl

The example below connects to the realtime stream with cUrl and a full acceess API key:

    curl -i -H "Content-Type: application/json"\
    -H "x-apikey: your-full-access-api-key-here"\
    -X GET 'https://inventory-fac4.restdb.io/realtime'
    HTTP/1.1 200 OK
    ...

Connect and publish custom events a POST method and cUrl.

    curl -i -H "Content-Type: application/json"\
    -H "x-apikey: you-api-code-here"\
    -X POST -d '{"event":"answer","data":{"name":42}}'\
    'https://inventory-fac4.restdb.io/realtime'
    HTTP/1.1 200 OK
    ...

Connect using webhooks

Your RestDB database can connect to other systems with "user-defined HTTP callbacks", also known as WebHooks. Webhooks are perfect for integrations.

RestDB will call an URL when one of the following events occur:

  • Create a data record
  • Update a data record
  • Delete one or many data records

To create a Webhook, activate Developer mode (top right corner), navigate to a Collection and click on the Webhook tab.

Enter the URL endpoint for the Webhook, check which event you want to trigger and check the Active checkbox.

screenshot

Connect from a user session

When you log in to the RestDB data admin backend a session is created for your user. This enables you to access the database API from the same user session without providing an API key. For quick access to a REST data source or to test a MongoDB query this is really easy.

browser database access

Connect from an iOS App

Example on how to connect to your database from an iOS App using the Swift programming language.

import Foundation

let headers = [
"content-type": "application/json",
"x-apikey": "560bd47058e7ab1b2648f4e7",
"cache-control": "no-cache"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://inventory-fac4.restdb.io/rest/motorbikes")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                        timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
        print(error)
    } else {
        let httpResponse = response as? HTTPURLResponse
        print(httpResponse)
    }
})

dataTask.resume()

Connect from an Android App

Example on how to connect to your database from an Android App using the standard Java library.

Enable Internet access in your application manifest file:

<uses-permission android:name="android.permission.INTERNET" />
// Create URL
URL restdbEndpoint = new URL("https://inventory-fac4.restdb.io/rest/motorbikes");
 
// Create connection
HttpsURLConnection myConnection =
        (HttpsURLConnection) restdbEndpoint.openConnection();
        
myConnection.setRequestProperty("User-Agent", "my-restdb-app");
myConnection.setRequestProperty("Accept", "application/json");
myConnection.setRequestProperty("x-apikey", "560bd47058e7ab1b2648f4e7");

if (myConnection.getResponseCode() == 200) {
    // Success
    // Further processing here
} else {
    // Error handling code goes here
}

Connect from node.js

Example on how to connect to your database from a Node.js App using the standard http library.

const https = require('https');

var options = {
    "method": "GET",
    "hostname": "inventory-fac4.restdb.io",
    "path": "/rest/motorbikes",
    "port": 443,
    "headers": {
      "Content-Type": "application/json",
      "x-apikey": "560bd47058e7ab1b2648f4e7",
      "Cache-Control": "no-cache"
    }
};

https.get(options, (res) => {
    let body = "";

    res.on("data", (chunk) => {
        body += chunk;
    });

    res.on("end", () => {
        try {
            let json = JSON.parse(body);
            // do something with JSON
            console.log(json);
        } catch (error) {
            console.error(error.message);
        };
    });

}).on("error", (error) => {
    console.error(error.message);
});

With Node.js you can use the npm library to explore other popular libraries, and perhaps easier ways to connec to your online database. Examples here are the Axios and Request libraries. Pick your favorite :)

Connect from Postman

Using the excellent Postman app for accessing your database is a great way to explore and test your data REST API. Just install the Postman application and paste in a database REST url to get started. For authentication you also need to add a secure token as a HTTP Header value. E.g. x-apikey: xxxxxxxxxx. The screenshot below shows the Postman application running a MongoDB query against RestDB.

The Postman app

Connect from other popular programming languages

Check out the code examples for REST API in all the popular programming languages, including:

JavaScript, Node.js, Java, Python, PHP, C#, Swift, Objective-C and curl.

Read more about RestDB in the docs.