# Welcome to PromptJoy Preview

Welcome to PromptJoy, the platform that enables you to build scalable APIs by simply describing what you want.&#x20;

This guide is designed to help you navigate all the features and possibilities that PromptJoy offers. We are currently in Public Preview, so please email any feedback to <team@promptjoy.com>.&#x20;

Here's a quick overview of what you'll find:

* [**Quick Start Guide**](/welcome-to-promptjoy-preview/quickstart-guide)**:** If you're new to PromptJoy or need a refresher, this section will help you hit the ground running. We'll walk you through the process of creating your first API.
* [**API Creation with PromptJoy**](/api/api-creation)**:** Here you'll learn how to describe and deploy your APIs with PromptJoy.
* [**API Usage Examples**](/api/api-usage)**:** This section provides usage examples in popular languages like [Python](/api/api-usage/python), [JavaScript](/api/api-usage/javascript), [Ruby](/api/api-usage/ruby), [Go](/api/api-usage/go), [Java](/api/api-usage/java), and [C#](/api/api-usage/c).
* **API Use Cases:** Ready to level up? Explore complex use cases like [building a book search engine](/tutorials/building-a-book-search-engine-with-promptjoy-and-next.js) or [transforming data schemas](/tutorials/data-transformation-enrichment).
* **Integration with Internal Data Sources:** Learn how to integrate your PromptJoy APIs with internal databases and file storage solutions.

Feel free to explore these sections at your own pace. If you ever need help or just want to chat, don't hesitate to get in touch at <team@promptjoy.com>.


# Quickstart Guide

Ready to create your first API with PromptJoy? Here's how:

1. **Sign Up/Log In:** If you're new here, start by creating an account on <https://preview.promptjoy.com>. PromptJoy leverages Auth0 so that you can use your existing Google or GitHub account to sign in.
2. **Create Your API:** Create your API by simply describe what you want your API to do on <https://preview.promptjoy.com/apis/new>. For instance, "You're an API that takes a city name and returns a landmark"
3. **Deploy Your API:** Once you're happy with your API description, hit the "Create API" button. Your API is now alive on a scalable server platform.
4. **Test Your API:** You can try out your new API right within PromptJoy. Just input the required inputs and hit "Test". You'll see the output immediately.
5. **Integrate Your API:** Now that your API is ready, it's time to introduce it to your application. We provide examples in [Python](/api/api-usage/python), [JavaScript](/api/api-usage/javascript), [Ruby](/api/api-usage/ruby), [Go](/api/api-usage/go), [Java](/api/api-usage/java), and [C#](/api/api-usage/c) to help you get started.

And that's it! You have just created your first API with PromptJoy.


# API Creation

Creating an API with PromptJoy is as simple as describing what you want it to do. Let's go through the process using an example: creating a book search API.

### Step 1: Describe Your API

To create a new API, begin by describing what you want it to do. For our example, you might say: "You are a book search engine. I will give you a query, and you will give me 3 results, each one of a real book."

### Step 2: Define the Input and Output

Next, define what the input and output of the API should look like. This is how we tell the API what data it should expect and what it should return. For our book search API, the input might be a query string, and the output could be a list of books.

Input

```json
{"query":"running"}
```

Output

```json
[
  {"title": "Daniels' Running Formula", "author":"Jack Daniels"},
  {"title": "Running In The Dark- Autobiography: To exist on this spinning planet means hope", "author":"Senol Tasdelen"},
  {"title": "80/20 Running: Run Stronger and Race Faster by Training Slower", "author":"Matt Fitzgerald, Rob Grgach, et al."}
]

```

### Step 3: Create Your API

With the description, input, and output defined, you can now create your API. Click on the "Create API" button and PromptJoy will do the rest. Your API is now ready to use.

### Step 4: Test Your API

Once your API is created, you can test it right within PromptJoy. Just enter your query, hit "Test", and you'll see the results instantly.

And that's it! You've just created a book search API with PromptJoy. With this API, you can now search for books in your application.

The same process applies to creating other APIs as well. Just describe what you want, define the input and output, and let PromptJoy create the API for you.


# API Usage

Using an API created with PromptJoy can be done in several programming languages. This guide will show you how to use the book search API (<https://preview.promptjoy.com/apis/mVMCpq>) we created earlier. For this API, we will be making a POST request to `https://api.promptjoy.com/api/mVMCpq` with a JSON payload containing the book search query.

The general API request looks like this:

**Endpoint:** <https://api.promptjoy.com/api/mVMCpq>&#x20;

**HTTP Method:** POST&#x20;

**Headers:**

* Content-Type: application/json
* x-api-key: sk-6200906b6fcc732e9265028f53d5d6f01575a162&#x20;

**Data/Payload:**

```json
{
  "query": "your_search_term"
}
```

\
Before diving into language-specific examples, let's talk about how to store your API key as an environment variable. Environment variables are a great way to keep sensitive information like API keys out of your source code. Here's how to do it:

1. **Windows:** Open a new Command Prompt window and type `setx PROMPTJOY_API_KEY "your_api_key"` then press Enter. Replace "your\_api\_key" with your actual API key.
2. **macOS/Linux:** Open a new Terminal window and type `export PROMPTJOY_API_KEY="your_api_key"` then press Enter. Replace "your\_api\_key" with your actual API key.

You can then access this environment variable in your code using the specific syntax for your programming language. This will be covered in each language-specific example.

Here's how you can make the request using `curl`, a command-line tool used for transferring data with URLs.

```bash
curl -X POST https://api.promptjoy.com/api/mVMCpq \
-H 'Content-Type: application/json' \
-H 'x-api-key: '$PROMPTJOY_API_KEY \
-d '{"query":"your_search_term"}'


```

\
Replace "your\_search\_term" with the book you're searching for. The response will be a JSON object containing the search results.

For language-specific examples, please navigate to the sections for Python, JavaScript, Ruby, Go, Java, and C#. Each section will provide a detailed guide on how to use the book search API in the respective language.<br>


# Java

In Java, we'll use the `java.net.http` package introduced in Java 11 to send HTTP requests. Here's how you can use the book search API with Java:

Firstly, you need to define a Book class to model the data you will be receiving:

```java
public class Book {
    private String title;
    private String author;
    
    // Getters and setters
    public String getTitle() {
        return title;
    }
    
    public void setTitle(String title) {
        this.title = title;
    }
    
    public String getAuthor() {
        return author;
    }
    
    public void setAuthor(String author) {
        this.author = author;
    }
}

```

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

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        String apiKey = System.getenv("PROMPTJOY_API_KEY");
        Map<String, String> values = Map.of("query", "your_search_term");
        String body = new ObjectMapper().writeValueAsString(values);
        
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.promptjoy.com/api/mVMCpq"))
            .header("Content-Type", "application/json")
            .header("x-api-key", apiKey)
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        
        Book[] books = new ObjectMapper().readValue(response.body(), Book[].class);
        
        for (Book book : books) {
            System.out.println("Title: " + book.getTitle() + ", Author: " + book.getAuthor());
        }
    }
}

