DEV Community

Cover image for Introducing JSON Schema for codehooks.io backend collections
Jbee - codehooks.io
Jbee - codehooks.io

Posted on

Introducing JSON Schema for codehooks.io backend collections

In today's fast-paced digital environment, having a reliable backend for applications is crucial. A good datastore ensures data integrity, security, and scalability, which are vital for both business and user experiences. Codehooks.io provides a solid solution with its Datastore, JSON schema support, and a MongoDB-like NoSQL API. This platform helps maintain data consistency and validation and offers a REST API secured with API tokens and JWKS for user authentication.

Why a Solid and Consistent Datastore Backend is Essential

A well-structured NoSQL datastore backend is the backbone of any application. It ensures:

  1. Data Integrity: All data is validated against defined JSON Schemas, reducing the risk of corrupt or malformed data.
  2. Security: Sensitive data is protected through robust authentication and authorization mechanisms.
  3. Scalability: The system can handle increasing loads, ensuring performance remains stable as the application grows.
  4. Flexibility: Ready-made REST APIs allow for seamless integration with various clients and services.

Follow the next 4 simple steps to learn how to build your own Datastore.

Step 1: Setting Up Codehooks.io

First, you'll need to sign up for an account on Codehooks.io if you haven't already. Once signed in, install the Codehooks CLI to manage your projects efficiently.

npm install -g codehooks
Enter fullscreen mode Exit fullscreen mode

Next, log in to your account.

codehooks login
Enter fullscreen mode Exit fullscreen mode

Then create a local directory for your project files.

mkdir myproject
cd myproject
codehooks init
Enter fullscreen mode Exit fullscreen mode

Find the avaliable HTTP endpoint addresses for your project.

codehooks info
Enter fullscreen mode Exit fullscreen mode

In my example this outputs something like this.

Project name: myproject-24ej
Team: codehooks 

API endpoints: 

https://mighty-frog-14a0.codehooks.io
https://myproject-24ej.api.codehooks.io/dev
Enter fullscreen mode Exit fullscreen mode

Step 2: Defining Your JSON Schema

To ensure your data is consistent and secure, you can define a JSON Schema for your collections. This schema will validate the data structure and enforce data types.

Create a schema file (e.g., personSchema.json) defining the structure of your data:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Person",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string",
      "description": "The person's first name."
    },
    "lastName": {
      "type": "string",
      "description": "The person's last name."
    },
    "age": {
      "type": "integer",
      "description": "The person's age.",
      "minimum": 0
    },
    "email": {
      "type": "string",
      "format": "email",
      "description": "The person's email address."
    },
  },
  "required": [
    "firstName",
    "lastName",
    "email"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Use the CLI to add this JSON Schema to your collection:

codehooks add-schema --collection 'person' --schema './personSchema.json'
Enter fullscreen mode Exit fullscreen mode

This command applies the schema to the specified collection, ensuring all future data adheres to this structure.

Step 3: Importing Your Data

Codehooks.io allows you to import data from various formats such as JSON, Excel, or CSV. For this example, we'll import a JSON file containing sample data for our web application.

Importing JSON Data

Prepare your JSON file (e.g., persondata.json) with the data you want to import. Then use the CLI to import this data into your Codehooks NoSQL Datastore.

codehooks import --filepath './persondata.json' --collection 'person'
Enter fullscreen mode Exit fullscreen mode

This command uploads your JSON data to Codehooks, creating a new collection in the process.

Step 4: Utilizing the Ready-Made REST API

Codehooks.io provides a robust, ready-made REST API to interact with your NoSQL datastore, making it easy to perform CRUD (Create, Read, Update, Delete) operations on your data. This JavaScript database API is secured with API tokens for machine-to-machine integration and supports JWKS for flexible user authentication.

Creating a Record

To add a new record to your collection, use the following REST API call with fetch:

const newRecord = {
  firstName: "John",
  lastName: "Doe",
  email: "john.doe@example.com",
  age: 30
};

fetch('https://mighty-frog-14a0.codehooks.io/person', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_JWT_TOKEN'
  },
  body: JSON.stringify(newRecord)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

JSON-Schema validation

In the event that clients sends data not following the JSON-Schema, a validator error will be returned.
E.g. when a client posts a JSON object missing a required field a validator HTTP status 400 error object will be returned.

{
    "schemaError": [
        {
            "instancePath": "",
            "schemaPath": "#/required",
            "keyword": "required",
            "params": {
                "missingProperty": "firstName"
            },
            "message": "must have required property 'firstName'"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Reading Records

To fetch records from your collection, use a GET request with fetch:

fetch('https://mighty-frog-14a0.codehooks.io/person', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer YOUR_JWT_TOKEN'
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

Updating a Record

To update an existing record, specify the record ID and the fields to update, This example will fail due to the requirements in the JSON-schema:

const updatedRecord = {
  firstName: "Jill",
  lastName: "Doe",
  email: "jill.doe@example.com",
  age: 29
};

fetch('https://mighty-frog-14a0.codehooks.io/person/record-id', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_JWT_TOKEN'
  },
  body: JSON.stringify(updatedRecord)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

Deleting a Record

To delete a record, use the record ID in a DELETE request:

fetch('https://mighty-frog-14a0.codehooks.io/person/record-id', {
  method: 'DELETE',
  headers: {
    'Authorization': 'Bearer YOUR_JWT_TOKEN'
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

Codehooks.io Studio

While the Codehooks CLI is designed for automation and efficiency, Codehooks.io also provides a user-friendly interface - Codehooks Studio. This makes it easy to manage your database, import data, and define data schemas. The intuitive dashboard allows you to visualize your data, perform CRUD operations, and configure settings without writing any code. This flexibility ensures that both developers and non-developers can manage the backend seamlessly.

Conclusion

By leveraging the new JSON Schema support in Codehooks.io, you can ensure that your backend data is consistently validated and well-structured. This powerful feature, combined with Codehooks.io's NoSQL Datastore and ready-made REST API, provides a robust and efficient foundation for any modern application. These tools make your data fast, secure, and consistent, allowing you to focus on building great features and enhancing user experience.

Start today and see how Codehooks.io's JSON Schema support can streamline your backend development process 🚀

Links for Further Reading

Introduction to NoSQL Databases

  • Learn about the different types of NoSQL databases and their use cases.

Understanding JSON Schema

  • A comprehensive guide to defining and using JSON Schemas for data validation.

RESTful API Design Best Practices

  • Explore best practices for designing and using RESTful APIs.

JavaScript Fetch API

  • Official documentation and examples for using the Fetch API in JavaScript to make HTTP requests.

Securing APIs with JWT

  • Understand how to secure your APIs using JSON Web Tokens (JWT).

Codehooks.io Documentation
- Official documentation for Codehooks.io, covering all features and functionalities.

Top comments (0)