Introduction

Overview of the Client Library

The client library for our API is a Go package that simplifies the process of interacting with the API, providing a set of easy-to-use functions to perform common tasks such as creating, updating, and querying data. The library abstracts away the low-level details of HTTP requests and responses, allowing developers to focus on building their applications.

Purpose and Benefits

The primary purpose of the client library is to make it more efficient and convenient for developers to interact with the API. By using the client library, developers can:

  • Reduce the amount of boilerplate code needed to work with the API
  • Handle errors and edge cases more easily
  • Improve code readability and maintainability

In addition, the client library aims to provide a consistent and idiomatic interface that aligns with the best practices of the Go programming language, further enhancing the developer experience.

API Version and Compatibility

The client library is compatible with version 1 of the API, as indicated by the /v1/ prefix in the API endpoints. As the API evolves, future versions of the client library will be released to maintain compatibility and provide access to new features.

It is recommended to always use the latest version of the client library to ensure compatibility with the latest features and improvements in the API. However, the library is designed to be backward compatible, so that existing code using older versions of the library should continue to work without modifications when updating the library version.

Requirements and Dependencies

To use the client library, you must have the following:

  • Go 1.15 or later
  • An active API key for authentication (if applicable)

The client library has minimal dependencies, which are managed using Go modules. When you import the library into your project, the Go toolchain will automatically handle downloading and installing the required dependencies.

Getting Started

This section will guide you through installing the client library, setting up authentication, creating a client instance, and providing basic usage examples in JavaScript, cURL, and Go.

Installation

To install the client library, use the go get command:

go get -u github.com/example/client-library-go

Authentication and Authorization (if applicable)

If the API requires an API key for authentication, you'll need to obtain one from the API provider. Once you have an API key, you can pass it to the client library when creating a client instance.

JavaScript Example

const apiKey = 'your-api-key';

cURL Example

export API_KEY='your-api-key'

Go Example

apiKey := "your-api-key"

Creating a Client Instance

To interact with the API, you'll need to create a client instance. The client instance allows you to configure settings, such as the API key and base URL, and provides methods to interact with the API.

JavaScript Example

const Client = require('client-library-go');
const client = new Client(apiKey);

Go Example:

import (
    "github.com/example/client-library-go"
)

client, err := clientlibrary.NewClient(apiKey)
if err != nil {
    log.Fatalf("Error creating client: %v", err)
}

Basic Usage Examples

Here are some basic usage examples to help you get started with the client library.

Creating a Collection

cURL example:

curl -X POST "https://example.com/v1/collections" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-collection"
  }'

Inserting Data

cURL example:

curl -X POST "https://example.com/v1/collections/my-collection:insert" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "1",
    "name": "John Doe"
  }'

Querying Data

cURL example:

curl "https://example.com/v1/collections/my-collection/find?index=my-index&value=1" \
  -H "Authorization: Bearer $API_KEY"

Updating Data

cURL example:

curl -X PATCH "https://example.com/v1/collections/my-collection" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "1",
    "fields": {
      "name": "Jane Doe"
    }
  }'

Deleting Data

cURL example:

curl -X DELETE "https://example.com/v1/collections/my-collection/1" \
  -H "Authorization: Bearer $API_KEY"

Find

Retrieve one or more items from a collection by searching with a specified index and value.

Parameteres

  • collectionName: The name of the collection to search in.
  • query: An object containing the index and value to search for, along with optional limit and skip parameters.

Usage Examples

cURL Example:

curl "https://example.com/v1/collections/my-collection/find?index=my-index&value=John%20Doe&limit=10&skip=0" \
-H "Authorization: Bearer $API_KEY"

Response structure

[
  {
    "id": "1",
    "name": "John Doe",
    "email": "john.doe@example.com"
  },
  {
    "id": "2",
    "name": "John Doe",
    "email": "johndoe@example.org"
  }
]

Insert

Insert one or more items into a collection.

Parameters:

  • collectionName: The name of the collection to insert the items into.
  • items: An array of items to insert into the collection.

Patch

Update one or more fields of an item in a collection.

Parameters:

  • collectionName: The name of the collection to update the item in.
  • id: The ID of the item to update.
  • update: An object containing the fields to update and their new values.

Delete

Delete an item from a collection by its ID.

Parameters:

  • collectionName: The name of the collection to delete the item from.
  • id: The ID of the item to delete.

CreateCollection

Create a new collection.

Parameters:

  • collectionName: The name of the collection to create.

GetCollection

Retrieve the details of a specific collection.

Parameters:

  • collectionName: The name of the collection to retrieve.

ListCollections

Retrieve a list of all collections.

CreateIndex

Create a new index for a collection.

Parameters:

  • collectionName: The name of the collection to create the index for.
  • index: The index configuration object.

ListIndexes