```

Replace `"your_search_term"` with the book you're searching for. This function will return an array of books.

Remember to handle exceptions and errors as needed in your actual application code.

Note: This example uses the `ObjectMapper` class from the Jackson library to convert JSON to and from Java objects. Ensure that you've added Jackson to your project's dependencies. Also, 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.<br>


# Go

In Go, we'll be using the `net/http` standard library to send HTTP requests. Here's how you can use the book search API with Go:

First, make sure you import the necessary libraries at the top of your file:

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
)

```

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

```go
type Book struct {
	Title  string `json:"title"`
	Author string `json:"author"`
}

type Query struct {
	Query string `json:"query"`
}

func searchBook(query string) ([]Book, error) {
	url := "https://api.promptjoy.com/api/mVMCpq"
	var jsonData = []byte(`{"query":"` + query + `"}`)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("x-api-key", os.Getenv("PROMPTJOY_API_KEY"))

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)

	var books []Book
	err = json.Unmarshal(body, &books)
	if err != nil {
		return nil, err
	}

	return books, nil
}

func main() {
	books, err := searchBook("your_search_term")
	if err != nil {
		fmt.Printf("The HTTP request failed with error %s\n", err)
	} else {
		for _, book := range books {
			fmt.Println("Title: " + book.Title + ", Author: " + book.Author)
		}
	}
}

```

