Comment on page
TypeScript
In TypeScript, we'll be using the
fetch
API to send HTTP requests. Here's how you can use the book search API with TypeScript:First, define an interface for the book data:
interface Book {
title: string;
author: string;
}
Next, write the
searchBook
function using async/await:async function searchBook(query: string): Promise<Book[]> {
const url = 'https://api.promptjoy.com/api/mVMCpq';
const options: RequestInit = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': process.env.PROMPTJOY_API_KEY
},
body: JSON.stringify({ query })
};
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: Book[] = await response.json();
return data;
}
You can call this function with the search term as follows:
searchBook('your_search_term')
.then(data => console.log(data))
.catch(error => console.log('There was an error!', error));
This example uses the Fetch API, which returns Promises. If you're not familiar with Promises or async/await syntax, you might want to read up on those.
Remember to handle exceptions and errors as needed in your actual application code.
Note: In this example, the API key is retrieved from environment variables for security reasons. Ensure that you've set the
PROMPTJOY_API_KEY
environment variable in your environment where this code will be executed. If you're running this in a browser, you'll need to set this in some secure way, as exposing your API key in the client-side JavaScript code is not recommended.Last modified 5mo ago