Merge pull request #547 from gilbertoaceville/feat/update-prompts-docs

feat: update prompts docs
pull/552/head
Kye Gomez 5 months ago committed by GitHub
commit e27c6c4efc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -1,34 +1,37 @@
# Documentation for `getAllPrompts` API Endpoint # Documentation for `getAllPrompts` API Endpoint
The `getAllPrompts` API endpoint is a part of the `swarms.world` application, designed to fetch all prompt records from the database. This endpoint is crucial for retrieving various prompts stored in the `swarms_cloud_prompts` table, including their metadata such as name, description, use cases, and tags. It provides an authenticated way to access this data, ensuring that only authorized users can retrieve the information. The `getAllPrompts` API endpoint is a part of the `swarms.world` application, designed to fetch all prompt records from the database. This endpoint is crucial for retrieving various prompts stored in the `swarms_cloud_prompts` table, including their metadata such as name, description, use cases, and tags.
## Purpose ## Purpose
The primary purpose of this API endpoint is to provide a secure method for clients to fetch a list of prompts stored in the `swarms_cloud_prompts` table. It ensures data integrity and security by using an authentication guard and handles various HTTP methods and errors gracefully. The primary purpose of this API endpoint is to provide a method for clients to fetch a list of prompts stored in the `swarms_cloud_prompts` table, with the ability to filter by name, tags, and use cases.
## API Endpoint Definition ## API Endpoint Definition
### Endpoint URL ### Fetch All Prompts
#### Endpoint URL
``` ```
https://swarms.world/get-prompt https://swarms.world/get-prompts
``` ```
### HTTP Method #### HTTP Method
``` ```
GET GET
``` ```
### Request Headers ### Query Parameters
| Header | Type | Required | Description | - **name** (optional): A substring to match against the prompt name. The query is case-insensitive.
|----------------|--------|----------|-----------------------------| - **tag** (optional): A comma-separated list of tags to filter prompts by. The query matches any of the provided tags, and is case-insensitive.
| Authorization | String | Yes | Bearer token for API access | - **use_case** (optional): A substring to match against the use case titles within the `use_cases` array. The query is case-insensitive.
- **use_case_description** (optional): A substring to match against the use case descriptions within the `use_cases` array. The query is case-insensitive.
### Response #### Response
#### Success Response (200) ##### Success Response (200)
Returns an array of prompts. Returns an array of prompts.
@ -39,14 +42,19 @@ Returns an array of prompts.
"name": "string", "name": "string",
"description": "string", "description": "string",
"prompt": "string", "prompt": "string",
"use_cases": "string", "use_cases": [
{
"title": "string",
"description": "string"
}
],
"tags": "string" "tags": "string"
}, },
... ...
] ]
``` ```
#### Error Responses ##### Error Responses
- **405 Method Not Allowed** - **405 Method Not Allowed**
@ -56,11 +64,57 @@ Returns an array of prompts.
} }
``` ```
- **401 Unauthorized** - **500 Internal Server Error**
```json
{
"error": "Could not fetch prompts"
}
```
### Fetch Prompt by ID
#### Endpoint URL
```
https://swarms.world/get-prompts/[id]
```
#### HTTP Method
```
GET
```
#### Response
##### Success Response (200)
Returns a single prompt by ID.
```json
{
"id": "string",
"name": "string",
"description": "string",
"prompt": "string",
"use_cases": [
{
"title": "string",
"description": "string"
}
],
"tags": "string"
}
```
##### Error Responses
- **404 Not Found**
```json ```json
{ {
"error": "API Key is missing" "error": "Prompt not found"
} }
``` ```
@ -68,31 +122,50 @@ Returns an array of prompts.
```json ```json
{ {
"error": "Could not fetch prompts" "error": "Could not fetch prompt"
} }
``` ```
## Request Handling ### Request Handling
1. **Method Validation**: The endpoint only supports the `GET` method. If a different HTTP method is used, it responds with a `405 Method Not Allowed` status. 1. **Method Validation**: The endpoint only supports the `GET` method. If a different HTTP method is used, it responds with a `405 Method Not Allowed` status.
2. **Authentication**: The request must include a valid Bearer token in the `Authorization` header. If the token is missing, a `401 Unauthorized` status is returned.
3. **Authorization Check**: The token is validated using the `AuthApiGuard` class. If the token is invalid, an appropriate error response is returned based on the status received from the guard.
4. **Database Query**: The endpoint queries the `swarms_cloud_prompts` table using the `supabaseAdmin` client to fetch prompt data.
5. **Response**: On success, it returns the prompt data in JSON format. In case of an error during the database query, a `500 Internal Server Error` status is returned.
## Code Example 2. **Database Query**:
- **Fetching All Prompts**: The endpoint uses the `supabaseAdmin` client to query the `swarms_cloud_prompts` table. Filters are applied based on the query parameters (`name`, `tag`, and `use_cases`).
- **Fetching a Prompt by ID**: The endpoint retrieves a single prompt from the `swarms_cloud_prompts` table by its unique ID.
### JavaScript (Node.js) 3. **Response**: On success, it returns the prompt data in JSON format. In case of an error during the database query, a `500 Internal Server Error` status is returned. For fetching by ID, if the prompt is not found, it returns a `404 Not Found` status.
### Code Example
#### JavaScript (Node.js)
```javascript ```javascript
import fetch from 'node-fetch'; import fetch from "node-fetch";
// Fetch all prompts with optional filters
const getPrompts = async (filters) => {
const queryString = new URLSearchParams(filters).toString();
const response = await fetch(
`https://swarms.world/get-prompts?${queryString}`,
{
method: "GET",
}
);
const getPrompts = async () => { if (!response.ok) {
const response = await fetch('https://swarms.world/get-prompt', { throw new Error(`Error: ${response.statusText}`);
method: 'GET',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
} }
const data = await response.json();
console.log(data);
};
// Fetch prompt by ID
const getPromptById = async (id) => {
const response = await fetch(`https://swarms.world/get-prompts/${id}`, {
method: "GET",
}); });
if (!response.ok) { if (!response.ok) {
@ -103,19 +176,24 @@ const getPrompts = async () => {
console.log(data); console.log(data);
}; };
getPrompts().catch(console.error); // Example usage
getPrompts({
name: "example",
tag: "tag1,tag2",
use_case: "example",
use_case_description: "description",
}).catch(console.error);
getPromptById("123").catch(console.error);
``` ```
### Python #### Python
```python ```python
import requests import requests
def get_prompts(): # Fetch all prompts with optional filters
headers = { def get_prompts(filters):
'Authorization': 'Bearer YOUR_API_KEY' response = requests.get('https://swarms.world/get-prompts', params=filters)
}
response = requests.get('https://swarms.world/get-prompt', headers=headers)
if response.status_code != 200: if response.status_code != 200:
raise Exception(f'Error: {response.status_code}, {response.text}') raise Exception(f'Error: {response.status_code}, {response.text}')
@ -123,17 +201,32 @@ def get_prompts():
data = response.json() data = response.json()
print(data) print(data)
get_prompts() # Fetch prompt by ID
def get_prompt_by_id(id):
response = requests.get(f'https://swarms.world/get-prompts/{id}')
if response.status_code != 200:
raise Exception(f'Error: {response.status_code}, {response.text}')
data = response.json()
print(data)
# Example usage
get_prompts({'name': 'example', 'tag': 'tag1,tag2', 'use_case': 'example', 'use_case_description': 'description'})
get_prompt_by_id('123')
``` ```
### cURL #### cURL
```sh ```sh
curl -X GET https://swarms.world/get-prompt \ # Fetch all prompts with optional filters
-H "Authorization: Bearer YOUR_API_KEY" curl -X GET "https://swarms.world/get-prompts?name=example&tag=tag1,tag2&use_case=example&use_case_description=description"
# Fetch prompt by ID
curl -X GET https://swarms.world/get-prompts/123
``` ```
### Go #### Go
```go ```go
package main package main
@ -142,18 +235,39 @@ import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/url"
) )
func getPrompts() { func getPrompts(filters map[string]string) {
client := &http.Client{} baseURL := "https://swarms.world/get-prompts"
req, err := http.NewRequest("GET", "https://swarms.world/get-prompt", nil) query := url.Values{}
for key, value := range filters {
query.Set(key, value)
}
fullURL := fmt.Sprintf("%s?%s", baseURL, query.Encode())
resp, err := http.Get(fullURL)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := ioutil.ReadAll(resp.Body)
panic(fmt.Sprintf("Error: %d, %s", resp.StatusCode, string(body)))
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
panic(err) panic(err)
} }
req.Header.Add("Authorization", "Bearer YOUR_API_KEY") fmt.Println(string(body))
}
resp, err := client.Do(req) func getPromptById(id string) {
url := fmt.Sprintf("https://swarms.world/get-prompts/%s", id)
resp, err := http.Get(url)
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -173,24 +287,30 @@ func getPrompts() {
} }
func main() { func main() {
getPrompts() filters := map[string]string{
"name": "example",
"tag": "tag1,tag2",
"use_case": "example",
"use_case_description": "description",
}
getPrompts(filters)
getPromptById("123")
} }
``` ```
### Attributes Table #### Attributes Table
| Attribute | Type | Description | | Attribute | Type | Description |
|---------------|--------|------------------------------------------------------------| | ----------- | ------ | -------------------------------- |
| id | String | Unique identifier for the prompt | | id | String | Unique identifier for the prompt |
| name | String | Name of the prompt | | name | String | Name of the prompt |
| description | String | Description of the prompt | | description | String | Description of the prompt |
| prompt | String | The actual prompt text | | prompt | String | The actual prompt text |
| use_cases | String | Use cases for the prompt | | use_cases | Array | Use cases for the prompt |
| tags | String | Tags associated with the prompt | | tags | String | Tags associated with the prompt |
## Additional Information and Tips ## Additional Information and Tips
- Ensure your API key is kept secure and not exposed in client-side code.
- Handle different error statuses appropriately to provide clear feedback to users. - Handle different error statuses appropriately to provide clear feedback to users.
- Consider implementing rate limiting and logging for better security and monitoring. - Consider implementing rate limiting and logging for better security and monitoring.

