Access the API data by sending requests with the required headers which include the GUID, Username,

Assigned the task of creating a website that relies on fetching vehicle stock data from an API, I find myself struggling with this particular API. Despite my previous experience with various APIs, this one is proving to be quite challenging. Unfortunately, the company behind the API is uncooperative and unwilling to assist me in troubleshooting the issue.

Here's what the API guide contains:

The request needs to be made via an https call to a URL provided by API_COMPANY.

Security

All APIs require the following HTTP security header to be included in the request. The necessary details will be provided by API_COMPANY. Each Dealer will have a unique OrganisationalUnit_UID.

Request

GET
https://theurltotheapi.net/API/vehicles/stockstockListOptionModel.includenewvehicles=true
Accept: application/json
UserName: USERNAME
Password: PASSWORD
OrganisationalUnit_UID: UID
Host: MYWEBSITE.CO.UK
Accept-Encoding: gzip, deflate

I have tried different methods to retrieve the API data, including XMLHttpRequest and the Fetch method shown below. However, I am consistently encountering a 403 error in the console.

<script src="link_to_credentials.js"></script>
<script>
const uri = 'https://theurltotheapi.net/API/vehicles/stock?stockListOptionModel.includenewvehicles=true';

let username = USERNAME;
let password = PASSWORD;
let h = new Headers(); 

h.append('Accept', 'application/json'); 
h.append('Authorization', 'Basic ' + window.btoa(username + ":" + password));
h.append('Accept-Encoding', 'gzip, deflate');
h.append('Host', 'WEBSITE');

let req = new Request(uri, {
method: 'GET',
headers: h,
OrganisationalUnit_UID: GUID,
mode:'no-cors'
});
fetch(req)
    .then ( (response)=>{
    if (response.ok){
        return response.json();
    }else{
            throw new Error('Could not fetch data');    
         }
})
.then( (jsonData) =>{
    console.log(jsonData);
})
.catch ( (err) =>{
    console.log('ERROR : ', err.message);
});
</script>

Despite expecting to see JSON vehicle stock data in the console, I only receive a 403 forbidden error message -

Failed to load resource: the server responded with a status of 403 (Forbidden).

Answer №1

Have you attempted adjusting your authentication header to match their provided example?

Their specified format is as follows:

GET https://theurltotheapi.net/API/vehicles/stockstockListOptionModel.includenewvehicles=true
Accept: application/json
UserName: USERNAME
Password: PASSWORD
OrganisationalUnit_UID: UID
Host: MYWEBSITE.CO.UK
Accept-Encoding: gzip, deflate

However, in your current implementation, you are only including the following headers:

Accept: application/json
Authorization: Basic <user:pass>
Accept-Encoding: gzip, deflate
Host: WEBSITE

Consider adding the code below after this line h.append('Host', 'WEBSITE');

h.append('UserName', username);
h.append('Password', password);
h.append('OrganisationalUnit_UID', GUID);

Additionally, remember to remove the Authorization header as per their example.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trigger JavaScript keypress event on keypress

