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).