node-ovh

repository·master·Indexed 41 days ago

https://github.com/ovh/node-ovh

Official Node.js wrapper for OVHcloud APIs (version 3.0.6). Provides callback-based `request()` and Promise-based `requestPromised()` methods to interact with OVHcloud services across Europe, US, and Canada, as well as SoYouStart and Kimsufi. Supports authentication via OAuth2 or Application Key/Secret and includes built-in API schema loading for validation and deprecation warnings.

Tokens
3.1K
Snippets
10
Records
11
Agent score
99%

What's inside node-ovh

  1. Configure the client using Application Key/Secret

    master

    To use Application Key/Secret authentication, you must first create an application on the appropriate OVHcloud portal (Europe, US, North-America, SoYouStart, or Kimsufi) to obtain an appKey (AK) and appSecret (AS).

    To authorize your application to access a specific customer account, you need a consumer key (CK). You can request this by calling the /auth/credential endpoint with specific accessRules.

    var ovh = require('@ovhcloud/node-ovh')({
      endpoint: 'ovh-eu',
      appKey: 'YOUR_APP_KEY',
      appSecret: 'YOUR_APP_SECRET'
    });
    
    // Requesting a consumer key with specific access rules
    ovh.request('POST', '/auth/credential', {
      'accessRules': [
        { 'method': 'POST', 'path': '/sms/*/jobs'}
      ]
    }, function (error, credential) {
      console.log(error || credential);
    });
  2. Migrate from 1.x.x to 2.x.x (Removing Proxy Support)

    master

    In version 1.x.x, the library used a proxy-based approach for accessing resources (e.g., ovh.me.bill["0123"].$get()).

    In version 2.x.x, you must use the explicit request or requestPromised methods with the correct API path discovered via the OVHcloud API consoles.

    Example Migration: To get bill information for ID 0123:

    • Old (1.x.x): ovh.me.bill["0123"].$get(...)
    • New (2.x.x): ovh.requestPromised('GET', '/me/bill/0123')
    // 2.x.x approach
    ovh.requestPromised('GET', '/me/bill/0123')
      .then(function (billInformation) {
        // handle success
      })
      .catch(function (err) {
        // handle error
      });
  3. Install @ovhcloud/node-ovh

    master

    You can install the latest stable release from the npm registry or install the latest development version directly from GitHub.

    To install the stable version:

    npm install @ovhcloud/node-ovh

    To install the development version:

    npm install git://github.com/ovh/node-ovh.git
    npm install @ovhcloud/node-ovh
  4. Configure API schema loading and validation

    master

    The client can automatically load API schemas to provide warnings about deprecated methods, missing authentication, or invalid paths.

    To optimize performance and only load necessary schemas, use the apis option in the constructor to specify which APIs you intend to use. The client will automatically include the auth API if needed.

    Warnings generated by the client include:

    • Calling a method that does not exist in the schema.
    • Calling a method with an incorrect HTTP verb.
    • Calling a method tagged as DEPRECATED (includes replacement suggestions).
    • Calling a method that requires a consumerKey when none is provided.
    const client = ovh({
      appKey: '...', 
      appSecret: '...', 
      apis: ['ip', 'cloud', 'storage'] // Only load these schemas
    });
  5. Initialize the OVH client

    master

    To use the OVH API, you must instantiate the client by providing authentication credentials. The client supports two main authentication methods: Legacy Application Key and OAuth2. You cannot use both simultaneously.

    Authentication Options

    1. Legacy Application Key/Secret: Requires appKey and appSecret. If you also have a consumerKey, provide it to enable request signing.
    2. OAuth2: Requires clientID, clientSecret, and a tokenURL.

    Configuration Parameters

    ParameterTypeDescription
    endpointstringPreconfigured API endpoint name (e.g., from endpoints.js)
    appKeystringYour OVH application key
    appSecretstringYour OVH application secret
    consumerKeystringYour OVH consumer key (required for signing)
    clientIDstringOAuth2 client ID
    clientSecretstringOAuth2 client secret
    tokenURLstringThe URL to fetch OAuth2 tokens
    hoststringAPI host (defaults to eu.api.ovh.com)
    portnumberAPI port (defaults to 443)
    basePathstringAPI base path (defaults to /1.0)
    apisstring[]List of specific APIs to load schemas for (improves performance)
    debugbooleanEnable debug logging
    warnfunctionCustom function for warnings (defaults to console.log)
    const ovh = require('node-ovh');
    
    // Example using Application Key/Secret
    const client = ovh({
      appKey: 'YOUR_APP_KEY',
      appSecret: 'YOUR_APP_SECRET',
      consumerKey: 'YOUR_CONSUMER_KEY'
    });
    
    // Example using OAuth2
    const oauthClient = ovh({
      clientID: 'YOUR_CLIENT_ID',
      clientSecret: 'YOUR_CLIENT_SECRET',
      tokenURL: 'https://auth.ovh.com/oauth2/token'
    });
  6. Use request() and requestPromised() to call OVHcloud APIs

    master

    The library provides two ways to make API requests: a callback-based method request() and a Promise-based method requestPromised().

    Callback pattern

    Use request(method, path, [body], callback) where the callback receives (err, response).

    Promise pattern

    Use requestPromised(method, path, [body]) which returns a Promise that resolves with the response or rejects with an error object in the format {error: statusCode, message: message}.

    var ovh = require('@ovhcloud/node-ovh')({
      appKey: process.env.APP_KEY,
      appSecret: process.env.APP_SECRET,
      consumerKey: process.env.CONSUMER_KEY
    });
    
    // Callback usage
    ovh.request('GET', '/me', function (err, me) {
      console.log(err || 'Welcome ' + me.firstname);
    });
    
    // Promise usage
    ovh.requestPromised('GET', '/me')
      .then(function (response) {
        // Do what you want
      })
      .catch(function (err) {
        // Handle error
      });
  7. Configure the client using OAuth2

    master

    To use OAuth2, initialize the client with clientID, clientSecret, and an endpoint.

    Available endpoints:

    • ovh-eu for OVHcloud Europe
    • ovh-us for OVHcloud US
    • ovh-ca for OVHcloud Canada
    var ovh = require('@ovhcloud/node-ovh')({
      clientID: 'YOUR_CLIENT_ID',
      clientSecret: 'YOUR_CLIENT_SECRET',
      endpoint: 'ovh-eu'
    });
  8. Reference: API Endpoints

    master

    When initializing the client, use the following endpoint values to target different OVHcloud services:

    ServiceEndpoint Value
    OVHcloud Europeovh-eu
    OVHcloud USovh-us
    OVHcloud Canadaovh-ca
    SoYouStart Europesoyoustart-eu
    SoYouStart North-Americasoyoustart-ca
    Kimsufi Europekimsufi-eu
    Kimsufi North-Americakimsufi-ca
  9. Execute API requests with requestPromised()

    master

    The requestPromised method is the recommended way to interact with the OVH API using modern async/await syntax. It returns a Bluebird promise.

    Parameters:

    • httpMethod: The HTTP verb (e.g., 'GET', 'POST', 'PUT', 'DELETE').
    • path: The API endpoint path. Supports template placeholders like {paramName} which will be replaced by values in the params object.
    • params: An object containing query string parameters or the JSON body (for POST/PUT).

    Note: If the path contains {key}, the corresponding value in params is extracted from the body and injected into the URL path.

    // Example: GET request with query params
    const services = await client.requestPromised('GET', '/services', { limit: 10 });
    
    // Example: POST request with body
    const result = await client.requestPromised('POST', '/services', { name: 'new-service' });
    
    // Example: Path parameter replacement
    // If path is '/services/{id}', passing { id: '123' } results in '/services/123'
    const service = await client.requestPromised('GET', '/services/{id}', { id: '123' });
  10. Execute API requests with request()

    master

    The request method is the primary way to interact with the OVH API. It supports path parameter replacement using the {key} syntax.

    Signature: request(httpMethod, path, params, callback)

    • httpMethod: The HTTP verb (e.g., 'GET', 'POST', 'PUT', 'DELETE').
    • path: The API endpoint path. If the path contains placeholders like {id}, the values in params will be used to replace them.
    • params: An object containing query string parameters (for GET) or the request body (for POST/PUT).
    • callback: A function called with (error, response). If error is present, it may be a status code or an error object.

    Note on Path Parameters: If a parameter in params is used to replace a placeholder in the path, it is automatically removed from the params object so it is not sent in the body or query string.

    client.request('GET', '/user/{id}', { id: '123' }, function (err, resp) {
      if (err) return console.error(err);
      console.log(resp);
    });
  11. Preconfigured OVHcloud API endpoints

    master

    The node-ovh library provides a set of preconfigured endpoint configurations for different OVHcloud services and regions. These configurations include the API host and, where applicable, the tokenURL required for authentication. You can use these identifiers to quickly target specific services like OVH Europe, OVH US, SoYouStart, or Kimsufi.

    // Available endpoint identifiers and their configurations:
    {
      'ovh-eu': { 'host': 'eu.api.ovh.com', 'tokenURL': 'https://www.ovh.com/auth/' },
      'ovh-us': { 'host': 'api.us.ovhcloud.com', 'tokenURL': 'https://us.ovhcloud.com/auth/' },
      'ovh-ca': { 'host': 'ca.api.ovh.com', 'tokenURL': 'https://ca.ovh.com/auth/' },
      'sys-eu': { 'host': 'eu.api.soyoustart.com' },
      'sys-ca': { 'host': 'ca.api.soyoustart.com' },
      'soyoustart-eu': { 'host': 'eu.api.soyoustart.com' },
      'soyoustart-ca': { 'host': 'ca.api.soyoustart.com' },
      'ks-eu': { 'host': 'eu.api.kimsufi.com' },
      'ks-ca': { 'host': 'ca.api.kimsufi.com' },
      'kimsufi-eu': { 'host': 'eu.api.kimsufi.com' },
      'kimsufi-ca': { 'host': 'eu.api.kimsufi.com' }
    }