In my code, I have a function called addMoney() that is triggered by pressing Enter in an input field: $('body').on('keypress', 'input[type=text]', function(e){ if(e.keyCode==13){ var val = $('input[type=te ...

What are some ways to create a responsive image design?

Currently, I am using the code below to enlarge an image when clicked on. I have attempted using media queries in CSS... I have also added another class in #modalPopupHtml# to adjust the size of the large image: .imgsize{ height: 600px; width: 800px; ...

Command in Selenium Webdriver for initiating a mouse click

Currently, I am in the process of writing tests for a Java application that has been created with the Vaadin framework. To conduct these tests, I have opted to utilize the Robot Framework. In certain instances, I must implement robot framework commands suc ...

Eradicate white space in a JavaScript code

Calling all JS programmers! Here's a challenge for you, check out this demo: https://codepen.io/gschier/pen/jkivt I'm looking to tweak 'The pen is simple.' to be 'The pen issimple.' by removing the extra space after 'is& ...

Oops! Looks like something went wrong. The command to install the debug app failed because the emulator could not be launched. This could be due to the fact that no emulators were found

I'm in need of assistance to resolve these issues Encountered an error while trying to install the app. Please ensure that your Android development environment is properly configured: https://reactnative.dev/docs/environment-setup. Error: Command fai ...

Bring in JS into Vue from the node_modules directory

Apologies for my limited knowledge in this area, but I am currently working on integrating and importing This Grid System into my Vue project. However, I am facing some challenges. Typically, I import plugins like this: import VuePlugin from 'vue-plu ...

Creating objects based on interfaces

After looking at this straightforward code: interface int1 { aa: string, bb: number, } const obj1:int1 = {} //#1 function fun(param_obj:int1) { //#2 } I am curious as to why the compiler throws an error: Type '{}' is missing the fol ...

What is the best way to fetch information from an external json api using angularJS?

As an example, I am interested in accessing data from two different URLs: 1- http://jsonplaceholder.typicode.com/posts/ 2- http://jsonplaceholder.typicode.com/todos/ Is it possible to fetch data from these two URLs in a single application using two contro ...

Encountering Internal Server Error when C# WebMethod communicates with JavaScript AJAX call

I've encountered an issue where my AJAX call to a C# WebMethod is not returning the expected result. Instead, it keeps showing an "Internal Server Error" message. A button triggers a JavaScript function: <button id="btn" onclick="Create();">fo ...

React JS: You must define 'Message' in order to avoid the react/jsx-no-undef error

As a novice learner in React JS, I am currently working on developing a messaging web application. However, as I was writing my code, I encountered the following error: Failed to compile. ./src/App.js Line 41:17: 'Message' is not defined react/j ...

What is the best way to dynamically select and deselect radio buttons based on a list of values provided by the controller?

I am currently working on implementing an edit functionality. When the user initially selects a list of radio buttons during the create process, I store them in a table as a CSV string. Now, during the edit functionality, I retrieve this list as a CSV stri ...

A mistake occured: Unable to modify the stack property of [object Object], as it only has a getter method

Encountering an error when attempting to use a service in my component and declaring it in the constructor - TypeError: Cannot set property stack of [object Object] which has only a getter This is the code snippet: import { Component } from '@angula ...

Centering the scrollIntoView feature on mobile devices is presenting challenges with NextJS applications

Description While navigating on mobile browsers, I'm facing a challenge with keeping an element centered as I scroll due to the browser window minimizing. I've experimented with different solutions such as utilizing the react-scroll library and ...

Creating a versatile function for rendering content

I am working on a unique calendar feature that involves using checkboxes for filtering purposes. So far, I have managed to get all the filters functioning correctly by triggering my render event in this manner: //Initiate render event when checkbox is cli ...

Yet another error has been encountered: TypeError undefined is not a function

Hey everyone, I'm currently working on a JavaScript school project where I'm creating a dungeon. It may not be the best code out there, but hey, I'm still learning. I'm encountering an error in the following code: function damageFormu ...

Tips for setting a checkbox as checked based on a value using JQuery

My task is to set the checked status of my checkbox based on a data value. So far, I have been using the following method. $(document).ready(function(){ $('#add').click(function(){ $('#insert').val("Insert"); ...

Inquiries regarding real-time alerts and notifications

Just curious, I am wondering about the creation of those notifications/alerts (for example on platforms like twitchalerts, commonly used by livestreamers). Are they typically coded in JavaScript/AJAX or another language? Is there a specific framework for ...

Tips for extracting a specific field from a list of objects using $push without relying on $group functionality

I have a collection of data in my database [{ "name":"Alice", "age":30 }, { "name":"Bob", "age":35 }, { "name":"Cathy", "age":25 }, { "name":"David", "age":28 }] I'm looking to extract a list of ages like ages:[30,35,25,28] Although these ar ...

Utilizing dynamic, MongoDB-inspired expressions to eliminate specific elements from an array

In the process of creating a lightweight database similar to MongoDB, I am incorporating an object-oriented query language where references can be functions or object references: foo.users.find( args ); foo.users.remove( args ); The 'args' para ...

Trying to parse a JSON object within a try-catch statement

I am facing a challenge while trying to check for a specific condition within a try-catch block in my code. Each time I check for the condition's value, I must initialize it, and if it turns out to be false, the try block exits and the catch block is ...