C#

In C#, we'll be using HttpClient from System.Net.Http to send HTTP requests. Here's how you can use the book search API with C#:

First, make sure you have the following using directives at the top of your file:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

Then, you can use the following code to make the API request:

public async Task<string> SearchBook(string query)
{
    string apiKey = Environment.GetEnvironmentVariable("PROMPTJOY_API_KEY");
    string url = "https://api.promptjoy.com/api/mVMCpq";

    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("x-api-key", apiKey);
        
        var payload = new StringContent("{\"query\":\"" + query + "\"}", Encoding.UTF8, "application/json");
        var response = await client.PostAsync(url, payload);
        
        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsStringAsync();
            return result;
        }
        else
        {
            throw new Exception($"Error: {response.StatusCode}");
        }
    }
}

You can call this function with the search term as follows:

string searchResult = await SearchBook("your_search_term");
Console.WriteLine(searchResult);

Replace "your_search_term" with the book you're searching for. This function will return a JSON string of the search results.

This example uses the async and await keywords for asynchronous programming. If you're not familiar with these, you might want to read up on Asynchronous Programming with async and await in C#.

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.

Last updated