0

I am trying to make use of UDEMY API. Each request must contain Authorization: Basic + keys header. This is in the api documentation:

curl --user {YOUR_CLIENT_ID}:{YOUR_CLIENT_SECRET} https://www.udemy.com/api-2.0/courses/

curl -H "Authorization: Basic {BASE64_ENCODED(CLIENT_ID:CLIENT_SECRET)}" https://www.udemy.com/api-2.0/courses/

This is what I have tried below but I have been getting errors.

const axios = require('axios');
const config = require('../config');


const { app: { API_URL, CLIENT_ID, CLIENT_SECRET } } = config;


var options = {
    method: 'GET',
    url: 'courses',
    baseURL: API_URL,
    headers: {
        'Authorization': 'Basic ' + CLIENT_ID + ':' + CLIENT_SECRET,
    },
    responseType: 'json',
  };

//  Get all Posts handler
exports.getCourses = async(req, res, next) => {
    try {
        const response = await axios(options);
        console.log(response);
        res.status(200).json({ courses: response });

    } catch (error) {
        res.status(500).json({message: 'ERROR: Error Occured!'});
    }
}

This is the error I am getting:

GET http://localhost:3000/api/courses 500 (Internal Server Error)
ERROR Error: Error Code: 500,  Message: Http failure response for http://localhost:3000/api/courses: 500 Internal Server Error

Please, I need your help in resolving this.

Thanks in advance!

1 Answers1

1

According to your docs, /api-2.0/courses/ uses Basic authentication which is a simple authentication scheme built into the HTTP protocol.

Technically it needs a header:

Authorization : Basic ******

In wich ***** is a base64 encode of clientid:clientsecret

Something like this:

var clientId = 'Test';
var clientSecret = '123';
var authHeaderValue = 'Basic ' + Buffer.from(clientId + ':' + clientSecret).toString('base64');

And then, add to your options:

var options = {
    ...
    headers: {
        'Authorization': authHeaderValue
    },
    ...
  };

Check this for more examples:

JRichardsz
  • 14,356
  • 6
  • 59
  • 94
  • Thanks @JRichardsz I did the string conversion to base64 like so: ``` const client_id = Buffer.from(CLIENT_ID).toString('base64'); const client_secret = Buffer.from(CLIENT_SECRET).toString('base64'); const options = { method: 'GET', url: 'courses/?page=1&page_size=5', baseURL: API_URL, headers: { 'Authorization': 'Basic ' + client_id + ':' + client_secret, }, responseType: 'json', }; const response = await axios(options); ``` but it's still throwing error. Any suggestion? – Trailblazer Dec 13 '21 at 22:50
  • Try with curl and if it works, compare it with your nodejs code. Also your code is wrong. I updated the answer with a complete sample – JRichardsz Dec 13 '21 at 23:14
  • Thanks @JRichardsz ! It's working now following your edited answer. – Trailblazer Dec 15 '21 at 07:58
  • If this helped to solve your question, please click the checkmark on the left to mark this as solved and/or the arrow up to mark as useful – JRichardsz Dec 15 '21 at 14:07