\
Replace `"your_search_term"` with the book you're searching for. This function will return a slice of books.

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.

\ <br>


# 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:

```csharp
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:

```csharp
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:

```csharp
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.\ <br>


# JavaScript

In JavaScript, we'll be using the `fetch` API to send HTTP requests. Here's how you can use the book search API with JavaScript:

First, make sure you have access to the `fetch` API. It's built into most modern browsers, but if you're running this in a Node.js environment, you might need to install and import a package like `node-fetch`.

```javascript
async function searchBook(query) {
    const url = 'https://api.promptjoy.com/api/mVMCpq';
    const options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'x-api-key': process.env.PROMPTJOY_API_KEY
        },
        body: JSON.stringify({ query: query })
    };

    const response = await fetch(url, options);

    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data;
}

```

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

```javascript
searchBook('your_search_term')
    .then(data => console.log(data))
    .catch(error => console.log('There was an error!', error));

```

\
Replace `"your_search_term"` with the book you're searching for. This function will return a promise that resolves to the search results.

Note: 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.

\
\ <br>


# PHP

In PHP, we'll be using the cURL library to send HTTP requests. Here's how you can use the book search API with PHP:

```php
<?php
function searchBook($query) {
    $url = 'https://api.promptjoy.com/api/mVMCpq';
    $apiKey = getenv('PROMPTJOY_API_KEY');
    
    $ch = curl_init();
    
    $postData = json_encode(array('query' => $query));
    
    $options = array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'x-api-key: ' . $apiKey
        ),
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData
    );
    
    curl_setopt_array($ch, $options);
    
    $response = curl_exec($ch);
    
    if (!$response) {
        die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
    }
    
    curl_close($ch);
    
    return json_decode($response, true);
}

$books = searchBook('your_search_term');
foreach ($books as $book) {
    echo "Title: " . $book['title'] . ", Author: " . $book['author'] . "\n";
}
?>

```

Replace `"your_search_term"` with the book you're searching for. This function will return an array of books.

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.

\
\ <br>


# Python

In Python, we'll be using the `requests` library to send HTTP requests. Here's how you can use the book search API with Python:

First, make sure you import the necessary library at the top of your file:

```python
import requests
import os
import json
```

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

```python
def search_book(query):
    url = "https://api.promptjoy.com/api/mVMCpq"
    headers = {
        'Content-Type': 'application/json',
        'x-api-key': os.getenv('PROMPTJOY_API_KEY')
    }
    data = {
        'query': query
    }
    response = requests.post(url, headers=headers, data=json.dumps(data))

    if response.status_code == 200:
        return response.json()
    else:
        raise Exception(f"Request failed with status {response.status_code}")

```

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

```python
search_result = search_book("your_search_term")
print(search_result)

```

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

This example uses the `requests` library, which is a popular choice for making HTTP requests in Python. If you haven't installed it yet, you can do so with `pip install requests`.

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.

\
\ <br>


# Python (Django)

In a Django application, you might want to create a view that makes the API call and returns the result to the client. Here's how you can do it:

First, in your views.py file, add the following code:

```python
from django.http import JsonResponse
import requests
import os
import json

def book_search(request):
    query = request.GET.get('query', '')
    url = "https://api.promptjoy.com/api/mVMCpq"
    headers = {
        'Content-Type': 'application/json',
        'x-api-key': os.getenv('PROMPTJOY_API_KEY')
    }
    data = {
        'query': query
    }
    response = requests.post(url, headers=headers, data=json.dumps(data))

    if response.status_code == 200:
        return JsonResponse(response.json(), safe=False)
    else:
        return JsonResponse({'error': f"Request failed with status {response.status_code}"}, status=response.status_code)

```

In this example, the search term is expected to be passed as a query parameter named `query` in the request to the `book_search` view. The search results are then returned as a JSON response.

Then, in your urls.py file, add a URL pattern for this view:

```python
from django.urls import path
from . import views

urlpatterns = [
    path('book_search/', views.book_search, name='book_search'),
]

