Home > Software engineering >  API Request to RAPID API gives StatusCode: 401,
API Request to RAPID API gives StatusCode: 401,

Time:10-04

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const cryptoApiHeaders = {
  'x-rapidapi-key': 'coinranking1.p.rapidapi.com',
  'x-rapidapi-host': '935af67341msh072d3f07b71a1f8p1cb0b5jsn44961d90a001',
};

const baseUrl = 'https://coinranking1.p.rapidapi.com';

const createRequest = (url) => ({ url, headers: cryptoApiHeaders });

export const cryptoApi = createApi({
  reducerPath: 'cryptoApi',
  baseQuery: fetchBaseQuery({ baseUrl }),
  endpoints: (builder) => ({
    getCryptos: builder.query({
      query: () => createRequest('/coins'),
    }),
  }),
});

export const { useGetCryptosQuery } = cryptoApi;

** I tried to connect api from RapidApi but I keep getting 401 unauthorized. I couldn't figured out by myself :3 someone help me please **

CodePudding user response:

Your headers should be this

const cryptoApiHeaders = {
  'x-rapidapi-host': 'coinranking1.p.rapidapi.com',
  'x-rapidapi-key': '935af67341msh072d3f07b71a1f8p1cb0b5jsn44961d90a001',
};

CodePudding user response:

Just pass the API key and host another way around. Like this

'x-rapidapi-key': '935af67341msh072d3f07b71a1f8p1cb0b5jsn44961d90a001',
'x-rapidapi-host': 'coinranking1.p.rapidapi.com',

P.S. API key is a sensitive credential that might be misused. You have just exposed your API key. I recommend you delete this API key and generate a new one for you at Developer Dashboard of RapidAPI

  • Related