I have to use the API-Football in my application in react.
The application must have a Login screen and a Dashboard screen (which must be shown after login). To access the application, the user must create an account on API-Football, thus, he will have access to the X-RapidAPI-Key to allow access to the API.
In the login screen, the user must insert the authentication API key provided by API-Football;
Note: The application must use the API key informed by the user to make requests to the API
User and password will not be required to login, only the API key;
It must not be possible to login with an invalid API key;
It should not be possible to access the dashboard page without the user logging in;
I tried to make a login screen to receive the API key in an input, to check if it is valid, however, it did not work.
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
const Login: React.FC = () => {
const [apiKey, setApiKey] = useState('');
const [error, setError] = useState('');
const history = useHistory();
const handleLogin = async () => {
const isValidApiKey = await validateApiKey(apiKey);
if (isValidApiKey) {
sessionStorage.setItem('apiKey', apiKey);
history.push('/dashboard');
} else {
setError('API key no exist');
}
};
return (
<div>
<h1>Login</h1>
{error && <p>{error}</p>}
<input
type="text"
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
placeholder="API Key"
/>
<button onClick={handleLogin}>Login</button>
</div>
);
};
export default Login;
import axios from 'axios';
const validateApiKey = async (apiKey: string): Promise<boolean> => {
try {
const response = await axios.get('api-football', {
headers: {
'X-RapidAPI-Key': apiKey,
'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com',
},
});
if (response.status === 200 && response.data && response.data.api) {
return true; // API key validates
} else {
return false; // A API invalid
}
} catch (error) {
return false; // A API key invalid or error in call
}
};
OBS: The API expects the API key to be included in all API requests to the server in a header similar to the following:
Be sure to replace XxXxXxXxXxXxXxXxXxXxXxXx with API key.
EXAMPLE:
import axios from 'axios';
const options = {
method: 'GET',
url: 'https://api-football-v1.p.rapidapi.com/v3/timezone',
headers: {
'X-RapidAPI-Key': 'xxxxXXXXxxxxxXXXXXxxxxxXXXXXxxxxXXXX',
'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com'
}
};
try {
const response = await axios.request(options);
console.log(response.data);
} catch (error) {
console.error(error);
}
URL: https://rapidapi.com/api-sports/api/api-football