```

\
This example uses the `requests` library, which is a popular choice for making HTTP requests in Python. If you haven't installed it yet, you can do so with `pip install requests`.

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.

\ <br>


# Ruby

### Installation

Add this line to your application's Gemfile:

```ruby
gem 'promptjoy-ruby'
```

And then execute:

```bash
bundle install
```

Or install it yourself as:

```bash
gem install promptjoy-ruby
```

### Usage

```ruby
require 'promptjoy-ruby'

client = PromptjoyRuby::Client.new('your_api_key')
```

You can find the API you want to interact with by using its URL. You can find the URL in the endpoint field of the API's page:

```ruby
api = client.find_by_api_url('https://api.promptjoy.com/api/id')
```

You can also just find the API by its id:

```ruby
api = client.find('id')
```

To call the API, pass in the data as a Hash:

```ruby
response = api.call({
  key1: 'value1',
  key2: 'value2'
})
```

### Example

The following example uses PromptJoy to build an API that recommends an open-source software package based on a problem to be solved: <https://promptjoy.com/apis/jNqC7A>

```ruby
> require 'promptjoy-ruby'
> client = PromptjoyRuby::Client.new('***********************')
> api = client.find_by_api_url('https://api.promptjoy.com/api/jNqC7A')
> response = api.call({problem: "queue processing in ruby"})
> puts response

{"software"=>"Sidekiq", "reason"=>"Efficient and reliable background processing 
for Ruby", "github_url"=>"https://github.com/mperham/sidekiq"}
```

### Error Handling

If an error occurs during an API call, an instance of PromptjoyRuby::Error is raised with a message indicating the nature of the error.

```ruby
begin
  api.call(some_data)
rescue PromptjoyRuby::Error => e
  puts "An error occurred: #{e.message}"
end
```


# Ruby on Rails

In a Rails application, you might want to wrap the API call into a service object for better organization and reusability. Here's how you can do it:

First, create a new file under `app/services` directory (you might need to create this directory if it doesn't exist yet), named `book_search_service.rb` and put the following code into it:

```ruby
class BookSearchService
  require 'net/http'
  require 'uri'
  require 'json'

  def self.search(query)
    uri = URI.parse("https://api.promptjoy.com/api/mVMCpq")
    request = Net::HTTP::Post.new(uri)
    request["Content-Type"] = "application/json"
    request["X-Api-Key"] = ENV['PROMPTJOY_API_KEY']
    request.body = JSON.dump({
      "query" => query
    })

    req_options = {
      use_ssl: uri.scheme == "https",
    }

    response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
      http.request(request)
    end

    if response.code == '200'
      return JSON.parse(response.body)
    else
      raise "HTTP Request Failed with code #{response.code}"
    end
  end
end

```

Then, in your controller, you can use this service to search for a book as follows:

```ruby
class BooksController < ApplicationController
  def search
    query = params[:query]
    @search_results = BookSearchService.search(query)
    render json: @search_results
  end
end

```

In this example, the search term is expected to be passed as a parameter named `query` in the request to the `search` action of `BooksController`. The search results are then returned as a JSON response.

This example uses Net::HTTP, which is part of Ruby's standard library. If you're more comfortable with another HTTP library like `httparty` or `rest-client`, feel free to use that instead.

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.

\
\
\ <br>


# Rust

In Rust, we'll use the `reqwest` library to send HTTP requests. Here's how you can use the book search API with Rust:

First, add the following dependencies in your `Cargo.toml` file:

```rust
[dependencies]
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

```

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

```rust
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use serde::Deserialize;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Deserialize)]
    struct Book {
        title: String,
        author: String,
    }

    let url = "https://api.promptjoy.com/api/mVMCpq";
    let api_key = env::var("PROMPTJOY_API_KEY").unwrap();
    let mut headers = HeaderMap::new();
    headers.insert("x-api-key", HeaderValue::from_str(&api_key).unwrap());
    headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));

    let client = reqwest::Client::new();
    let res = client.post(url)
        .headers(headers)
        .json(&serde_json::json!({"query": "your_search_term"}))
        .send()
        .await?;

    let books: Vec<Book> = res.json().await?;
    for book in books {
        println!("Title: {}, Author: {}", book.title, book.author);
    }

    Ok(())
}