@ -1,9 +1,8 @@
# Prompts API Documentation # Prompts API Documentation
The `https://swarms.world/api/add-prompt` endpoint allows users to add a new prompt to the Swarms platform. This API accepts a POST request with a JSON body containing details of the prompt, such as its name, description, use cases, and tags. The request must be authenticated using an API key. The `https://swarms.world/api/add-prompt` endpoint allows users to add a new prompt to the Swarms platform. This API accepts a POST request with a JSON body containing details of the prompt, such as its name, description, use cases, and tags. The request must be authenticated using an API key.
## Endpoint ## Endpoint: Add Prompt
- **URL:** `https://swarms.world/api/add-prompt` - **URL:** `https://swarms.world/api/add-prompt`
- **Method:** POST - **Method:** POST
@ -15,10 +14,10 @@ The `https://swarms.world/api/add-prompt` endpoint allows users to add a new pro
The request body should be a JSON object with the following attributes: The request body should be a JSON object with the following attributes:
| Attribute | Type | Description | Required | | Attribute | Type | Description | Required |
|-------------|----------|---------------------------------------------------------|----------| | ------------- | -------- | --------------------------------------------------------------- | -------- |
| `name` | `string` | The name of the prompt. | Yes | | `name` | `string` | The name of the prompt. | Yes |
| `prompt` | `string` | The prompt text. | Yes | | `prompt` | `string` | The prompt text. | Yes |
| `description`| `string` | A brief description of the prompt. | Yes | | `description` | `string` | A brief description of the prompt. | Yes |
| `useCases` | `array` | An array of use cases, each containing a title and description. | Yes | | `useCases` | `array` | An array of use cases, each containing a title and description. | Yes |
| `tags` | `string` | Comma-separated tags for the prompt. | No | | `tags` | `string` | Comma-separated tags for the prompt. | No |
@ -27,7 +26,7 @@ The request body should be a JSON object with the following attributes:
Each use case in the `useCases` array should be an object with the following attributes: Each use case in the `useCases` array should be an object with the following attributes:
| Attribute | Type | Description | Required | | Attribute | Type | Description | Required |
|---------------|----------|---------------------------------|----------| | ------------- | -------- | ------------------------------------ | -------- |
| `title` | `string` | The title of the use case. | Yes | | `title` | `string` | The title of the use case. | Yes |
| `description` | `string` | A brief description of the use case. | Yes | | `description` | `string` | A brief description of the use case. | Yes |
@ -62,32 +61,32 @@ print(response.json())
### Node.js ### Node.js
```javascript ```javascript
const fetch = require('node-fetch'); const fetch = require("node-fetch");
async function addPromptsHandler() { async function addPromptsHandler() {
try { try {
const response = await fetch('https://swarms.world/api/add-prompt', { const response = await fetch("https://swarms.world/api/add-prompt", {
method: 'POST', method: "POST",
headers: { headers: {
'Content-Type': 'application/json', "Content-Type": "application/json",
'Authorization': 'Bearer {apiKey}' Authorization: "Bearer {apiKey}",
}, },
body: JSON.stringify({ body: JSON.stringify({
name: 'Example Prompt', name: "Example Prompt",
prompt: 'This is an example prompt from an API route.', prompt: "This is an example prompt from an API route.",
description: 'Description of the prompt.', description: "Description of the prompt.",
useCases: [ useCases: [
{ title: 'Use case 1', description: 'Description of use case 1' }, { title: "Use case 1", description: "Description of use case 1" },
{ title: 'Use case 2', description: 'Description of use case 2' } { title: "Use case 2", description: "Description of use case 2" },
], ],
tags: 'example, prompt' tags: "example, prompt",
}) }),
}); });
const result = await response.json(); const result = await response.json();
console.log(result); console.log(result);
} catch (error) { } catch (error) {
console.error('An error has occurred', error); console.error("An error has occurred", error);
} }
} }
@ -178,6 +177,202 @@ The response will be a JSON object containing the result of the operation. Examp
} }
``` ```
# Endpoint: Edit Prompt
The `https://swarms.world/api/edit-prompt` endpoint allows users to edit an existing prompt on the Swarms platform. This API accepts a POST request with a JSON body containing the prompt details to be updated, such as its name, description, use cases, and tags. The request must be authenticated using an API key.
## Endpoint
- **URL:** `https://swarms.world/api/edit-prompt`
- **Method:** POST
- **Content-Type:** `application/json`
- **Authorization:** Bearer token required in the header
## Request Parameters
The request body should be a JSON object with the following attributes:
| Attribute | Type | Description | Required |
| ------------- | -------- | --------------------------------------------------------------- | -------- |
| `id` | `string` | The ID of the prompt to be edited. | Yes |
| `name` | `string` | The name of the prompt. | Yes |
| `prompt` | `string` | The prompt text. | Yes |
| `description` | `string` | A brief description of the prompt. | No |
| `useCases` | `array` | An array of use cases, each containing a title and description. | Yes |
| `tags` | `string` | Comma-separated tags for the prompt. | No |
### `useCases` Structure
Each use case in the `useCases` array should be an object with the following attributes:
| Attribute | Type | Description | Required |
| ------------- | -------- | ------------------------------------ | -------- |
| `title` | `string` | The title of the use case. | Yes |
| `description` | `string` | A brief description of the use case. | Yes |
## Example Usage
### Python
```python
import requests
import json
url = "https://swarms.world/api/edit-prompt"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer {apiKey}"
}
data = {
"id": "prompt_id",
"name": "Updated Prompt",
"prompt": "This is an updated prompt from an API route.",
"description": "Updated description of the prompt.",
"useCases": [
{"title": "Updated use case 1", "description": "Updated description of use case 1"},
{"title": "Updated use case 2", "description": "Updated description of use case 2"}
],
"tags": "updated, prompt"
}
response = requests.post(url, headers=headers, data=json.dumps(data))
print(response.json())
```
### Node.js
```javascript
const fetch = require("node-fetch");
async function editPromptsHandler() {
try {
const response = await fetch("https://swarms.world/api/edit-prompt", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer {apiKey}",
},
body: JSON.stringify({
id: "prompt_id",
name: "Updated Prompt",
prompt: "This is an updated prompt from an API route.",
description: "Updated description of the prompt.",
useCases: [
{
title: "Updated use case 1",
description: "Updated description of use case 1",
},
{
title: "Updated use case 2",
description: "Updated description of use case 2",
},
],
tags: "updated, prompt",
}),
});
const result = await response.json();
console.log(result);
} catch (error) {
console.error("An error has occurred", error);
}
}
editPromptsHandler();
```
### Go
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func main() {
url := "https://swarms.world/api/edit-prompt"
payload := map[string]interface{}{
"id": "prompt_id",
"name": "Updated Prompt",
"prompt": "This is an updated prompt from an API route.",
"description": "Updated description of the prompt.",
"useCases": []map[string]string{
{"title": "Updated use case 1", "description": "Updated description of use case 1"},
{"title": "Updated use case 2", "description": "Updated description of use case 2"},
},
"tags": "updated, prompt",
}
jsonPayload, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer {apiKey}")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("An error has occurred", err)
return
}
defer resp.Body.Close()
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
fmt.Println(result)
}
```
### cURL
```bash
curl -X POST https://swarms.world/api/edit-prompt \
-H "Content-Type: application/json" \
-H "Authorization: Bearer {apiKey}" \
-d '{
"id": "prompt_id",
"name": "Updated Prompt",
"prompt": "This is an updated prompt from an API route.",
"description": "Updated description of the prompt.",
"useCases": [
{ "title": "Updated use case 1", "description": "Updated description of use case 1" },
{ "title": "Updated use case 2", "description": "Updated description of use case 2" }
],
"tags": "updated, prompt"
}'
```
## Response
The response will be a JSON object containing the result of the operation. Example response:
```json
{
"success": true,
"message": "Prompt updated successfully",
"data": {
"id": "prompt_id",
"name": "Updated Prompt",
"prompt": "This is an updated prompt from an API route.",
"description": "Updated description of the prompt.",
"useCases": [
{
"title": "Updated use case 1",
"description": "Updated description of use case 1"
},
{
"title": "Updated use case 2",
"description": "Updated description of use case 2"
}
],
"tags": "updated, prompt"
}
}
```
In case of an error, the response will contain an error message detailing the issue. In case of an error, the response will contain an error message detailing the issue.
## Common Issues and Tips ## Common Issues and Tips
@ -195,4 +390,4 @@ In case of an error, the response will contain an error message detailing the is
- [Requests Library (Python)](https://requests.readthedocs.io/) - [Requests Library (Python)](https://requests.readthedocs.io/)
- [Net/HTTP Package (Go)](https://pkg.go.dev/net/http) - [Net/HTTP Package (Go)](https://pkg.go.dev/net/http)
This comprehensive documentation provides all the necessary information to effectively use the `https://swarms.world/api/add-prompt` endpoint, including details on request parameters, example code snippets in multiple programming languages, and troubleshooting tips. This comprehensive documentation provides all the necessary information to effectively use the `https://swarms.world/api/add-prompt` and `https://swarms.world/api/edit-prompt` endpoints, including details on request parameters, example code snippets in multiple programming languages, and troubleshooting tips.

Loading…
Cancel
Save