Retrieve a list of all indexes for a collection.

Parameters:

  • collectionName: The name of the collection to list indexes for.

Error Handling

This section covers common error types and best practices for handling errors when working with the API.

Common error types

  • Bad Request (400): The request is malformed, incomplete, or contains invalid data. This usually occurs when required fields are missing, incorrect values are provided, or the data is not formatted properly.
  • Unauthorized (401): The request lacks valid authentication credentials or the provided API key is invalid. Ensure that the API key is correct and passed in the request header.
  • Forbidden (403): The authenticated user does not have the required permissions to perform the requested action. Verify that the user has the necessary permissions to access the requested resource.
  • Not Found (404): The requested resource, such as a collection or an item, could not be found. Ensure that the provided identifiers are correct and the resource exists.
  • Method Not Allowed (405): The request method (GET, POST, PATCH, DELETE) is not supported for the specified endpoint. Check the API documentation for the allowed methods for the endpoint.
  • Internal Server Error (500): An unexpected error occurred on the server while processing the request. This typically indicates an issue with the API itself or its infrastructure.

Error handling best practices

By following these best practices, you can effectively handle errors when working with the API and ensure your application is resilient and informative when encountering issues.

  • Handle specific error types: When handling errors, it's a good practice to handle specific error types explicitly. This allows for better error reporting and handling tailored to each error type.
  • Use retries with exponential backoff: When encountering transient errors, such as network issues or server errors, implement retries with exponential backoff. This strategy helps reduce the load on the server and increases the chances of a successful request.
  • Provide clear error messages: Ensure that error messages are clear and informative, allowing users to understand the cause of the error and how to resolve it.
  • Log errors: Log errors, including request details and response data, to help with debugging and identifying potential issues in your application.
  • Implement fallback mechanisms: In case of errors, implement fallback mechanisms to ensure your application can continue functioning or gracefully degrade its functionality.

Python example:

import requests

try:
    response = requests.post(url, headers=headers, data=json.dumps(data))
    response.raise_for_status()
    print("Data inserted")
except requests.exceptions.HTTPError as e:
    status_code = e.response.status_code
    message = e.response.json().get("message")

    if status_code == 400:
        print(f"Bad Request: {message}")
    elif status_code == 401:
        print(f"Unauthorized: {message}")
    elif status_code == 403:
        print(f"Forbidden: {message}")
    elif status_code == 404:
        print(f"Not Found: {message}")
    elif status_code == 500:
        print(f"Internal Server Error: {message}")
    else:
        print(f"Unexpected error: {e}")
    except requests.exceptions.RequestException as e:
        print(f"Error sending request: {e}")

Contributing

We welcome contributions from the community! If you'd like to contribute to the project, please follow the guidelines below.

Guidelines for submitting issues and pull requests

Submitting Issues

If you encounter a bug, have a feature request, or want to report a problem, please submit an issue on our GitHub repository. When submitting an issue, please include the following information:

  1. A clear and concise title.
  2. A detailed description of the issue or feature request.
  3. Steps to reproduce the issue, if applicable.
  4. Expected behavior and actual behavior.
  5. Additional information, like screenshots or logs, that might help in understanding the issue.

Submitting Pull Requests

We encourage you to submit pull requests with bug fixes, improvements, or new features. To ensure a smooth review process, please follow these guidelines:

  1. Fork the repository and create a new branch for your changes.
  2. Ensure your changes adhere to the code style and conventions of the project.
  3. Add or update tests for your changes and ensure they pass.
  4. Update any relevant documentation to reflect your changes.
  5. Write a detailed description in your pull request, explaining the purpose of your changes and any potential side effects.
  6. Submit your pull request, and wait for a review from the maintainers.

Code style and conventions

Please follow the existing code style and conventions used throughout the project. This includes:

  1. Consistent indentation (e.g., spaces instead of tabs).
  2. Clear and concise variable and function names.
  3. Proper use of comments and documentation.
  4. Adherence to any linting rules or tools used in the project.

Testing and validation

Before submitting your pull request, make sure to test your changes thoroughly. This includes:

  1. Running the existing test suite and ensuring all tests pass.
  2. Adding new tests for your changes, if applicable.
  3. Manually testing your changes in a realistic environment or with real data.
  4. Verifying that your changes do not introduce new issues or negatively impact performance.

By following these guidelines, you can help ensure a smooth review process and contribute to the ongoing success of the project. Thank you for your interest in contributing!

License

This project is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0). This license allows you to use, modify, and distribute the software, as long as you adhere to the terms and conditions specified in the license.

Licensing information

The AGPL-3.0 license ensures that any modifications or improvements made to the project are also released under the same license. This promotes collaboration and the sharing of knowledge within the community.

To read the full text of the AGPL-3.0 license, please visit the GNU Affero General Public License v3.0 webpage.