```

\
Replace `"your_search_term"` with the book you're searching for. This function will return a vector of books.

Remember to handle exceptions and errors as needed in your actual application code.

Note: This example uses the `serde` and `serde_json` crates for deserialization of the JSON response. The `tokio` crate is used as the async runtime. Also, 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.

\
\ <br>


# 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:

```typescript
interface Book {
    title: string;
    author: string;
}

```

Next, write the `searchBook` function using async/await:

```typescript
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:

```typescript
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.

\
\
\
\ <br>


# Data Transformation/Enrichment

## The Need

Imagine you've conducted a large-scale survey as part of your market research or customer feedback initiatives. The survey responses contain a wealth of information including the names and email addresses of potential customers, as well as their job titles. This is an invaluable resource for your sales and marketing teams, as these contacts could be potential sales leads.

However, the raw survey data is not readily usable. The data is unstructured and the relevant information - such as names, email addresses, and job titles - is mixed in with other less pertinent details. Furthermore, the job titles provided in the survey data are often in various formats and styles, and don't readily indicate the seniority level or the specific role of the contact.

To effectively utilize this data, you need to transform and classify the data into a structured format that can be easily imported into your CRM or sales prospecting system. The transformed data will give your sales team direct insights into each lead's name, company, industry, and job role, enabling them to tailor their sales pitches and outreach efforts more effectively.

The task of transforming and classifying this data manually would be a time-consuming process and is prone to errors. Automating this process would not only save time and resources but would also increase the accuracy of the data classification. That's where PromptJoy comes in.

### The Solution with PromptJoy

PromptJoy provides a simple yet powerful solution to this problem. By creating an API using the PromptJoy platform, you can automate the process of transforming your survey data into a format that your CRM can ingest. Not only can PromptJoy handle schema transformation, but it can also perform tasks like extracting the company name and industry from an email address and classifying job titles, all within the same API.

As an example, <https://preview.promptjoy.com/apis/jn8Cep> can be created with the simple prompt of "Given the original schema, transform it into the desired output. Please figure out the company name and industry from the email address. Please classify the job title appropriately. Use knowledge about the company and industry to inform the job title classification." By providing the expected input schema and the desired output schema, the API can now be used for the transformation.

### Example: Using the Schema Transformation API

The Schema Transformation API takes an input JSON object with fields for `name`, `email_address`, and `job_title`. Here's an example of an input object:

{% code overflow="wrap" %}

```json

{
  "name": "John Doe",
  "email_address": "[email protected]",
  "job_title": "Managing Director, Investment Banking"
}
```

{% endcode %}

The API transforms this input into a more detailed and structured format that's suitable for a CRM system. The output includes fields for `contact_id`, `name`, `contact_info` (which includes the `email`), `company` (which includes the `name`, `size`, and `industry`), and `job` (which includes the `title`, `role`, and `function`).

{% code overflow="wrap" %}

```json
{
  "name": {
    "first": "John",
    "last": "Doe"
  },
  "contact_info": {
    "email": "[email protected]",

  },
  "company": {
    "name": "The Goldman Sachs Group",
    "size": "Large",
    "industry": "Financial Services",
  },
  "job": {
    "title": "Managing Director",
    "role": "Management",
    "function": "Investment Banking",
  }
}

