Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add getting started example #1679

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 127 additions & 0 deletions docs/sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,133 @@ The [SDK _client_](/sdk/api/README.md#sdk-client) itself is in fact really simpl

If we take a step back and look at the general requirement, at the end we simply want to **execute a request**. It just happens to be that we want to make specific requests to the commercetools platform API but it might be as well any other API. That's where the [middlewares](/sdk/Middlewares.md) come in, which provide the _side effects_ of the given request.

## Getting started
This tutorial will show you how to use the middlewares in this commercetools JavaScript SDK to get a simple commercetools JavaScript app running.

### Create a API client
[Create API client](https://docs.commercetools.com/tutorials/getting-started#creating-an-api-client) from Merchant Center. If you do not have account [follow the steps to create a free trial account](https://docs.commercetools.com/tutorials/getting-started#first-steps).
In this guide we’ll be calling a method of commercetools API using JavaScript SDK to get the settings of a commercetools project. The commercetools API is the foundation of the commercetools Platform, and almost every commercetools client app uses it. Aside from getting project information, the commercetools API allows clients to call methods that can be used for everything from creating products to updating an order’s status. Before we can call any methods, we need to configure our new app to obtain an access token.

### Getting a client credentials to use the commercetools API
From the API client Details page mentioned in the previous step copy `project_key`, `clientId`, `clientSecret`, `API URL`, `scope` and `Auth URL`. The commercetools API uses `clientId` and `clientSecret` to authenticate the requests your app makes. In a later step, you’ll be asked to use these values in your code.

### Set up your local project
If you don’t already have a project, let’s create a new one. In an empty directory, you can initialize a new project using the following command:

```
$ npm init -y
```

After you’re done, you’ll have a new package.json file in your directory.
Install the `@commercetools/sdk-client`, `@commercetools/sdk-middleware-auth`, `@commercetools/sdk-middleware-http`, `@commercetools/api-request-builder` and `dotenv` packages and save it to your `package.json` dependencies using the following command:

```
$ npm install @commercetools/sdk-client @commercetools/sdk-middleware-auth @commercetools/sdk-middleware-http @commercetools/api-request-builder dotenv
```

Create a new file called `project.js` in this directory and add the following code:
```js
const { createClient } = require('@commercetools/sdk-client')
const { createRequestBuilder } = require('@commercetools/api-request-builder')
const { createAuthMiddlewareForClientCredentialsFlow } = require('@commercetools/sdk-middleware-auth')
const { createHttpMiddleware } = require('@commercetools/sdk-middleware-http')
const fetch = require('node-fetch')

require('dotenv').config()

console.log('Getting started with commercetools JavaScript SDK');
```

Back at the command line, run the program using the following command:
```
$ node project.js
Getting started with commercetools JavaScript SDK
```
If you see the same output as above, we’re ready to start.

### Get commercetools project information with the commercetools API
In this guide we’ll get project settings information. We’ll also follow the best practice of keeping secrets outside of your code (do not hardcode sensitive data).

Store the client id and secret in a new environment variable. Create a new file called .env in this directory and add the following code:
```
ADMIN_CLIENT_ID=<your_admin_client_id>
ADMIN_CLIENT_SECRET=<your_admin_secret_id>
```
Replace the values with your client id and client secret that you copied earlier.

Re-open `project.js` and add the following code:
```js
const {
ADMIN_CLIENT_ID,
ADMIN_CLIENT_SECRET,
} = process.env;

const projectKey = '<your_project_key>'

// Create a httpMiddleware for the your project AUTH URL
const authMiddleware = createAuthMiddlewareForClientCredentialsFlow({
host: '<your_auth_url>',
projectKey,
credentials: {
clientId: ADMIN_CLIENT_ID,
clientSecret: ADMIN_CLIENT_SECRET,
},
scopes: ['<your_client_scope>'],
fetch,
})

// Create a httpMiddleware for the your project API URL
const httpMiddleware = createHttpMiddleware({
host: '<your_api_url>',
fetch,
})

// Create a client using authMiddleware and httpMiddleware
const client = createClient({
middlewares: [authMiddleware, httpMiddleware],
})

// Create a request builder for the project
const projectService = createRequestBuilder({ projectKey }).project;

// Create a request to get project information
const createGetProjectRequest = {
uri: projectService.build(),
method: 'GET',
};


(async () => {
try {
// Use the `client.execute` method to send a message from this app
await client.execute(createGetProjectRequest)
.then(data => {
console.log('Project information --->', data);
})
.catch(error => {
console.log('ERROR --->', error);
})
} catch (error) {
console.log('ERROR --->', error);
}
})();
```
Replace the value `<your_project_key>`, `<your_auth_url>`, `<your_client_scope>` and `<your_api_url>` with your client `project_key`, `API URL`, `scope`, and `Auth URL` that you copied earlier.

This code creates a **client**, which uses `authMiddleware` and `httpMiddleware`. The `httpMiddleware` reads the `clientId` and `clientSecret` from environment variables. Then client will **execute** get project information request.

Run the program. The output should look like the following if the request is successful:
```
$ node project.js
Getting started with commercetools JavaScript SDK
Project information ---> {
body: {
<projectData>
},
statusCode: 200
}
```

## Usage example

In this example (integration test) we are going to make some requests to the `/channels` API endpoint. For that we need to be able to make actual requests (`http` middleware) as well as to authenticate the requests using the API Client Credentials Flow (`auth` middleware).
Expand Down