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:

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:

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.

Last updated