```

{% endcode %}

Harnessing the  power of large language models (LLMs), the PromptJoy API offers an intuitive way to extract and classify crucial information from the raw data. With just an email address and job title, the API is able to infer pertinent details such as the name, size, and industry of the associated company, as well as classify the job function and level of seniority.&#x20;

However, it's important to note that while powerful, LLMs are not infallible. They can sometimes generate ("hallucinate") inaccurate information or use outdated data. This is particularly the case when dealing with precise numerical data such as exact company revenue. So we recommend using categories (`industry`, `size`) for enrichment usage. &#x20;

PromptJoy is actively developing a *hallucination checking API*. This tool aims to ensure higher accuracy by cross-verifying the inferences made by the LLM. It will make the use of LLMs even more reliable and effective in data transformation tasks.<br>

### Using the API in Bulk

To use this API in bulk, you can send a POST request to the API endpoint with an array of input objects in the request body. The API will process each object in the array and return an array of transformed objects.

The specific implementation would depend on your programming language of choice and your HTTP client library. However, the general process is the same: construct an HTTP POST request with the array of input objects in the request body, send the request to the API endpoint, and handle the response.

### What This Replaces

Using PromptJoy's Schema Transformation API can replace several parts of your existing data pipeline:

* **DBT (Data Build Tool)**: DBT is a tool for transforming data in your warehouse. While DBT is powerful, it requires writing SQL and Jinja scripts. In contrast, PromptJoy abstracts away these complexities behind a simple API.
* **Rule-Based Classifiers**: If you're currently using rule-based classifiers to classify job titles or extract company information, the Schema Transformation API can do this automatically, reducing the need for manual rule creation and maintenance.
* **Clearbit**: Clearbit is a data enrichment tool that can provide company information from an email address. However, it's a separate service with its own cost. PromptJoy can extract company information as part of the schema transformation, eliminating the need for a separate Clearbit integration.
* **In-House AI Models**: If you've built in-house AI models to classify job titles or extract company information, you can replace them with the Schema Transformation API. This can reduce the cost and complexity of maintaining your own models and allow you to focus on your core business.

Remember that each business case is unique, and while PromptJoy provides a powerful and easy-to-use solution, it's essential to evaluate it in the context of your specific needs and existing systems. The Schema Transformation API is highly flexible and can be used in a wide range of scenarios, but it's always a good idea to test it thoroughly with your data and use case.

In conclusion, the Schema Transformation API from PromptJoy can simplify and automate the process of transforming and classifying data, making it a great tool for any data-intensive business. Happy data wrangling!


# Building A Book Search Engine with PromptJoy and Next.js

In this tutorial, we are going to build a book search engine using Next.js, an open-source development framework built on top of Node.js. We'll be leveraging two APIs provided by PromptJoy: the Book Search API and the Book Summary API. These APIs will allow our search engine to retrieve book results based on user queries and provide a detailed summary for each book.

One of the exciting features of PromptJoy is that you can create your own APIs to customize the functionality of your search engine. For instance, you could create APIs for searching and summarizing different types of content like movies, songs, recipes, etc.

PromptJoy APIs

1. **Book Search API**: This API (<https://preview.promptjoy.com/apis/mVMCpq>) acts as a book search engine. When provided with a query, it returns 3 book results that match the query. Each result includes the title and author of a book.
   * **Endpoint**: `https://api.promptjoy.com/api/mVMCpq`
   * **Method**: `POST`
   * **API Key**: You need to include your unique API key in the request header to authenticate your requests. We'll discuss how to set this up later in the tutorial.
