Step 1: Create a Bitly account using this link Bitly sign up
Step 2: Just by the side bar, head over to settings.
Step 3: Head over to developer settings to generate an
API token.
Step 4: Fill in your password to generate this token.
Step 5: Head over to VS Code.
Step 6: Install axios using
npm i axios --save
Step 7:Create form component
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter a long URL"
value=''
/>
<button type="submit">Shorten</button>
</form>
Step 8: Create a state function for your URL values.
urlInput: This is the long URL the user wants to shorten.
urlOutput: This is the new shortened URL.
const [urlInput, setUrlInput] = useState('');
const [urlOutput, setUrlOutput] = useState('');
Step 9: Create an asynchronous submit function
//(e) is an event handler that
const handleSubmit = async (e) => {
e.preventDefault(); // To prevent the button from submitting before the function runs, we add e.preventDefault.
//The try-catch function is to run the function smoothly and help us identify errors along the way
try {
const res = await axios.post(
'https://api-ssl.bitly.com/v4/shorten', // the api link
{
long_url: urlInput // your url input state value
},
{
headers: {
'Content-Type': 'application/json',
Authorization: 'YOUR_API_KEY/TOKEN'
}
}
);
setUrlOutput(res.data.link);
} catch (error) {
console.error(error);
}
};
Step 10
a. Create a
{urlOutput && (
<div>
<p>Shortened URL:</p>
<a href={urlOuput} target="_blank" rel="noopener noreferrer">
{urlOutput}
</a>
</div>
)}
b. Update the values of the form
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter a long URL"
value={urlInput}
onChange={(e) => setUrlInput(e.target.value)}
/>
<button type="submit">Shorten</button>
</form>
That's it!
You've created your url shortener with Bitly's API! Let me know what you think in the comments. Contributions and feedbacks are obviously welcome. Cheers ;)
Top comments (0)