2. **Book Summary API**: This API (<https://preview.promptjoy.com/apis/jJbC2p>) acts as a book database. When given the title and author of a book, it returns a detailed summary of the book.
   * **Endpoint**: `https://api.promptjoy.com/api/jJbC2p`
   * **Method**: `POST`
   * **API Key**: You need to include your unique API key in the request header to authenticate your requests.

### Project Setup

First, let's create a new Next.js application. We are using Next.js version 12 in this tutorial. You can do this by running the following command in your terminal:

{% code overflow="wrap" %}

```bash
npx create-next-app@12 book-search-engine
```

{% endcode %}

Then, navigate into your new project directory:

{% code overflow="wrap" %}

```bash
cd book-search-engine
```

{% endcode %}

Next, install the necessary dependencies. We will be using axios for making HTTP requests and react-spinners for displaying a loading spinner:

{% code overflow="wrap" %}

```bash
npm install axios react-spinners @emotion/react @emotion/styled
```

{% endcode %}

### Creating the Search Engine

Now, let's create our book search engine. We'll need to create a form for users to enter their search queries, a component to display the search results, and a function to handle the search.

In your `pages` directory, create a new file called `index.js` and copy the following code:

```jsx
import React, { useState } from 'react';
import axios from 'axios';
import { css } from "@emotion/react";
import { BeatLoader } from "react-spinners";

const override = css`
  display: block;
  margin: 0 auto;
  border-color: red;
`;

function Book({book, onClick}) {
  return (
    <div className="p-4 bg-white rounded-lg shadow-md mt-5">
      <h2 className="text-blue-500 cursor-pointer" onClick={() => onClick(book)}>{book.title}</h2>
      <h3 className="text-gray-700">{book.author}</h3>
    </div>
  )
}

export default function Home() {
  const [books, setBooks] = useState([]);
  const [query, setQuery] = useState('');
  const [loading, setLoading] = useState(false);
  const [loadingSummary, setLoadingSummary] = useState(false);

  const searchBooks = async (event) => {
    event.preventDefault();
    setLoading(true);
    const response = await axios.post(
      'https://api.promptjoy.com/api/mVMCpq',
      { query },
      {
        headers: {
         'Content-Type': 'application/json',
          'x-api-key': process.env.PROMPTJOY_API_KEY,
        },
      }
    );
    setBooks(response.data);
    setLoading(false);
  };

  const fetchSummary = async (book) => {
    setLoadingSummary(true);
    const response = await axios.post(
      'https://api.promptjoy.com/api/jJbC2p',
      { title: book.title, author: book.author },
      {
        headers: {
          'Content-Type': 'application/json',
          'x-api-key': process.env.PROMPTJOY_API_KEY,
        },
      }
    );
    alert(response.data.summary);
    setLoadingSummary(false);
  };

  return (
    <div className="container mx-auto px-4 py-5">
      <h1 className="text-3xl font-semibold text-center mb-5">Book Search Engine</h1>
      <form className="w-full max-w-md mx-auto" onSubmit={searchBooks}>
        <input
          type="text"
          className="w-full shadow border rounded py-2 px-3 mb-5 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
          id="query"
          placeholder="Search for books..."
          value={query}
          onChange={e => setQuery(e.target.value)}
        />
        <button
          className="w-full bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
          type="submit"
        >
          Search
        </button>
        <div className="mt-2">
          {loading && <BeatLoader color={"#123abc"} loading={loading} css={override} size={15} />}
          {loadingSummary && <BeatLoader color={"#123abc"} loading={loadingSummary} css={override} size={15} />}
        </div>
      </form>
      <div className="mt-5">
        {books.map((book, index) => (
          <Book key={index} book={book} onClick={fetchSummary} />
        ))}
      </div>
    </div>
  );
}

```

In this code, we have a `Home` component which acts as the main page of our application. Inside this component, we have a form that takes in a search query from the user. When the form is submitted, it triggers the `searchBooks` function which makes a request to the Book Search API with the provided query, retrieves the results, and sets them in the `books` state.

The `books` state is then mapped to our `Book` component which displays each book title and author. The title of the book is clickable, and when clicked, it triggers the `fetchSummary` function. This function makes a request to the Book Summary API with the book title and author, retrieves the book summary, and displays it in an alert.

Finally, we have a loading spinner that displays while the requests to the APIs are being processed. The spinner is centered under the search button and will disappear once the requests are complete.

### Deploying to Vercel

Deploying your Next.js application to Vercel is straightforward. First, you need to push your application to a GitHub repository. Then, go to [Vercel](https://vercel.com/), sign up for a new account or log in to your existing one, and import your GitHub repository. Vercel will automatically detect that your application is a Next.js app and will provide sensible default configurations.

Lastly, you'll need to set your PromptJoy API key as an environment variable in Vercel. You can do this by going to your project settings, thento the "Environment Variables" section, and adding a new variable with the name `PROMPTJOY_API_KEY` and the value being your actual API key.

Once that's done, click "Deploy", and Vercel will automatically build and deploy your application.

And there you have it! You've built a book search engine using Next.js and PromptJoy. This is just the beginning, though. The great thing about PromptJoy is that you can build your own APIs to create a search engine that's perfectly tailored to your needs. Whether you want to search for books, movies, music, or anything else, you can create an API for it and integrate it into your search engine.

Remember to secure your API keys and to regularly update your application to ensure its security and performance. Happy coding!

\
\
\
\
\
\ <br>


# Internal Data Sources

To integrate your internal data sources to PromptJoy, please contact us at <team@promptjoy.com> and we will work with you on leveraging your internal data securely with our platform.


