> This is part 1 of 2 of the full documentation (pages 1–100 of 114).
> The content is paginated: fetch every part to see all of it.
> Next part: https://docs.neurelo.com/llms-full.txt/1
> Page index: https://docs.neurelo.com/llms.txt

# Introduction

## Overview - Neurelo Cloud Data API Platform

Modern applications require a different approach to programming with data. Imagine not just writing less and better code faster, but also seamlessly scaling, securing and optimizing your queries with complete visibility and control. Neurelo simplifies the development process, empowering developers to achieve measurable productivity gains by eliminating the complexities associated with database programming.

Neurelo is a Cloud Data API Platform for developers. Cloud Data APIs (Application Programming Interfaces) refer to an interface that allows applications to interact with and access data from data sources such as databases. Cloud Data APIs enable seamless communication between applications and data sources, allowing for the retrieval, manipulation, and management of data over the network.

This approach allows developers to integrate various functionalities and services into their applications without the need to manage the underlying infrastructure, while offering several advantages including scalability, options to securely access the data with different deployment strategies, and the ability to collaborate on and extend data in their data sources.&#x20;

## How Neurelo Works

Neurelo auto-generates a rich set of APIs, in [REST/JSON](/neurelo-api-reference-rest) and [GraphQL](/neurelo-api-reference-graphql) formats, that are purpose built based on application's data models. These APIs are instantly generated, comprehensively documented, and version controlled.&#x20;

With Neurelo, developers build their applications by using Data APIs for all their read and write operations with databases such as PostgreSQL, MySQL, and MongoDB. Instead of running on a local server or infrastructure, these APIs are automatically deployed and managed on Neurelo's Cloud Platform.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fk0Cu1OljzFhA5CsvukjW%2Fframe.png?alt=media&amp;token=3c920912-70e7-47f3-9875-251f9e6ba52c" alt=""><figcaption></figcaption></figure>


# Core Concepts

This is the guide for the vocabulary and key concepts used in Neurelo to help with building a strong understanding of Neurelo's features and capabilities.

### Cloud Data APIs

Cloud Data APIs (Application Programming Interfaces) refer to an interface that allows applications to interact with and access data from data sources such as databases. Cloud Data APIs enable seamless communication between applications and data sources, allowing for the retrieval, manipulation, and management of data over the network.

Neurelo supports REST and GraphQL API protocols. Instead of running on a local server or infrastructure, these APIs are automatically deployed and managed on Neurelo's Cloud Platform.

This approach allows developers to integrate various functionalities and services into their applications without the need to manage the underlying infrastructure, while offering several advantages including scalability, options to securely access the data with different deployment strategies and the ability to collaborate on and extend data in their data sources.&#x20;

### Neurelo Information Architecture

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FbjiUMUvBPj6s96yHxjWP%2Fimage.png?alt=media&amp;token=0e38f173-9478-45ff-bcf2-7919aa8b484a" alt=""><figcaption></figcaption></figure>

### Organizations

A company or a large division within a company would be an organization in Neurelo. Organization is the highest level entity in the Neurelo information hierarchy. Every Neurelo account belongs to one or more organizations.&#x20;

### Members

A team member is an individual who is part of a group or team, collaborating with others to achieve common goals or objectives. A member belongs inside an organization. Every member in Neurelo has their own Neurelo account.

### Projects

A project is an application (or software or workload) that developers build and run with Neurelo. A project can be a front-end application, back-end application, a monolith or a micro-service, etc. A project is the primary “working” entity where all things start inside Neurelo. A project would exist inside an Organization and has its own set of entities such as dashboards, data definitions, environments, data sources, etc. that belong to that project. &#x20;

### Data sources

A database such as PostgreSQL, MongoDB, MySQL. One ore more data sources can be added to projects inside Neurelo. Data sources can include cloud-provider databases (e.g. AWS RDS, Aiven, MongoDB Atlas, etc.), self-managed instances, and local databases

### Data Definitions

Neurelo's data definition comprises of three key elements - Schema, Auto-Generated APIs and Custom Queries. Definitions exist inside a project and are scoped to that particular project. Different projects will have their own definitions.

### Schemas

Neurelo Schema is the representation of data models that define the shape and structure of the data for applications. Schema captures different characteristics of data such as the name of data field (label), type of data field (integer, string, datetime), what can be done with that data (read, write), relationships across data, and more.

Neurelo Schema supports both Visual (Schema Builder) and codified (JSON and YAML) editing experiences and provides Git-like branches, commits and version control for the definitions.&#x20;

### Auto-Generated APIs and API Docs

Neurelo instantly generates Data APIs in both REST and GraphQL formats from the specified schema (data model). These APIs efficiently manage a large spectrum of operations encompassing Create, Read, Update, and Delete (CRUD) functionalities across individual entities (Tables/Collections) as well as handling JOIN queries across multiple entities against the underlying database. Neurelo offers comprehensive API documentation and version control that further enhance the ability to collaborate across building an application, and the accessibility and maintainability of these APIs.

### Custom Queries

A custom query refers to User-Defined complex query for retrieving or updating specific information from the database. These queries are typically used for very advanced data operations and may involve multiple criteria, conditions, or operations to extract specific and nuanced information from the database, beyond what can be done with the auto-generated APIs.&#x20;

Neurelo offers users the ability to write and test custom queries against their data sources in a project and to create API endpoints from these custom queries. This capability allows users to extend Neurelo's APIs and to have complete flexibility to query and update the data from their data sources.&#x20;

### Environments

An environment is a run-time workspace that allows users to run their Neurelo APIs using a specific version (commit), of their definitions and custom queries, against a specific data source. Neurelo environments are built to be naturally aligned to typical Software Development LifeCycles (SDLCs) as applications are developed, tested, deployed, and operated. This encompasses various stages, including:

1. **Development (Dev) Environments:** Environments in which developers build, extend, and debug code.
2. **Test Environments:** Typically a separate environment where software is tested. This includes environments which be run as part of pipelines, regression test suites, continuous test environments, performance tests, long running tests, etc.&#x20;
3. **Staging Environments:** A pre-production environment where the software is deployed for final validations before release.
4. **Production Environments:** The final live environment where the application is deployed for end-users.

### Runners

A runner in Neurelo is the main component that executes and manages all API calls. In Neurelo's Cloud Data Access Platform, a runner is a part of every environment inside a project. Runners need to be started for the application to be able to handle API requests and process them against the configured data source within an environment.&#x20;


# Key Features

Neurelo's Cloud Data Access Platform simplifies different aspects of database programming, and running and scaling for modern applications. It enables teams to write less but better code, more efficiently, and enables queries to be managed, debugged, scaled, secured, and optimized effortlessly.&#x20;

Key features of Neurelo include -

### **Auto-Generated APIs**

Neurelo's Auto-Generated APIs significantly streamline the way developers interact with data in their datasources. This key feature automatically generates both REST and GraphQL endpoints directly from users data models and schemas. These endpoints are designed for a wide range of data operations, including Create, Read, Update, and Delete (CRUD) actions that work on single entities (tables/collections) as well as advanced join read/write tasks that go across multiple entities. Neurelo's auto-generated APIs are fully documented and version controlled.&#x20;

This automation not only saves time but also ensures consistency and reliability in how your application accesses and manipulates data, allowing developers to focus on more complex aspects of their application development.

### **Custom Query API Endpoints with AI Assist**

Custom Query APIs with AI Assist feature leverages a smart AI engine based on Large Language Models (LLM). This capability allows developers to easily create advanced custom queries, test and validate the queries, and quickly deploy these complex queries as custom API endpoints seamlessly.&#x20;

Neurelo's AI assist capability enables building these queries by taking a natural language prompt from the user and generating optimized queries in SQL (Structured Query Language) or MQL (Mongo Query Language) as needed for the data sources based on the user prompt. The AI models are trained to understand the specific language and rules of databases, including syntax and meaning, along with the context of your application like the data model in the schema.&#x20;

By bringing all these elements together, this feature makes application development smoother and it also boosts how efficiently and accurately one can build and run complex queries.

### **Query Observability**

Neurelo's Query Observability feature gives users a clear visibility into what's happening with their APIs. It offers detailed metrics for each API endpoint, so one can understand and track every data action. This helps users keep an eye on performance, catch any issues, and make queries work better in real-time. Query observability can be enabled for an environment allowing one to track API and database query performance for different setups across dev, test, prod, etc. With this constant visibility, your endpoints always perform their best, making your data work more smoothly and securely.

### **Schema-as-Code**

Neurelo's Schema-as-Code feature revolutionizes data modeling by offering a programmable experience that integrates seamlessly with version control, governance, and collaboration practices. It lets users handle their database schema like source code, using coding practices they are already familiar with. This means users can easily define and manage their schema while keeping track of changes efficiently with version control. The feature also helps enforce standards, making collaboration smoother among team members, and overall, it makes developing and maintaining database schemas more efficient, clear, and consistent.


# Getting Started

## Overview - Universal Database Integration for MongoDB, PostgreSQL, and MySQL

Neurelo brings a cutting-edge approach to building, managing, and interacting with databases, supporting various technologies like MongoDB, PostgreSQL, and MySQL. This means no matter your database choice or where it's hosted, Neurelo easily integrates with it.&#x20;

Create an account with Neurelo to get started. Once you create the account, just share the details of your MongoDB, Postgres, or MySQL databases, and you're all set to explore and elevate your data operations with Neurelo using our Quick Start guide. Additionally, getting started with Neurelo's advanced features, like generating complex queries using AI assist, validating them, and creating custom API endpoints, is a breeze once you have onboarded a project on Neurelo.&#x20;

After the setup, Neurelo becomes a robust intermediary, allowing you to smoothly use its features on any of these databases with your applications. Whether you're dealing with MongoDB's document-oriented structures, PostgreSQL's relational complexities, or MySQL's widespread utility, Neurelo guarantees a consistent, efficient, and user-friendly experience across the board.

Neurelo's universal compatibility not only expands the possibilities for your data operations but also simplifies your workflows. It cuts down on the usual complexities related to handling different database systems. With Neurelo's robust, versatile, and user-friendly platform, developers can worry less about the details of database management and focus more on developing their applications.&#x20;


# Sign-in/Sign-up

To access the Neurelo dashboard, go to <https://dashboard.neurelo.com/>. Once there, you'll find the option to sign in to your existing account. If you don't have an account, you can create a new Neurelo account using the "New to Neurelo? [Create an Account](https://dashboard.neurelo.com/register)" option on the page.&#x20;

### Login/Register

**Visit the Neurelo Dashboard**: Open <https://dashboard.neurelo.com/> using your browser. This is your starting point for accessing Neurelo’s Cloud Data Access Platform.

**Sign-In (Login) or Sign-Up (Register) Options**: On the dashboard, you will find options to either sign in using an existing account or sign up for a new account. Users can sign up with their email address and a secure password. Neurelo also offers the convenience of signing in with a Google or a Github account. This can be a quick and convenient way to sign up/in without having to create an account using an email address and password. &#x20;

* **Sign-In**: If you already have a Neurelo account, you can sign in using your existing credentials. Please use the same method (Email/Password, Sign in with Google, or Sign in with GitHub) you used when signing up for an account with Neurelo.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FKc5ypdyQlZ3mh2XxmqP2%2FNeurelo%20-%20SignIn.png?alt=media&amp;token=e2255c10-a85e-4d98-9a40-87447e74fa71" alt=""><figcaption><p>Sign into your existing Neurelo account</p></figcaption></figure>

* **Sign-Up for New Users**: For new users, look for the "[Create an Account](https://dashboard.neurelo.com/register)" option on <https://dashboard.neurelo.com>. You can provide your Full Name, Email Address and Password to create a new account. Or you can simply sign-up with your Google or Github  account for convenience.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FtfAUgqBIgFD12W8ICADZ%2FNeurelo%20-%20SignUp.png?alt=media&amp;token=254113f1-828d-46bc-8942-f4428142c61a" alt=""><figcaption><p>Register for a new Neurelo account</p></figcaption></figure>

If you are using an email address and password,&#x20;

1. The password needs to comply with the following -&#x20;
   * Must be at least 8 characters long
   * Should contain a number or symbol
   * Cannot contain your name or email address
   * We validate passwords using [Have I Been Pwned](https://haveibeenpwned.com/Passwords) to prevent using exposed ones.
2. You will need to verify your email address. Neurelo will send you a 6-digit verification code to your email, as part of the sign up process, which you will need to input during the signup flow. The email with the verification code will be from "<hello@neurelo.com>" with the Subject as "Please verify your email address".&#x20;

{% hint style="danger" %}
Please make sure that "<hello@neurelo.com>" is in your allowed senders list in your email settings. If you have not received the email with the verification code, please check your Junk/Spam/Bulk email mailbox. You can resend a new code as part of the workflow if you are not able to find the original code.&#x20;
{% endhint %}

{% hint style="warning" %}
If you are Signing Up with Google or GitHub, depending on the browser type, version and local settings, you may sometimes need to click on the Sign In with Google/Github button twice to continue with the Sign Up process
{% endhint %}

{% hint style="success" %}
Reference - [Supported Operating Systems and Browsers](/references/supported-os-and-browsers)
{% endhint %}

### Recover your Account

If you don't remember the password or need to reset your password, please use the "Did you forget your password? [Recover your account](https://dashboard.neurelo.com/recovery)" workflow on the page, which will start the workflow to help you get back to using your Neurelo account quickly.&#x20;

{% hint style="info" %}
This workflow to recover your account can only be used if you signed up with an email and password. This is not supported if your account uses Sign In with Google or Github.
{% endhint %}

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fm6kGngOPtaLmK6LJcGUh%2FNeurelo%20-%20Recover%20Account.png?alt=media&amp;token=9ec7bc5b-953a-4440-92fe-7d5190b90842" alt=""><figcaption><p>Recover your account</p></figcaption></figure>


# Dashboard

### Overview

The[ Neurelo Dashboard](https://dashboard.neurelo.com/) acts as your main control hub, providing a range of features to effectively handle your projects and carry out different tasks.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FDdiYF1Z2e96VXR6ejQmG%2FDashboard%20-%20Annotated.png?alt=media&amp;token=3b35107a-4b2c-42cb-a880-01fc64406ffc" alt=""><figcaption></figcaption></figure>

Here's a quick overview of what you can accomplish on the Dashboard:

1. **Projects**: Easily select an existing project or initiate new projects directly from the dashboard. This feature is designed for quick access, allowing you to continue working on an existing project or to start new projects.&#x20;
2. **Light/Dark Mode**: Personalize your experience by switching the dashboard theme between light and dark modes. This feature enhances visual comfort and accessibility, catering to different preferences and working environments.
3. **Account Settings**: Update and manage your personal account settings. This could include changing your name, email address, and setting up a profile pic. You can also enable 2FA for your account from here. Note, if you signed up using an Email/Password and need to reset your password , please use the "Did you forget your password? [Recover your account](https://dashboard.neurelo.com/recovery)" workflow on the page from the sign-in page at <https://dashboard.neurelo.com>.
4. **Audit Events**: Keep track of activities and changes made in the organization across projects and environments by using the audit events feature. This is crucial for monitoring the performance and security of your projects. Note - this feature is only available for the Admins in the organization.
5. **Members**: View and manage the list of members within your organization. This feature is essential for team collaborations, allowing you to add, remove, or change roles of team members. Admins of the organization can invite other users as Admins or Members.&#x20;
6. **Organization Settings**: Manage and modify settings related to your organization. This includes updating organization details, and configuring a logo for the organization.
7. **Docs:** Link to access Neurelo Product Documentation (<https://docs.neurelo.com>)
8. **Contact Support**: If you encounter any issues or have questions, the dashboard provides a direct link to contact Neurelo’s support team. This ensures that help is readily available whenever needed.&#x20;
   * For support using email, please send us an email to <support@neurelo.com> with details of the help needed
   * For faster support, please join our Discord Server using <https://discord.com/invite/5VRK8vyFmG> and send us a message there.

With these functionalities, the Neurelo Dashboard is designed to be an all-encompassing interface, simplifying the management of your projects and enhancing your overall experience with Neurelo’s platform.

Let's dive into some of these features to get a better understanding of navigating the Dashboard.&#x20;


# Collapsible Sidebar

The sidebar on the dashboard enables quick navigation access for the following actions -

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fk0OXYu14kEhNeHSoM1De%2FSidebar.png?alt=media&amp;token=44082714-6781-4cc1-816c-64a7c3a9e8c5" alt=""><figcaption></figcaption></figure>

* **Home** - Quick access to go back to the main page by clicking on the Neurelo logo
* **Project Selector** - Quickly select the project you want to work on. Each project has options for
  * **Dashboard** - Summary of the onboarding progress and widgets for accessing environments and data sources within the project
  * **Definitions** - Go to the definitions section of the project
  * **Environments** - Go to the environments section of the project
  * **Data Sources** - Go to the data sources section of the project
  * **Settings** - Open up the project settings page
* **Docs:** Link to access the Product Documentation (<https://docs.neurelo.com>)
* **Support:** Send us an [email](mailto:support@neurelo.com) or reach us on our [Discord Server](https://discord.com/invite/5VRK8vyFmG) for help
* **Org Selector**
  * Select an Organization to work on the projects in that org
  * Organization settings page
  * Manage membership in the organization
  * Audit Events
* **Collapse/Expand**

  The sidebar opens by default in the expanded mode, but can be collapsed to get more space for the project workspace in your browser. The collapse/expand option will appear once you move your mouse to the sidebar&#x20;

  <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FtiRF2EOGuSHwnul63aFo%2FNeurelo%20-%20Sidebar%20Expanded.png?alt=media&amp;token=525c6dd0-33fb-4d73-919f-ebdc885caf92" alt="" width="563"><figcaption><p>Expanded Sidebar (Default)</p></figcaption></figure>

<div align="center"><figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FGESLgSF2Fs4Y7EMNarNW%2FNeurelo%20-%20Sidebar%20Collapsed.png?alt=media&amp;token=6b4de03f-b571-4c97-9c69-cc4fa204c064" alt="" width="563"><figcaption><p>Collapsed Sidebar</p></figcaption></figure></div>


# Light/Dark Mode

### Switching to Light/Dark Mode in Neurelo

Neurelo accommodates different development preferences by offering both Light and Dark themes. By default, the dashboard is set to the mode that matches your system settings. If you prefer to switch to Light/Dark Mode, here’s a simple guide:

1. **Locate Theme Settings**: On your Neurelo Dashboard, navigate to the upper right corner. Here, you'll find your organization name and email address displayed.
2. **Access Theme Options**: Click on the area where your organization name and email address are shown. This action will open a dropdown menu with several options.
3. **Select Light/Dark Mode**: In the dropdown menu, look for the option labeled "Light Mode" or "Dark Mode" This is typically listed among other options such as 'Account Settings' and 'Sign Out'. If you are currently using Light mode, the option displayed in the menu will be the Dark mode and vice versa.&#x20;
4. **Activate Light/Dark Mode**: Click on the "Light Mode" or "Dark Mode" option. Upon selection, the theme of your dashboard will change to the selected mode.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FtXAwLtDEs3eEE9ORqw4X%2FScreenshot%202024-01-11%20at%2010.38.12%E2%80%AFAM.png?alt=media&amp;token=e325c1a1-3cac-4b7c-a8d8-6a9f5838574a" alt=""><figcaption></figcaption></figure>

Once you've selected a specific mode, your Neurelo Dashboard will switch to this theme. Depending on your preference, you can select Light Mode if you prefer a brighter navigation experience. or alternatively dark mode is preferred for its visually soothing properties and reduced strain on the eyes, especially in low-light environments. Neurelo will remember the selection in the browser cache and render the appropriate mode for future logins.&#x20;


# Account Settings

### Managing Your Account Settings in Neurelo

The "Account Settings"option in Neurelo is where you can manage various aspects of your profile. Here's a breakdown of what you can do:

1. **Update Profile Information**:
   * **Profile Picture**: Change your profile picture to personalize your account.
   * **Full Name**: Update your full name as needed, ensuring your profile correctly reflects your identity.
   * **Email Address**: Change your email address if necessary. Having a valid email address is important for maintaining your account with Neurelo.
2. **Set Up Two-Factor Authentication**:
   * **Authentication QR Code**: For enhanced security, you can set up two-factor authentication (2FA/MFA). A QR code will be provided for this purpose. Scan this QR code with your preferred authenticator app (like Google Authenticator or Authy) to link your Neurelo account with the app.
     * **Authenticator App Secret Key**: If you're unable to scan the QR code, use the provided secret key. This key can be manually entered into your authenticator app to achieve the same result as scanning the QR code.
   * **Enter the Verification Code**:

     * **Verification Code Input**: Once your authenticator app is set up and synced with your Neurelo account, it will generate a verification code. Enter this code in the provided text box in your account settings to complete the 2FA/MFA setup process.

     <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FnuepxB1iakmve1avfHqd%2FNeurelo%20Account%20Settings.png?alt=media&amp;token=cbe9e81a-28b6-4ae7-8ca5-eac24abefa7d" alt=""><figcaption></figcaption></figure>

By managing your account settings, you can ensure that your Neurelo profile is customized and remains up-to-date and secure. The inclusion of two-factor authentication adds an additional layer of security, safeguarding your account against unauthorized access.


# Audit Events

### Accessing Audit Events/Logs in Neurelo

The Audit Events or Logs section in Neurelo is a powerful feature that offers comprehensive insights into the activities conducted by the users in your Organization within Neurelo. This section is instrumental for tracking and auditing user actions, ensuring transparency and accountability. Here’s how you can utilize this feature:

1. **Navigating to Audit Events**:
   * To begin, navigate to the lower left corner of your Neurelo Dashboard.
   * Click on your organization name. This action will open a list of options, including "Audit Events," "Members," "Org Settings," and the Organizations your account belongs to. Note - some of these options may not show up depending on whether your account is an "Admin" or a "Member" in the organization.&#x20;
   * Select "Audit Events" from this list to access the logs.
2. **Overview of Activities**: The audit events/logs provide a detailed overview of all actions performed. It covers various aspects like the type of activity, the date and time it was performed, the user who executed it, and the specific project it pertains to.
3. **Filtering Events for Specific Timeframes**:
   * **Start Date and End Date**: To navigate through a vast number of events, Neurelo allows you to filter activities within a specific timeframe. You can set a 'Start Date' and 'End Date' to view events that occurred during that period.
4. **User-Specific Activity Tracking**:
   * **User Filter**: If you need to review the actions of a specific user, you can filter events by user names. This is particularly useful in collaborative environments to track individual contributions or modifications.
5. **Project-Specific Viewing**:
   * **Project Filter**: In cases where you’re managing multiple projects, the ability to filter activities by a specific project is invaluable. This helps in isolating events related to a particular project, facilitating easier project management and audit.
6. **Environment-Based Sorting**:
   * **Environment Filter**: Neurelo further allows sorting activities based on different environments like test, production (prod), development (dev), etc. This feature is crucial for distinguishing activities across various stages of your project lifecycle.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fw7MwFAVE25w8PPtBXjVm%2FScreenshot%202024-01-11%20at%2010.42.39%E2%80%AFAM.png?alt=media&amp;token=10fb951b-6b1e-4588-a0a4-8b0d1ba718b6" alt=""><figcaption></figcaption></figure>

By effectively using these filtering and sorting capabilities, you can quickly pinpoint specific events, streamline your project management process, and maintain a high level of auditability and accountability within your Neurelo Dashboard.


# User Management

## Inviting Team Members and Managing Roles in Neurelo

Neurelo enables you to invite team members, collaborators, and stakeholders to your organization. These individuals can manage the project as an Administrator and/or contribute to the project as a Member. Here’s how you can manage these settings:

### **Accessing the Members section (Admins Only)**

* To begin, navigate to the lower left corner of your Neurelo Dashboard.
* Click on the Org selector and select the organization you would like to edit the membership for.&#x20;
* Select "Members" from this list to access the Members section.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F3ntT7oAiOj4wJQmWYeu2%2Finvite1.jpg?alt=media&amp;token=85d90290-5612-4cf3-be8d-57066b673309" alt="" width="263"><figcaption></figcaption></figure>

{% hint style="warning" %}
Only the Admins of the Organization can list and manage members
{% endhint %}

### **Inviting New Users**:

* On the Members page, you’ll find the "Invite User" option.
* Clicking "Invite User" opens a popup window where you can add a new user.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FrujLPtLrYvelJSz8FiTZ%2Fimage.png?alt=media&amp;token=689b2cff-1c46-4fda-a368-02650a83234c" alt=""><figcaption></figcaption></figure>

* Enter the user’s email address and select their role from the dropdown menu. Available roles typically include "Admin," "Member," and possibly others (future), depending on your organization's setup. See [this](/getting-started/dashboard/user-management/permissions-member-v-s-admin) for details on the Admin v/s Member roles.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FSZvPixcuw7uLAYLKG1WZ%2Fimage.png?alt=media&amp;token=a06e6902-23d1-4913-b117-28b7fa5671f5" alt="" width="563"><figcaption></figcaption></figure>

* After selecting the appropriate role, click "Submit" to send an invitation to the user. The invited user will receive an email to join the organization with the designated role. This invited user can be a user with an existing account in Neurelo or may need to create a new account. Once they have a valid account and accept the invite, they will be added to this organization.&#x20;

### **Viewing Current Users**:

* Back in the Members section, click on the "Users" tab.
* This tab displays all users who have accepted the invitation and currently have access to the dashboard for the organization.
* From here, you can invite new users as well as manage existing memberships.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F8tCMtfY4aOLNrLk3gC4M%2Finvite2.jpg?alt=media&amp;token=47c598ae-d0c7-4338-9bcd-d7409bce8f91" alt=""><figcaption></figcaption></figure>

### **Tracking Invitation History**:

* Next to the "Users" tab, you’ll find the "Invitation History" tab.
* This section allows you to view all the invitations you have sent out, including pending and accepted invites. It’s an effective way to track who has been invited and their current status. You can also re-send an invitation from this page.&#x20;

By utilizing these features, you can effectively manage who has access to your Neurelo projects, ensuring that the right people have the right level of access for collaboration and monitoring. This system enhances teamwork and project oversight, making your workflow more efficient and organized.


# Permissions (Member v/s Admin)

## Roles/Permissions

When you invite another user into your organization, you can decide whether they should have an **admin** or a **member** role within the organization. This choice determines what exactly they are allowed to do. Below is a list of these permissions.

✅ = Permitted

❌ = Not Permitted

### Organization-Level

| Action              | Member | Admin |
| ------------------- | ------ | ----- |
| Create project      | ✅      | ✅     |
| Manage memberships  | ❌      | ✅     |
| Manage billing      | ❌      | ✅     |
| Change Org Settings | ❌      | ✅     |

### Project-Level

| Action             | Member | Admin |
| ------------------ | ------ | ----- |
| Delete             | ✅      | ✅     |
| Create Data Source | ✅      | ✅     |
| Create Environment | ✅      | ✅     |
| Update schema      | ✅      | ✅     |

### Environment-Level

* Environment **not** tagged as "**Production**". See [Environment/Data Source Tags](/guides/environment-data-source-tags)

<table><thead><tr><th width="298">Action</th><th>Member</th><th>Admin</th></tr></thead><tbody><tr><td>View</td><td>✅</td><td>✅</td></tr><tr><td>Delete</td><td>✅</td><td>✅</td></tr><tr><td>Update Tag</td><td>❌</td><td>✅</td></tr><tr><td>Generate Mock Data</td><td>✅</td><td>✅</td></tr><tr><td>Manage API Keys</td><td>✅</td><td>✅</td></tr><tr><td>Change Env Settings</td><td>✅</td><td>✅</td></tr></tbody></table>

* Environment tagged as "**Production**".  See [Environment/Data Source Tags](/guides/environment-data-source-tags)

| Action              | Member | Admin |
| ------------------- | ------ | ----- |
| View                | ✅      | ✅     |
| Delete              | ❌      | ✅     |
| Update Tag          | ❌      | ✅     |
| Generate Mock Data  | ❌      | ❌     |
| Manage API Keys     | ❌      | ✅     |
| Change Env Settings | ❌      | ✅     |

### Data Source-Level

* Data Source **not** tagged as "**Production**". See [Environment/Data Source Tags](/guides/environment-data-source-tags)

<table><thead><tr><th width="298">Action</th><th>Member</th><th>Admin</th></tr></thead><tbody><tr><td>View</td><td>✅</td><td>✅</td></tr><tr><td>Delete</td><td>✅</td><td>✅</td></tr><tr><td>Update Tag</td><td>❌</td><td>✅</td></tr><tr><td>Wipe Database</td><td>✅</td><td>✅</td></tr><tr><td>Change Data Source Settings</td><td>✅</td><td>✅</td></tr></tbody></table>

* Data Source tagged as "**Production**". See [Environment/Data Source Tags](/guides/environment-data-source-tags)

<table><thead><tr><th width="298">Action</th><th>Member</th><th>Admin</th></tr></thead><tbody><tr><td>View</td><td>✅</td><td>✅</td></tr><tr><td>Delete</td><td>❌</td><td>✅</td></tr><tr><td>Update Tag</td><td>❌</td><td>✅</td></tr><tr><td>Wipe Database</td><td>❌</td><td>❌</td></tr><tr><td>Change Data Source Settings</td><td>❌</td><td>✅</td></tr></tbody></table>


# Org Settings

### Managing Organization Settings in Neurelo

The Organization Settings in Neurelo provide a straightforward way to personalize and update your organization’s profile. Here are the key functionalities available in this section:

1. **Change the Org Logo**:
   * In Organization Settings, you have the option to update or change the logo of your organization. This logo represents your organization on the Neurelo platform and can help with quickly identifying your organization in Neurelo with your brand image.
   * To update the image, simply click on the current profile image and select a new image from your device. This new image will replace the existing one and be displayed as your organization’s profile picture.
2. **Change Organization Name**:

   * Another critical feature in Organization Settings is the ability to change your organization's name.
   * This option is particularly useful if your organization undergoes rebranding or if you need to correct a typo in the current name.
   * To change the name, locate the organization name field, make your edits, and save the changes. The new name will be reflected immediately across the Neurelo platform.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FP6VSTZkNbdnUJJ5FwltG%2FNeurelo%20Org%20Settings.png?alt=media&amp;token=4ff848ab-514b-40b3-849d-a022f476ac03" alt=""><figcaption></figcaption></figure>

These settings allow you to maintain the most current and relevant information for your organization, ensuring that your Neurelo account aligns with your organization's identity and branding.


# Starting your Neurelo Project

### Overview

Projects are applications (software/workload) that developers build and run with Neurelo. This is the primary “working” entity where all things start inside Neurelo. A project exists inside an Organization and has its own set of entities such as data definitions, environments, dashboards, data sources, etc. There is no limit to the number of projects users can create in Neurelo.

To begin setting up your new project in Neurelo, follow these simple steps:

1. **Access Your Neurelo Dashboard**: After signing in to your Neurelo account, you will be directed to your Neurelo Dashboard. This is your central hub for managing your projects.
2. **Start a New Project**:&#x20;
   1. Look for an orange button on the Dashboard with a + icon and the word "New" inside it. This button is designed for creating new projects.
   2. Initiate Project Creation: Click on this orange "+ New" button. This action will launch the process for setting up a new project in Neurelo.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FOPz1eMNGFRY1ZiX0L04u%2Fimage.png?alt=media&amp;token=4bb3b997-088e-4649-bfeb-3091ff0b7e07" alt=""><figcaption></figcaption></figure>

### Creating a New Neurelo project

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fw1eJu29JdYTQ0ZFYYVe5%2FNewProject.png?alt=media&amp;token=014061b3-7030-44f8-a958-429ed542097b" alt="" width="375"><figcaption></figcaption></figure>

As part of creation of a new project, please provide the following information:

* **Organization Name**: The organization name associated with your account will be automatically filled in. This helps in categorizing your project under the correct organizational umbrella in Neurelo.
* **Name Your Project**: Enter a distinctive name for your project. This name should reflect the essence or purpose of the project for easy identification.
* **Select the Database Engine**: For your project, choose any one of the supported databases from the available options. This selection is crucial as it determines the database technology your project will utilize.&#x20;
* **Migrations (Optional)**: Neurelo supports a feature (in preview) to automatically generate an initial set of schema migrations to correspond with the schema (data model) changes. This is enabled by default for the supported relational databases - PostgreSQL and MySQL. If this setting is enabled, schema migrations are generated as schema changes are made. There is additionally also a feature to apply (also in preview mode) these migrations. For non-relational databases such as MongoDB, this setting is not supported.&#x20;

{% hint style="info" %}
Neurelo Schema Migrations is currently a feature is currently in preview and not intended for production use. Use with caution and provide feedback to help us improve.
{% endhint %}

{% hint style="warning" %}
**Note** - The Migrations setting is a one-way toggle, and can't be re-enabled once it's disabled (either during project creation, or subsequently from under project settings)
{% endhint %}

* **Language Stack Preference (Optional)**: Choose the programming language you will be using for your project. This tailors (future) your Neurelo project environment to your preferred programming language such as providing language specific SDK, and for API examples.
* **Project Description (Optional)**: There is an optional 'Description' field where you can provide a brief summary of your project. Although optional, this can be helpful for future reference or for team members to understand the project's purpose at a glance in the overview page.
* **Use Remote Git Repository (Optional):** When creating a new project in Neurelo, you can choose to use your own git repository for the Definitions (Schema, Migrations, Custom APIs, etc.) in your project instead in Neurelo's versioning system. Please refer to [this guide](/guides/remote-git-repository-for-definitions) for details on connecting and using a remote git repo in your project.

**Create the Project**: Finally, click on the "Create" button to finalize the creation of your new Neurelo project. This action will initialize your project with the configuration you have specified.

After you click on create, you will see the following screen and the next steps for your project.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FjfkLv4hHrclctVlL6l8K%2FNeurelo%20Quick%20Start.png?alt=media&amp;token=63aef6cf-a2be-4767-8d24-d38bbf2420d6" alt=""><figcaption></figcaption></figure>

You can start with one of 3 options:

1. Quick Start guide (**Recommended**): This is a step-by-step guide to help users with setting up and onboarding their new projects. This flow is recommended for all users new to Neurelo.
2. Introspection (Advanced): For advanced users of Neurelo, who are familiar and comfortable with the platform, this option enables users to start a project with definitions from an existing data source. Choose this option if you want to start from an existing data source. It’s ideal for projects where a database already exists and you want Neurelo to adapt to its current schema.
3. Empty Project (Advanced): For advanced users of Neurelo, who are familiar and comfortable with the platform, this option enables users to start a project from scratch and build definitions in Neurelo.

By completing these steps, your Neurelo project is now initialized and ready for your next steps. You can begin integrating your database and leveraging the powerful features offered by Neurelo for efficient data management and API generation.<br>


# Quick Start Guide

### Overview

The Quick Start guide for a new project is the recommended method for setting up a project with Neurelo.&#x20;

**Starting with Quick Start**: For most users, especially those new to Neurelo, the Quick Start option is the best way to begin. It provides a comprehensive guide through each of the 5 steps of the setup process, ensuring that users cover all necessary aspects for a successful onboarding.

This flow provides an intuitive 5-step guide for users to&#x20;

1. Setup their data sources
2. Add schema definitions
3. Create environments
4. Configure API Keys to be used with APIs, and&#x20;
5. Start the environment runners to be able to use the APIs&#x20;

### Diving Deeper into Quick Start

The Quick Start guide is designed to be intuitive, making it easy for users to understand and complete each step efficiently.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FiOox0tMAaKVGFKvMx6yU%2FQS0.png?alt=media&amp;token=92123cba-12e1-48e1-bba5-1606ea617bd7" alt="" width="563"><figcaption></figcaption></figure>

By following the Quick Start, users can ensure that their project is correctly set up and ready to leverage Neurelo's features starting with auto-generated REST and GraphQL APIs. This approach simplifies the initial setup and helps you get your project up and running quickly.

Let's start with the first step to "Add a Data Source".


# Step 1 - Add a Data Source

### Overview

The first step in the project onboarding process is to connect a data source to the project.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F6eMvjCU4clGF1sQHeVts%2FNeurelo%20Quick%20Start%20-%20Step%201.png?alt=media&amp;token=e0c37bba-0f9e-4608-a4ff-15bfe9c1d698" alt="" width="563"><figcaption></figcaption></figure>

If you have an existing database, you can attach it to this project using "Connect Data Source". Once the database is connected, Neurelo will perform an "introspection" on the data source and will try and infer the schema (data models) for the project from the database. If Neurelo finds a valid schema in the database, it will initialize the definitions with that schema (step 2 of the onboarding). If no valid schema is found, then the user will need to proceed to Step 2 and Build Definitions (Schema) to be used for the project.&#x20;

{% hint style="info" %}
Reference - [Neurelo Supported Databases and Versions](/references/supported-databases)
{% endhint %}

You can connect a Managed or Self-hosted PostgreSQL, MySQL or MongoDB instance to the project in this step. Some examples of database cloud providers you can use are [AWS RDS](https://aws.amazon.com/free/database/?gclid=CjwKCAiAqY6tBhAtEiwAHeRopbpdCG6Rw0-HeQchIGgnPN6AvBcEZqCzW9Q0AvoUIhJGaDQyhlWLBxoCxSQQAvD_BwE\&trk=83add82a-8e52-4837-bc73-c323da62d78c\&sc_channel=ps\&ef_id=CjwKCAiAqY6tBhAtEiwAHeRopbpdCG6Rw0-HeQchIGgnPN6AvBcEZqCzW9Q0AvoUIhJGaDQyhlWLBxoCxSQQAvD_BwE:G:s\&s_kwcid=AL!4422!3!679413812800!e!!g!!aws%20rds!11086562318!108339552603) (PostgreSQL, MySQL), [Atlas](https://www.mongodb.com/atlas/database) (MongoDB), [Aiven](https://aiven.io/) (PostgreSQL, MySQL).&#x20;

{% hint style="success" %}
Neurelo Provisioned Databases (Preview): For evaluation purposes, Neurelo also supports provisioning an evaluation database for your project. Neurelo offers this database for evaluation purposes only, with no guarantees on availability, durability, or security. This database should not be used for production workloads.&#x20;

Neurelo provisioned databases will be spun up for PostgreSQL and MySQL on AWS RDS, and on Atlas for MongoDB. You can spin up one Neurelo Provisioned database per organization.&#x20;

*Note - We are gradually rolling out this feature for our users, and it may not be available for your account yet.*&#x20;
{% endhint %}

### Adding a Data Source in Neurelo Project

* **Starting with 'Add a Data Source'**:

  * The first step in Quickstart is to connect your data source, which can be PostgreSQL, MongoDB, or MySQL.
  * If you already have a Database instance, Click on the "Connect Data Source" button to begin this process.
  * Alternatively, if you don't have a Database instance, Neurelo provides a seamless way to quickly provision an evaluation database instance for you.&#x20;

  <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fq4oZf1IIxJNQezUPXBFs%2FMDS.png?alt=media&amp;token=f7aa4290-93ee-4bbd-9600-5e71b73cf8b4" alt="" width="563"><figcaption></figcaption></figure>
* **Choosing How to Connect**:

  * Upon clicking, a popup window will appear, asking you to name your data source.
  * Next, you have two options to establish the connection: using Connection Details or a Connection String.<br>
  * **Using Connection Details**: If you opt for **Connection Details**, you'll need to provide specific information about your database:

  <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F5IVADIgsdZXH4vyJanwE%2Fimage.png?alt=media&amp;token=d01daac3-4a27-47cb-a7b4-863e0cd9987a" alt="" width="375"><figcaption></figcaption></figure>

  * **Host**: The URL endpoint of your database
  * **Port**: The port number used for the connection
  * **Database**: The exact name of the database to be used
  * **Schema**: Specify a schema, by default the schema will default to 'public', you can configure a different database schema for Neurelo to use based on your database configuration
  * **Username**: The username to be used for connecting to the database
  * **Password**: The password to be used for connecting to the database<br>
* **Using a Connection String**:  Alternatively, if you choose the Connection String method, simply input the connection string provided by your database host

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FjFG5EWFGOWu37CXTJPBL%2Fimage.png?alt=media&amp;token=c2a89595-47a1-41a9-abfd-1102f609c1b0" alt="" width="375"><figcaption></figcaption></figure>

This single string contains all necessary connection details, simplifying the process.

### **Selecting a Region and Allowing Neurelo IP Addresses**:

* If you have a firewall or security group configured in front of the data source, you may need add Neurelo IPs to the allowed list so that Neurelo can connect to the data source. There are multiple IPs for the selected region, all of which need to be permitted in the firewall or security group configuration
* Below the connection details or connection string, there’s an option to select a region. Choose one that best suits your operational needs.

{% hint style="info" %}
It is highly recommended that you create your Neurelo environments geographically as close to where the data source is as possible, for the best performance and lowest latency for your projects.
{% endhint %}

{% hint style="warning" %}
If you needed to configure Neurelo IPs to connect to your database, please make sure you spin up Environments that will use this database in the same region as the configured IPs selected.&#x20;
{% endhint %}

To make sure that all the information has been correctly entered and the Neurelo IPs have been added to the allowlist, you can test the connection by clicking on "Test Connection", You will receive a pop up saying "Connection test in progress" and once the connection has been tested successfully, you receive a message "Connection test completed successfully".&#x20;

### Saving the Data Source

You can then proceed to click on the "Submit" button. Once the data source is connected, Neurelo will perform an "introspection" on the data source and will try and infer the schema (data models) for the project from the database.&#x20;

If the database is empty and no valid schema is found, or the introspection process could not be completed for other reasons then the user will need to proceed to Step 2 and Build Definitions (Schema) to be used for the project. The quick start flow would now look something like this -&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FV8mqpZQZRY0esx9yS3Na%2FNeurelo%20Quick%20Start%20-%20Step%201%20Completed.png?alt=media&amp;token=fb4076d7-a5df-483c-bee7-a149ce0b72c0" alt="" width="563"><figcaption></figcaption></figure>

If Neurelo finds a valid schema in the database during the introspection process, it will initialize the definitions with that schema (Step 2 of the onboarding). Steps 1 and 2 are both completed now. You can proceed directly to Step 3 (Create an Environment). The quick start flow would now look something like this -&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FjbQwXi9x6RsHgQKmDt6f%2FNeurelo%20Quick%20Start%20-%20Step%201%20Completed.png?alt=media&amp;token=e2195348-45ca-4904-ac70-ae0de9831606" alt="" width="563"><figcaption></figcaption></figure>

By following these steps, you can successfully add a data source to your Neurelo project, setting the initial foundation for your subsequent activities and integrations within the platform.


# Step 2 - Build Definitions

### Overview

Neurelo's data definition comprises of three key elements - Schema, Auto-Generated APIs and Custom Queries. Definitions existing inside a project and are scoped to that particular project. Different projects will have their own definitions. Step 2 of the project onboarding process is to build the definitions (in particular, the schema) to be used for the project.&#x20;

The "Build Definitions" phase in Neurelo plays a pivotal role in shaping how your project interacts with data. This step varies depending on your database setup and the presence of existing definitions. Here's what you need to know:

### **Automated Definition Building with an Existing Database**:

* When you linked a database as a data source in Step 1 of the onboarding and it contains pre-defined schemas or definitions, Neurelo automates the building of your project definitions. In this case, you will typically see the following processes completed automatically:
  * **Neurelo Schema Added**: The platform successfully integrates your existing schema into the Neurelo environment.
  * **REST and GraphQL Data Access APIs Generated**: Neurelo automatically generates REST and GraphQL APIs based on your existing database schema, facilitating easy data access.
  * **API Documentation Generated**: Alongside API generation, Neurelo creates comprehensive documentation for these APIs, enhancing usability and understanding.

If a valid schema was identified, Step 2 of the onboarding process is complete and the user can proceed to Step 3 (Creating an Environment).&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FCTdLhX3wmYNSIXy5YCye%2FNeurelo%20Quick%20Start%20-%20Step%201%20%26%202%20Completed.png?alt=media&amp;token=1a925587-932d-4b17-9506-9621c9f1570b" alt="" width="563"><figcaption></figcaption></figure>

If the introspected schema has errors, or Neurelo could not identify a valid schema then users will need to fix or build the schema by going to the editor

### **Manual Definition Building without Existing Database Definitions**:

* In scenarios where your database doesn’t have pre-defined schemas, you will encounter a different interface, with a prompt to go to the Neurelo definitions editor interface

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FP0jJThrxCvjnVsAGfE3x%2FNeurelo%20Quick%20Start%20-%20Step%201%20Completed.png?alt=media&amp;token=27647652-75ba-4d0e-a3cb-b2b8114e8dfa" alt="" width="563"><figcaption></figcaption></figure>

* This option leads you to a interface where you can:
  * **Manage Database Schemas**: Directly interact with and modify your database schema using branches and commits.&#x20;
  * **Customize Definitions**: Perform customization and set up definitions according to your project requirements.
  * **Additional Customization Settings**: Access various settings to further tailor the definitions to your needs.
* For more detailed actions and capabilities within the editor, refer to the following sections in this document&#x20;
  * [Neurelo Schema Editor](https://app.gitbook.com/o/Ev8IAtj454Dt46GKpdB7/s/vzFLT4zSSU6J1uzbt5OF/definitions/neurelo-schema-editor)
  * [Neurelo Schema Language (NSL)](/neurelo-schema-language-nsl)

Once the definitions have been built, users can now proceed to Step 3 (Create an Environment).

Whether your project involves integrating existing definitions or creating new ones from scratch, the "Build Definitions" step in Neurelo ensures that your data models and APIs are precisely aligned with your project's needs.


# Step 3 - Create an Environment

### Overview

Environments are run time workspaces that allow users to run their Neurelo APIs using a specific version (commit) of their definitions and custom queries against a specific data source. Neurelo environments are built to be naturally aligned to typical Software Development LifeCycles (SDLC) as applications are developed, tested, deployed, and operated. Step 3 of the project onboarding flow is to create an environment

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FPhB6j0mzrOp3La3Lsk8K%2FNeurelo%20Quick%20Start%20-%20Step%201%20%26%202%20Completed.png?alt=media&amp;token=2a9fa115-cf1b-40a3-8f57-61e6724350d0" alt="" width="563"><figcaption></figcaption></figure>

### Create an Environment in Neurelo

In Neurelo, creating environments is a important step for managing different stages of your project. Whether it's for development, testing or production, Neurelo enables you to set up multiple environments tailored to your needs. Here's how you can create an environment:

1. **Understanding the Need for Environments**:
   * Environments like "test," "dev," or "prod" are essential for experimenting and deploying different stages of your project. ("test," "dev," or "prod" are examples of names you can provide, you have the choice to name your environment)
   * Neurelo requires at least one environment to complete your project setup.&#x20;
2. **Initiating Environment Creation**:
   * In the Quickstart guide, locate the "Create an Environment" section.
   * Click on the "New Environment" button to start setting up your environment.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FIhENnSFqnUzM4fUEXm0d%2Fimage.png?alt=media&amp;token=b306b06f-52c2-4baa-8710-6e8c4c9dbbae" alt=""><figcaption></figcaption></figure>

3. **Filling in Environment Details**:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FVwu5AFc3VGk3TGiFHhQO%2FNeurelo%20-%20New%20Environment.png?alt=media&amp;token=37b2dad7-6bda-451b-be7c-4e783711d9c0" alt="" width="375"><figcaption></figcaption></figure>

* **Environment Name**: Input a name for your environment. This could be indicative of its purpose, like "development" or "testing", or can be any relevant name for the environment e.g. "Dev-FR-Book-Covers", "\[QA] \[JIRA-953]: Add defaults for input fields"
* **Region**: Select the region you would like to spin up this environment in. We currently support 3 regions
  * AWS us-east-2 (Ohio, US)
  * AWS us-west-2 (Oregon, US)
  * AWS ap-south-1 (Mumbai, India)

{% hint style="info" %}
It is highly recommended that you create your Neurelo environments geographically as close to where the data source is as possible, for the best performance and lowest latency for your projects.
{% endhint %}

{% hint style="warning" %}
If you added Neurelo IPs to the allowed-list for your firewalls/security groups, as part of connecting your data source to Neurelo, please make sure to select the same region for your environment as you did when adding the data source
{% endhint %}

* **Select a Commit**: Every environment needs a definition commit which will be used in that environment. Once a commit is attached, the autogenerated APIs from that commit and custom query endpoints are available for use in that environment. In the dropdown for selection, one can select a branch and a commit from that branch to be used for the environment.&#x20;

{% hint style="warning" %}
Every project definition has an "Initial Empty Commit" created as part of initializing the project. This commit cannot be used for any environment.&#x20;
{% endhint %}

4. **Data Source Configuration**:

   \
   Every environment also needs a valid data source attached to it for it to be operational. When an environment is being created, if there is only one data source in the project it will be pre-selected. If you have multiple data sources, you can select the desired one to be used from the dropdown menu.<br>
5. **Configuring Additional Settings**:

* **Observability**: Enable this to activate observability for the environment, allowing you to monitor and analyze the environment's performance.
* **Automatic Migrations (Preview)**: This toggle enables automatic migrations (disabled by default) within the environment. It's particularly useful for managing database schema changes directly through Neurelo. This setting is applicable only for relational databases such as PostgreSQL and MySQL, and will show up as an option only when Migrations are enabled at the Project level&#x20;

Once the environment has been created, Step 3 of the Quick Start has been completed and the page will look something like this. The next step in the onboarding process is step 4 - Create an API Key

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FhGCMlpwVBGuXcaRQk7fk%2FQS4.png?alt=media&amp;token=c5e12d19-3951-444a-a77d-17b7d336cd1d" alt="" width="563"><figcaption></figcaption></figure>

By following these steps, you can effectively create and configure environments in Neurelo, ensuring that each stage of your project, from development to production, has the right setup and tools for success.


# Step 4 - Create an API Key

### Overview

In Neurelo, an API Key is a security credential that grants permissions to access the APIs for a specific environment. It serves as a form of authentication, allowing applications or users to make authorized requests to the API. API Keys are included in API requests to verify the identity and permissions of the requester. These api keys help ensure secure and controlled access to the API's functionality and data.&#x20;

Step 4 of the onboarding flow is to create an api key within the newly created environment.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FqB9RCT865OjaszgA9FCD%2FQS1.png?alt=media&amp;token=8e917bfd-681d-4b58-9c75-ab5c8b151217" alt="" width="563"><figcaption></figcaption></figure>

### Creating an API Key in Neurelo

Creating an api key is a vital step as part of activating an environment, especially when working with API endpoints. This key is used for securing and authorizing your API interactions, and passed with the API requests. Here’s how to create one:

1. **Initiating API key Creation**:
   * On the Quickstart dashboard, find the section for "Create an API Key"
   * Click on the "New API Key" button. This action will open a prompt for api key creation.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fbv8lFay9i7ZbatoEVXvs%2FQS2.png?alt=media&amp;token=224d6c00-1b57-4585-8b1c-a7c7d85e0c08" alt="" width="563"><figcaption></figcaption></figure>

2. **Configuring API Key Details**:

* **API Key Name**: You will be asked to provide a name for your new api key. Choose a name that is indicative of its use or purpose.
* **Permission Selection**: Decide the level of permission for the api key. The options are:
  * **Read**: This permission is always pre-selected and mandatory, allowing the api key to read data.
  * **Write**: Optionally, you can also enable the "Write" permission if the api key is  needed to modify or add data. This selection depends on your project requirements.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fs5ORVYnr4b0oE8MNiyFd%2FAPI%20Key%202.png?alt=media&amp;token=43bdca96-4f88-466e-a6fa-0d0d95799438" alt="" width="375"><figcaption></figcaption></figure>

3. **Generating the API Key**:

* After selecting the necessary options and filling in the information, click on "Create."
* A new prompt will appear with an important alert message: "Store this private key securely - For security reasons, you won't be able to view it again in your Neurelo Account. If you lose this secret key, you'll need to generate a new one."&#x20;

{% hint style="danger" %}
Please make sure to copy and save this api key in a secure location. Neurelo does not save this key and it cannot be retrieved again from the Neurelo dashboard once this step is completed.&#x20;
{% endhint %}

4. **Copying Your Generated API Key**:

* The prompt will display your "Generated API Key"
* You can either manually "Select and Copy" or click on the "Copy" button next to the  field with they api key to copy it to your clipboard.
* Below the api key, you’ll also see the permissions associated with it.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FRV5o8oFCFHgpjUqDrBvy%2FAPI%20Key%203.png?alt=media&amp;token=8ed05380-5ba2-414b-8e4d-b5d8bd925ff7" alt="" width="375"><figcaption></figcaption></figure>

5. **Completing the Process**:

* Once you have securely copied and stored the API Key, click on "Close" to return to the Quickstart dashboard.

{% hint style="info" %}
The "Close" option in the dialog box will not be activated until the api key has been "Copied"
{% endhint %}

Creating and securely storing this API Key is crucial for your project’s security and functionality in Neurelo. Ensure that the api key is kept in a secure location, as you cannot retrieve the existing key again from Neurelo for security reasons. If the key is lost, you need to revoke the existing api key and issue a new one within the Neurelo account. The Quick Start dashboard will now look something like this.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FAZu2pylRjbACwEXVfTBc%2FQS3.png?alt=media&amp;token=fb5a9cce-49e5-477b-a565-b217da9c73e5" alt="" width="563"><figcaption></figcaption></figure>

We are almost at the end of the quick start. The final step (Step 5) would be starting the runners in the environment.&#x20;


# Step 5 - Start Runners

### Overview

A runner in Neurelo is the main component that executes and manages all API calls. In Neurelo's Cloud Data Access Platform, a runner is a part of every environment inside a project. Runners need to be started for the application to be able to handle API requests and process them against the configured data source within an environment. The final step in the onboarding process is to Start the Runners for the  newly created environment within the project.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FAZu2pylRjbACwEXVfTBc%2FQS3.png?alt=media&amp;token=fb5a9cce-49e5-477b-a565-b217da9c73e5" alt="" width="563"><figcaption></figcaption></figure>

### **Understanding the Role of Runners**:

* Runners act as executing agents that manage the deployment and integration of your environment with the application.
* Notes
  * Once runners for an environment are started, the environment becomes Active and certain changes to the core settings of your project cannot be made (as long as runners are active). If you need to change the settings for the environment, you may have to stop the runners, make the changes, and then restart the runners.&#x20;
  * To conserve platform resources, running environments which are inactive (no api calls) for more than 7 days may be automatically stopped. When the runners are auto-stopped for inactive environments, their configuration is not impacted. Runners can be restarted anytime by clicking on "Start Runners" when you need to use the environment again.&#x20;

### Starting Runners in Neurelo

The final step in setting up your Neurelo project is to start the runners. Here’s how to activate them:

1. **Locating the 'Start Runners' Section**:

   * In the Quickstart guide on your Neurelo Dashboard, navigate to the "Start Runners" section.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FivasKlLdA8lcjMwlwXNt%2Fimage.png?alt=media&amp;token=3fd48681-db22-42fc-8100-6155f0f6b3e2" alt="" width="563"><figcaption></figcaption></figure>
2. **Activating the Runners**:

   * Click on the "Start Runners" button.
   * Upon clicking, a notification toast will appear stating, "Runners will start shortly. This will take a few seconds."
   * The card will show the status of the runners being deployed

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FQIvEZpFYLAl7lwYDPfXt%2FNeurelo%20Start%20Runners%20-%20Deploying.png?alt=media&amp;token=d7ce6a74-4ff6-4f24-a44a-b8873c677e7a" alt="" width="563"><figcaption></figcaption></figure>

   * Once the runners have been successfully deployed, this step is complete

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FMd9UOZzJwLsfs1e8Lk4K%2FNeurelo%20Start%20Runners%20-%20Completed.png?alt=media&amp;token=040e8d18-235f-43b4-91ea-76c10e434b3e" alt="" width="563"><figcaption></figcaption></figure>

### **Completion of Project Setup**

* With the runners successfully started, you have now completed the essential steps for the onboarding of your Neurelo project. Your environment is ready for deployment and integration activities.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FJQNVQdhKEOiN7qXZstWN%2FQS5.png?alt=media&amp;token=696f38b3-1b84-4545-9c97-e8c3768bd50c" alt=""><figcaption></figcaption></figure>

### **What's next?**

1. **Try your Neurelo APIs** using the API Playground
2. Checkout the SDKs
3. Create Custom Query Endpoints

By following these steps, you ensure that the runners, a vital component of your project's infrastructure in Neurelo, are correctly activated and ready to handle your deployment and continuous integration needs.

<br>


# Try your Neurelo APIs

### Testing Your Project with Neurelo APIs

After setting up your Neurelo project, the next step is to test and experiment with the APIs that have been generated for your project. Here’s how you can proceed:

1. **Accessing the API Playground**:

   * Locate the option "API Playground" on your Neurelo Dashboard&#x20;
   * Clicking this option will redirect you to the Environments section of your project and load the API Playground.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FyEAkW5fPk4L3wDChS6fP%2FNeurelo%20-%20Go%20to%20API%20Playground%20.png?alt=media&amp;token=edae8043-8032-478c-ba9a-fd20cebaa99e" alt=""><figcaption></figcaption></figure>
2. **Testing REST and GraphQL APIs**:

Within this section, you have the ability to view and interact with your REST and GraphQL APIs.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FgL2Tz3VBNOkUeHf5pNYR%2FNeurelo%20-%20API%20Playground.png?alt=media&amp;token=b8543f32-0f19-4382-83cc-0d6b3124a2bf" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
You will need to add your API Key in the "X-API-KEY" header to be able to use your APIs
{% endhint %}

### **Further Actions and Information**:

* For a more comprehensive understanding of all the actions you can perform in this section, refer to the \[[Environments](/environments)] documentation page. This documentation will offer detailed guidance on utilizing the full range of features available in your Neurelo project's environment.


# "How to" Videos

## <mark style="color:green;">Getting Started with Neurelo, Login, Key Settings</mark>

{% embed url="<https://www.loom.com/share/9aeb678cb45b42a3b83a71e374d49be1?sid=cdfc2684-ba8e-4248-a996-715e6ab4f832>" %}

## <mark style="color:green;">Creating a New Project, Using the Quick Start Guide</mark>

{% embed url="<https://www.loom.com/share/c9a1cd7cab5c4018b5864ef667c2e9c6?sid=37885043-679b-4080-a2c8-0805180db1d7>" %}

## <mark style="color:green;">Data Definitions</mark>

{% embed url="<https://www.loom.com/share/7ec76ecd9c9d45eb80562f8e8ded9e3e?sid=a882e1ea-993a-4423-9fa3-de7e4756821e>" %}

## <mark style="color:green;">Neurelo Schema Builder</mark>

{% embed url="<https://www.loom.com/share/4a3461c5822843428d2a222165726fdc?sid=15507a15-2fa2-4890-a01e-36e741f92817>" %}

## <mark style="color:green;">Environments</mark>

{% embed url="<https://www.loom.com/share/b34e912492e943c7b1b97af7bd66082f?sid=65a04fc0-ca3d-4ba9-a306-dd3655f8dead>" %}

## <mark style="color:green;">Auto-Generated APIs, API Docs, API Playground</mark>

{% embed url="<https://www.loom.com/share/d204cce4c0f04827b6b3e531d766ce3b?sid=402fab9f-d943-40c4-a697-c661deb72a37>" %}

## <mark style="color:green;">Using Neurelo APIs and SDKs</mark>

{% embed url="<https://www.loom.com/share/c6a950414c18478f965d17a34b557c62?sid=92e922a2-8016-43f1-8876-471247a163bf>" %}

## <mark style="color:green;">Neurelo Custom Query API Endpoints</mark>

{% embed url="<https://www.loom.com/share/6de04868b1ff4e71917493da29b4c901?sid=d5b51dc8-6c5e-428b-8802-fd5eb6222dcf>" %}

## <mark style="color:green;">Schema Migrations (Preview Feature)</mark>

{% embed url="<https://www.loom.com/share/f3db77b75a9f477eac0366d42995e1f6?sid=72705b08-4cf1-40a7-8a67-8a48f617adcd>" %}

## <mark style="color:green;">API Observability</mark>

{% embed url="<https://www.loom.com/share/749d5d7f606d49e68227532d7f71d9cf?sid=e0a235bb-c340-4019-9c3c-a58cf503be84>" %}


# Product Overview

{% embed url="<https://www.loom.com/share/bea8b436a12b4f7299c77f78dff9a336?sid=a7a52985-e004-4cda-b5fd-9bf01f73604c>" fullWidth="true" %}


# Neurelo APIs & SDKs

## <mark style="color:purple;">How to use Neurelo APIs and SDKs (Overview)</mark>

{% embed url="<https://www.youtube.com/watch?v=pXK-8bR2fPA>" %}

## <mark style="color:purple;">Select Basics</mark>

### How to select scalar fields and use of $scalars

{% embed url="<https://www.loom.com/share/2b94c001521d4c38b8b6a0ed1c27a589?sid=3e8d7575-3bde-4e4b-bd45-45bf8fa75add>" %}

### How to select related fields and use of $related

{% embed url="<https://www.loom.com/share/738b271ea0f64c0ead4481349efb0457?sid=8994b089-1f81-43a4-8e55-d02b5dcbfd7e>" %}

## <mark style="color:purple;">Filter Basics</mark>

### How to apply filters to scalar fields

{% embed url="<https://www.loom.com/share/f2f6666aff2942b98cfbb9e2b2c1094c?sid=d859eef3-0abc-43b0-b051-b9fa684ebaa8>" %}

### How to apply filters to relation fields

{% embed url="<https://www.loom.com/share/42e7d38354fc45569c43e1b58073d6dd?sid=ac50a1fb-f216-4e2b-a979-f31ac438f86a>" %}

### How to apply filters to json fields

{% embed url="<https://www.loom.com/share/056918315bf840a7bc9ecd4f46757806?sid=e72a5ffa-17ab-4201-9500-2148098aecba>" %}

### How to use OR/NOT filters

{% embed url="<https://www.loom.com/share/174e2f1122764c7f89fdf13339768866?sid=31dbc8db-62af-4e75-812f-35a650df59fb>" %}

## <mark style="color:purple;">Pagination (How to use order\_by, take, and skip)</mark>

{% embed url="<https://www.loom.com/share/90521ea399304604aebc26302914c6b6?sid=28ea18bc-2058-46c1-bea4-ad90ad3834f9>" %}

## <mark style="color:purple;">Aggregate (How to use aggregations)</mark>

{% embed url="<https://www.loom.com/share/16656ed8f86a49839c2f7e95d04d60c1?sid=268b9f58-9857-4705-922c-a2513bb333a2>" %}

## <mark style="color:purple;">Group By (How to use group by endpoint)</mark>

{% embed url="<https://www.loom.com/share/9c3934626f8b4b83967d3a60597cb705?sid=c0cbf7f1-ad35-4319-862e-f7039bb8b9f3>" %}

## <mark style="color:purple;">Create (How to create one or multiple records)</mark>

{% embed url="<https://www.loom.com/share/f7eff5dcdadf4dd3b013957b19a908e4?sid=e56a1ab4-1a6c-4037-bd5e-2fee5ea27a65>" %}

## <mark style="color:purple;">Update (How to update one or multiple records)</mark>

{% embed url="<https://www.loom.com/share/cce0d4f122c64ede89e4d2e7dbacb210?sid=ba8a3251-dd90-417f-9c3b-744a02ac1417>" %}

## <mark style="color:purple;">Delete (How to delete one or multiple records)</mark>

{% embed url="<https://www.loom.com/share/4ee7f70e367f47eca9a7996787b360f3?sid=96c6363c-c682-4f5e-be35-61707db7257e>" %}

## Other Videos

### <mark style="color:purple;">How to work with JSON data for MongoDB objects with the Neurelo APIs</mark>

{% embed url="<https://www.loom.com/share/4f684806d88243198f2efc9ab02392f5?sid=ab686a14-6c99-49ea-832b-36c7d84914f3>" %}

### <mark style="color:purple;">Exploring Neurelo's GraphQL APIs</mark>[<br>](https://www.loom.com/profile/Parth-c15de557-cb96-46b6-961e-b5c311780111)

{% embed url="<https://www.loom.com/share/01f67b42e2da406f9abc4b3accba6897>" %}


# Project Setup

## Quick Start

{% embed url="<https://www.loom.com/share/43154feb2fa84ed28c697f455e717f01?sid=84361a71-5546-4d74-8aaf-9c921cf17a90>" %}

## Project Creation

{% embed url="<https://www.loom.com/share/e74f53a8cc854dd9aa094dc41e8c3fb6?sid=daaea8a2-c844-4215-b157-e0a8e4967199>" %}


# Definitions

## Definitions Overview

{% embed url="<https://www.loom.com/share/802cba97f2d745e389d706638ba03507?sid=fd8b565a-2755-43bc-96e9-698c5111e851>" %}

## Introspection and Re-Introspection

{% embed url="<https://www.loom.com/share/3d594315bdcc448eb4f8387d63bde85e?sid=7047700c-4581-43f6-802a-71c1ea10a9ea>" %}

## Schema Objects

{% embed url="<https://www.loom.com/share/f8d42acd38cd4916a00a95bfad5d10e3?sid=aa923ff0-569d-4bd8-a9c3-1ec31927ed0f>" %}

## Schema Object Properties

{% embed url="<https://www.loom.com/share/604f74b8f6f5480cbec8e32ade8cecc7?sid=c391fbdb-ebed-45be-9568-def1d2c62f8e>" %}

## Schema Object Constraints

{% embed url="<https://www.loom.com/share/a0f0086054834fb181379cbd7769ce5b?sid=4a4afbcb-5079-427f-8231-22f104cd19d8>" %}

## Schema Enums

{% embed url="<https://www.loom.com/share/4e304cc6d5434a419e92592a64f49cdb?sid=a54aaef6-687a-4233-a9d0-c40ff06e2d6f>" %}

## Schema Inner Objects

{% embed url="<https://www.loom.com/share/833b047f875d407db0d2e106729aa6ba?sid=50a87923-e651-4a9e-9f92-e10f12363b3d>" %}

## Creating One:One Relationships

{% embed url="<https://www.loom.com/share/bfc2169a14324d18aa4f3dcc53afe2ba?sid=fd0ace6e-f340-40de-b247-bd1b9a702ddb>" %}

## Creating One:Many Relationships

{% embed url="<https://www.loom.com/share/df7836d29d19489d87a71f9925478abf?sid=7d8d20ec-7256-4415-8851-7e3bd033bfbc>" %}

## Creating Many:One Relationships

{% embed url="<https://www.loom.com/share/5a6b239126834f708b3991fce7c49254?sid=1fb093eb-2e8d-4947-8f76-32bdf2dbe522>" %}

## Creating Many:Many Relationships

{% embed url="<https://www.loom.com/share/7d8b91c5ed88413faeb6ba52556126cc?sid=abc32034-fdce-4fb0-b593-f98196928f75>" %}


# Environments

## Attaching a Data Source

{% embed url="<https://www.loom.com/share/eb162701aa944fbab55a90f2e291ceae?sid=60527491-f193-4f5e-a16f-646ec1de7527>" %}

## Detaching a Data Source

{% embed url="<https://www.loom.com/share/14003c8147404b0593f2bfa34c677ad6?sid=a4193fb8-3ba8-4278-9a7a-698270c4fd35>" %}

## Creating an API Key

{% embed url="<https://www.loom.com/share/826e5b6b54534ad19910295d0f907fca?sid=3f4ab43e-afd2-4b9c-b1db-ed31f5c1490f>" %}

## Revoking an API Key

{% embed url="<https://www.loom.com/share/0face578d56942f4af58e2d31bea67d2?sid=15ba8608-d266-43ea-a8bf-a1d9e1347e04>" %}

## Updating the Commit in the Environment

{% embed url="<https://www.loom.com/share/9a53ba955855410ab4deec3f068f1d66?sid=0119a474-86d8-43d6-b54d-a914285c6fcc>" %}

## Migrations

{% embed url="<https://www.loom.com/share/67321575681e49798fbdf463bcbdfbe6?sid=3e53328b-2cc4-4ade-8dbd-d2635ce6a380>" %}


# Data Sources

## Adding a MongoDB Database

{% embed url="<https://www.loom.com/share/212a73c0525a49f096891de5d664c829?sid=d3301d83-884d-4d8a-8900-f6d6e836408f>" %}

## Adding a PostgreSQL Database (Using the Connection Details)

{% embed url="<https://www.loom.com/share/d66c7f1215c24d478ab22f032d07f49d?sid=e77c6095-b2a7-4dee-b033-b92fe26c27a7>" %}

## Adding a PostgreSQL Database (Using the Connection String)

{% embed url="<https://www.loom.com/share/c3e107e564d74dc296ff2f24fb998fa9?sid=a07cdb82-da59-4ed7-a6f9-d49736d875e2>" %}

## Adding a MYSQL Database (Using the Connection Details)

{% embed url="<https://www.loom.com/share/0d1cfb9cae064ac897209039a9ff1c13?sid=da9dfcc7-532c-4f99-982b-14f4a5488e07>" %}

## Adding a MYSQL Database (Using the Connection String)

{% embed url="<https://www.loom.com/share/e204bf01a4124299bdf81a886ab83b22?sid=4304ac78-5fc3-4ca7-96e9-275bd4e2b0c4>" %}


# Organization Management

## Invite a Team Member

{% embed url="<https://www.loom.com/share/a1395381c78f4b87af7a06d1d39ab296?sid=886e9a2e-5fa7-452f-b3cd-f041bdfdd2e8>" %}

## Join an Organization

{% embed url="<https://www.loom.com/share/d079308277a94c3a9850b33fea1ce196?sid=f7a1525f-3b87-40ee-acca-bf4f9b1fd95c>" %}


# Creating and Using Custom Queries

## Defining parameters when creating Custom Query endpoints

{% embed url="<https://www.loom.com/share/1a58ab6865734d899567634b5b872e5e?sid=464fd575-0e26-4322-9d97-abe1a880da01>" %}

## Using Custom Query Endpoints in Postman

{% embed url="<https://www.loom.com/share/2a30ccfe8d5b4ad8812b75eed2792ed0?sid=4321099f-94d1-459a-86d6-521cee715906>" %}


# Using the Schema Builder to build Relationships

## One-to-One Relationships

{% embed url="<https://www.loom.com/share/f947b78cbc14441f8201915788678f58?sid=2861ab24-85d8-40b6-a415-7af1cb9365e0>" %}

## One-to-Many Relationships

{% embed url="<https://www.loom.com/share/4bf347ce52e04622802c1dde1264975a?sid=2b194311-ae2a-4993-ad6f-21d552a4d10c>" %}

## Many-to-One Relationships

{% embed url="<https://www.loom.com/share/6453a10bc27d47649444f2a1cd64fb75?sid=92557b2f-12ca-49b2-a63b-34502a673223>" %}

## Many-to-Many Relationships:&#x20;

{% embed url="<https://www.loom.com/share/3b3a14ffea9c43949f866d7bb1a0928a?sid=583fbce4-75ad-4d07-ab47-97c5b31aafc0>" %}


# Mock Data Generation

## How to use the Data Generation feature

{% embed url="<https://www.loom.com/share/45d2558c5e97497889b4196c8809f4b1?sid=0d17c568-484f-426d-b384-393d84df7bc2>" %}

##


# Definitions

### Overview

Neurelo's data definition comprises of three key elements - Schema, Auto Generated APIs and Custom Queries. Definitions exist inside a project and are scoped only to that project.

Definitions are configured at a project level and can be deployed across different environments inside that project. Neurelo definitions are version controlled (using the notion of branches and commits) and include comprehensive documentation.

{% hint style="info" %}

#### Neurelo Data Definitions = Schema + Migrations + Auto Generated APIs + Custom APIs

{% endhint %}

**Schema:** Programmable representation of users data model for that specific project. Neurelo supports JSON and YAML codification of data models using [Neurelo's Schema Language](/neurelo-schema-language-nsl) definition.

**Auto Generated APIs and API Docs:** Neurelo instantly Auto Generates Data APIs (for all your CRUD operations across single or multiple entities and advanced queries) based on schema defined within the project. Neurelo generates [REST](/neurelo-api-reference-rest) and [GraphQL](/neurelo-api-reference-graphql) API endpoints.

**Custom Query Endpoints:** Custom Query endpoints feature allows users to define (or use Neurelo's AI Assist functionality to generate) database specific native query code, especially for complex queries, and instantly make them available as REST or GraphQL API endpoints.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FwaY8roBm7fNUbSYq8fp6%2FScreenshot%202024-01-11%20at%2011.08.37%E2%80%AFAM.png?alt=media&amp;token=fe655a24-c052-4a9c-b93d-f924fe8c0570" alt=""><figcaption></figcaption></figure>

### Accessing the Definitions Section in Neurelo

The Definitions section in Neurelo is an integral part of your project where you can manage and modify your database schema, custom queries, and view API documentation. Here’s how to navigate to this section:

1. **Locating the Definitions Section**:
   * On your Neurelo Dashboard, look at the sidebar (left pane).
   * The Definitions section is conveniently located right below the "Dashboard" section and above the "Environments" section.
2. **Opening the Definitions Section**:
   * Click on the "Definitions" option for the project.&#x20;
   * This action will open up the Definitions section, where you can engage with various aspects of your project’s schema and related elements.

The Definitions section is a critical workspace for the project setup and customization. It offers tools and features to shape the data model and API structure of your project, ensuring that your database aligns perfectly with your project's requirements.


# Neurelo Schema Editor

### Overview

The [Neurelo Schema Language (NSL)](/neurelo-schema-language-nsl) is used to define entities, properties, relationships, and constraints of the schema definition for your project. The language is based on the [JSON Schema](https://json-schema.org/) spec, with added capabilities to accurately describe the relationships and constraints within the schema. NSL is a programmable representation of users data model for that specific project. Neurelo supports JSON and YAML codification of data models.&#x20;

{% hint style="info" %}
In Relational Databases (RDBMS), data models are referred to as E-R (Entity-Relation) models comprised of tables, columns, column types, relationships across tables, constraints (e.g. unique, not null)&#x20;

\
In Document Databases such as MongoDB, data models include collections and document structures
{% endhint %}

### Navigating the Schema Section in Neurelo

The Schema section in Neurelo is the core  part of the Definitions area, where you can interact with and manage your application's data models as the database schema. Here's how to navigate and utilize this section:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F9ZgX3XCQwOBH4brFh6Ix%2FScreenshot%202024-01-11%20at%2011.12.26%E2%80%AFAM.png?alt=media&amp;token=29ecec4f-54b0-474c-a04d-a8fcceafa20a" alt=""><figcaption></figcaption></figure>

1. **Accessing the Schema Section**:
   * The Schema section is located within the Definitions section of Neurelo.
   * It is accompanied by two other tabs: "Custom Queries" and "Docs".
2. **Using the Search Bar**:
   * At the top of the Schema section, there’s a Search bar.
   * Use this feature to quickly find specific objects or entities within your database schema.
3. **Modes of Working with Definitions**:
   * Neurelo offers three primary modes for working with your schema definitions: Schema Builder, JSON Editor, and YAML Editor.
   * Each mode caters to different preferences and requirements for handling schema definitions.
4. **Switching Between Modes**:
   * To switch between these modes, locate the dropdown menu on the right side of the dashboard.
   * This dropdown allows you to select the mode that best suits your current task or preference.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F4emkII0jKOG8Pv34huGz%2Fimage.png?alt=media&amp;token=b6fe200f-4c22-4137-8921-fbdf38ef69d9" alt=""><figcaption></figcaption></figure>

The Schema section in Neurelo provides a comprehensive and flexible workspace for managing database schemas, ensuring that you can tailor and refine your project's data structure according to specific needs and preferences.


# Schema Builder

### Overview

The Schema Builder Mode in the schema editor enables users to quickly create, update, manage and view their project level schema (data models) with a simple and intuitive UI.

{% hint style="info" %}
For more details and examples about Neurelo's Schema Language (NSL), check out the [NSL guide](/neurelo-schema-language-nsl)
{% endhint %}

### Exploring the Schema Builder in Neurelo

The Schema Builder in Neurelo is an interactive tool that allows you to visualize and modify the structure of your database. Here’s how you can navigate and use the Schema Builder:

#### **Viewing Objects**:

* The Schema Builder displays all objects defined in your database schema.
* Clicking on an object brings up detailed information in the Builder section of the page.
* You can add and delete objects from here

#### **Inspecting Object Details**:

* **Properties**: This section shows the properties of the selected object. Click on any property to view and edit its details. You can also create new properties.
* **Relationships**: Here you can see how the selected object relates to other objects in your database. You can add and edit relationships
* **Constraints:** This includes configurations such as unique, index and identifier for that object which you can add/delete/update from here.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FdtUA456vKReikZG6Km2O%2FScreenshot%202024-01-11%20at%2011.13.53%E2%80%AFAM.png?alt=media&amp;token=8ce7f9f6-ff10-4731-a862-7d4db61249e0" alt=""><figcaption></figcaption></figure>

#### **Editing Property Details**:

* **Type Format**: When a property is selected, you can define its type and format using a dropdown menu with options like "integer," "bigInt," "float," and others.
* **Property Settings**: Below the Type Format, there’s a list of checkboxes for settings such as "Identifier," "Unique," and "Nullable."

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FQnuAF4cQECBDqC1PxctK%2FScreenshot%202024-01-11%20at%201.54.16%E2%80%AFPM.png?alt=media&amp;token=4504d746-5813-4d41-abb8-a461a92807e8" alt=""><figcaption></figcaption></figure>

* **Description**: Add a description for the property for better understanding and documentation.
* **Source Settings**: Sometimes the property needs to be configured differently inside the actual database, different from the name of the property in Neurelo's schema.&#x20;

  * **Source Name**: Specify the name of this property inside the database
  * **Source Type**: Map the Neurelo type explicity to a particular type inside the database

  <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FFNCvGMO03QYgrLzllpel%2Fimage.png?alt=media&amp;token=b00a2a40-33ee-4418-ac3f-32327d5b101e" alt="" width="375"><figcaption></figcaption></figure>

#### **Configuring Default Settings for a Property**:

* **Default Type**: Choose between "value" and "function" from the dropdown. This setting determines the "default" handling for the property in the database.
* **Depending on the Default Type**:

  * If "value" is selected, you'll be prompted to enter a "Default Value"
  * If "function" is chosen, you'll need to specify a "Default Function"

  <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FJ1A0Z69q892ZfafpFYoz%2Fimage.png?alt=media&amp;token=7d275a23-db16-45a1-be2d-5dfc0c1b4afd" alt="" width="375"><figcaption></figcaption></figure>

{% hint style="info" %}
All changes made needed to be "Commit"'ed to use in other parts of the project. The commit part is covered in the next page and under "[Branches and Commits](/definitions/branches-and-commits)"
{% endhint %}

The Schema Builder is a comprehensive and useful tool within Neurelo that provides detailed viewing and editing capabilities for your database schema, ensuring that you can accurately define and refine the properties and relationships of your database objects.


# JSON/YAML Editor

{% hint style="info" %}
While this page covers the JSON Mode of the Neurelo Schema Editor, you can also use the YAML Mode of the editor by selecting the "YAML Editor" instead of the "JSON Editor" in the mode selector
{% endhint %}

### Utilizing the JSON Editor Mode in Neurelo

The JSON Editor mode in Neurelo is a feature for users who prefer to directly edit their schema as JSON for their database definitions. Here’s how you can navigate and use this mode:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F68SRlWn0yDGWQT4bB2bL%2FScreenshot%202024-01-11%20at%202.00.43%E2%80%AFPM.png?alt=media&amp;token=39a0ad2d-de0c-4db6-b549-e64dcb7aa347" alt=""><figcaption></figcaption></figure>

1. **Switching to JSON Editor Mode**:
   * Select "JSON Editor" from the dropdown menu in the Schema Builder.
   * The dashboard will transition to display the JSON representation of your database schema.
2. **Viewing and Editing JSON Schema as Code**:
   * In this mode, you’ll see the schema in JSON format outlining your "objects," "enums," and "inner objects
   * The Neurelo JSON Editor adheres to standard JSON Schema structures, allowing for familiarity and ease of use.
   * Make any desired changes directly in the JSON code. This is ideal for users comfortable with JSON syntax and schema structures.
3. **Committing Changes**:
   * If you make edits in the JSON Editor (or any of the editor modes), the "Commit" button becomes active, enabling you to commit your changes.
   * Click "Commit" after making changes. The schema is validated and df there are no errors, your changes will be committed. If errors exist, they need to be resolved before committing.
4. **Handling Errors**:

   * If an error is detected before committing (e.g., changing "authors" to "author", when "authors" is also being referenced in other parts of the schema), a pop-up will notify you of the error, and the "Commit" button will be disabled.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F9VqodelaPRmIg2uE5biN%2Fimage.png?alt=media&amp;token=604a6253-1ff1-4cdd-ba8d-11583dccc073" alt="" width="375"><figcaption></figcaption></figure>

   * To view and address these errors, click on "View Errors." This action will take you back to the editor, and a "Schema Errors" pane will open. The Schema Errors pane provides a detailed description of each error, allowing you to pinpoint and correct issues in your schema.

<div align="left" data-full-width="false"><figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FjQWFW5ugapaHuUJF8nJx%2FScreenshot%202024-01-11%20at%202.02.20%E2%80%AFPM.png?alt=media&amp;token=000c408c-fc81-4eb1-8c81-655ff8094330" alt=""><figcaption></figcaption></figure></div>

The JSON Editor mode in Neurelo offers a direct and flexible way to work with your database schema, catering to users who prefer hands-on control over their schema definitions by editing schema as JSON.

### Using the Prettify Feature in Neurelo’s JSON Editor

Neurelo’s JSON Editor includes a handy "Prettify" feature designed to enhance the readability and organization of your JSON code. This feature is especially useful for engineers and developers who work extensively with JSON structures. Here’s how to use it:

1. **Locating the Prettify Icon**:

   * In the JSON Editor, look for a set of icons near the editing area.
   * The icon for the Prettify feature typically resembles a magic wand or a similar symbol indicating formatting or beautification.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fm7PPkMBEX3rRHXq9MYbO%2Fimage.png?alt=media&amp;token=f0681c4c-475b-41f2-8686-0c39081e528e" alt="" width="375"><figcaption></figcaption></figure>
2. **Applying the Prettify Feature**:
   * Click on the Prettify icon (magic wand).
   * This action instantly formats your JSON code, organizing it into a more readable and structured format.
3. **Benefits of Prettifying JSON Code**:
   * The Prettify feature aids in enhancing the clarity of your code by adjusting indentation, aligning elements, and making the overall structure more visually appealing and easier to navigate.
   * It’s particularly beneficial when working with large or complex JSON schemas, as it helps in quickly identifying elements, properties, and values.

Using the Prettify feature in Neurelo's JSON Editor can significantly improve the efficiency of editing and reviewing JSON schemas, making the code maintenance process more streamlined and manageable.

### Using the View Differences Feature in Neurelo’s JSON Editor

Neurelo’s JSON Editor includes a useful "View Diff" feature that allows you to compare your current edits with the most recent commit. This is particularly useful for tracking modifications and ensuring accuracy in your changes. Here’s how to use this feature:

1. **Locating the View Differences Icon**:

   * In the JSON Editor, look for a set of icons, as indicated in the provided image.
   * Identify the icon for the View Difference feature, usually represented by a dot and arrow symbol, situated next to the Prettify icon.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F6AlQmHSlnNoNmgCHvPvY%2Fimage.png?alt=media&amp;token=ab04868f-5f5b-42a1-a470-6dc4495daf24" alt="" width="375"><figcaption></figcaption></figure>
2. **Activating View Diff**:
   * Click on the View Diff icon.
   * This action splits the editor into two sections: the left side displays the most recent commit, and the right side shows your modified version.
3. **Understanding the Highlights and Indicators**:

   * **Light Color Highlight**: Lines with changes are marked with a light color highlight, making it easy to spot where modifications have occurred.
   * **Dark Color Highlight**: Within those lines, specific words, values, or characters that have been altered are indicated with a darker shade. This feature pinpoints the exact changes made.
   * **Blank Gray Space with Slant Lines**: Any sections of code that have been completely removed are indicated with blank gray spaces featuring slant gray lines.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fmw37FFMy1nf4tpawqLgQ%2FScreenshot%202024-01-11%20at%202.06.27%E2%80%AFPM.png?alt=media&amp;token=175262f4-5622-43c4-81ff-90ba8f51eddb" alt=""><figcaption></figcaption></figure>
4. **Comparing Changes Effectively**:
   * The side-by-side comparison allows for an efficient review of changes, helping you to quickly identify additions, deletions, or modifications in the code.
   * This feature is particularly helpful in complex editing scenarios where multiple changes are made, ensuring that no unintended alterations go unnoticed.

The View Difference feature in Neurelo’s JSON Editor enhances your code editing experience by providing a clear and intuitive way to track and review changes made to your JSON schema.

### Using the Validate Schema Feature in Neurelo

After making changes to your schema JSON in Neurelo’s JSON Editor, it’s crucial to ensure that everything is correct before committing. The "Validate Schema" feature is designed to check your JSON schema for any errors or inconsistencies. Here’s how to use this feature:

1. **Locating the Validate Schema Icon**:

   * Refer to the provided image to locate the set of icons in the JSON Editor.
   * Find the "Validate Schema" icon, typically represented by a symbol indicative of checking or validation.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FM3s5mrHRaDQempK9RFlf%2Fimage.png?alt=media&amp;token=685764c5-a9df-444b-9316-5422d3158587" alt=""><figcaption></figcaption></figure>
2. **Initiating Schema Validation**:
   * Click on the "Validate Schema" icon.
   * This action triggers an automatic validation process for your JSON schema.
3. **Identifying and Handling Errors**:
   * If there are any errors in your schema, a red toast notification will appear at the bottom of the editor stating, "The schema definition has x error(s)."
   * Next to this notification, you’ll find a "View Errors" button.
   * If the schema is valid, there will be a green notification toast at the bottom of the editor indicating that the schema is valid.&#x20;
4. **Viewing Detailed Errors**:

   * Click on "View Errors" to open the "Schema Errors" pane.
   * This pane will display detailed information about each error, including its location and nature.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FgWmk0l6Qlh64YQ5lnhXJ%2FScreenshot%202024-01-11%20at%202.10.07%E2%80%AFPM.png?alt=media&amp;token=1fd0e519-d5d2-43bc-8e54-e5f28993ffb3" alt=""><figcaption></figcaption></figure>
5. **Correcting Errors Before Committing**:
   * Use the information in the Schema Errors pane to correct any mistakes or inconsistencies in your JSON code.
   * Ensuring your schema is error-free before committing can save significant time and effort and prevent issues in your project down the line.

{% hint style="success" %}
Even if you miss doing this step, Neurelo will validate the schema when you are performing the commit for your changes.&#x20;
{% endhint %}

The Validate Schema feature in Neurelo’s JSON Editor is a valuable tool for maintaining the integrity and accuracy of your project’s schema, helping you to identify and rectify errors before they impact your project.

### Utilizing the Introspect Feature in Neurelo

The "Introspect" feature in Neurelo synchronizes your Neurelo schema definitions with the current state of your source database. This feature is essential for ensuring that schema changes in your database are accurately reflected in Neurelo. Here’s how to use it:

1. **Locating the Introspect Icon**:
   * Refer to the provided image to locate the Introspect icon in the Neurelo interface.
2. **Initiating Introspection**:

   * Click on the "Introspect" icon to start the synchronization process.
   * A popup will appear, presenting you with a Data Source dropdown list. This list includes all databases added to your project.&#x20;

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fzhx3UOZ05dDMtlaLiM3m%2Fimage.png?alt=media&amp;token=12dbad72-3fc2-460d-b96d-a391ae410bd3" alt=""><figcaption></figcaption></figure>
3. **Selecting Your Data Source**:
   * From the dropdown, select the database you wish to synchronize with.
   * If you need to add a new data source, you’ll find an option for "New Data Source" as well.
4. **Starting the Introspection Process**:

   * After selecting the desired database, click "Start" to initiate the introspection.
   * A notification will inform you that "Introspection is in progress." This process will typically complete in a few seconds.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FhF54PWJ1NYI0kXAV21Yi%2Fimage.png?alt=media&amp;token=892db4a7-fd8b-4b33-9913-3f2c9472905f" alt="" width="375"><figcaption></figcaption></figure>
5. **Reviewing Schema Changes**:
   * Once introspection is complete, you’ll see a screen displaying the differences between your current schema in Neurelo and schema definition in the selected database. You can review the differences and make any necessary adjustments.
   * You have the option to "Cancel" if you do not wish to continue with the differences, or "Continue" if you want to update your schema in Neurelo.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F5SW4QRIi8HgpzruoX9et%2Fimage.png?alt=media&amp;token=7e0e397a-8eab-40a6-845e-90defbbcc43c" alt=""><figcaption></figcaption></figure>

6. **Updating Your Schema**:

* Clicking "Continue" will create a new commit and update your current Neurelo schema with the latest information fetched from your original database.
* This action ensures that your Neurelo project remains up-to-date and aligned with your source database.

### Using the Reset to Last Commit Feature in Neurelo

The "Reset to Last Commit" feature in Neurelo reverts their schema edits back to the state of the most recent commit. Here’s how to use this feature:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FdFvbwZ0wWpApAlP3rEsd%2Fimage.png?alt=media&amp;token=99a7150e-0996-4e0d-91c5-54c925c1f5f3" alt="" width="375"><figcaption></figcaption></figure>

1. **Locating the Reset to Last Commit Button**:
   * Find the "Reset to Last Commit" button in the Neurelo interface. It is typically located next to the "Introspect" tool, forming part of the array of schema editor options.
2. **Initiating the Reset**:
   * Click on the "Reset to Last Commit" button.
   * This action will instantly revert all your current unsaved changes in the schema back to the state of the last committed version.
3. **Confirming the Reset Action**:
   * Depending on Neurelo’s interface, you might receive a prompt asking for confirmation to proceed with the reset. This is to ensure that you are aware of the changes being reversed.
   * Confirm the action if prompted, to complete the reset process.
4. **Effects of the Reset**:
   * Once you reset to the last commit, any changes or edits made to the schema in the editor will be discarded and the last commited version will be loaded in the editor.
   * This feature is particularly useful when the changes made are extensive and rolling back manually would be time-consuming or complex.

The "Reset to Last Commit" feature is a useful component of Neurelo's schema editing tools, providing a quick way to revert to a previous stable state of your schema, thereby safeguarding against unintended modifications or errors.


# Schema Visualization: Entity-Relationship Diagram (ERD)

## Overview

Visual Data Schema, often presented in the Entity-Relationship Diagram (ERD) format, plays a pivotal role in understanding and designing complex database schemas. With an ERD, developers can visually understand the relationships between different entities, such as tables, in their database schema. This visual representation offers a clear and intuitive overview of the database structure, facilitating effective communication among team members and aiding in the identification of potential design flaws or optimization opportunities. Additionally, ERD views serve as valuable documentation for both current and future development efforts, ensuring consistency and coherence in database design.

Neurelo supports schema visualization for PostgreSQL, MySQL and MongoDB, providing developers with intuitive insights into their database schema layout.

## Exploring the Schema Visualization in Neurelo

The Schema Visualization feature allows you to visualize the structure of your database in the ERD view. Here’s how you can navigate and use Schema Visualization:

### **Viewing the ERD**

* Access the "Definition" section for your project from the left navigation bar.
* This will display the Schema in either JSON, YAML or the Schema Builder view based on your last selectiom
* Next to the mode selector near the top right, you will see the icon toolbar. In there, click on the "ERD" icon as show below

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FufItPfpjyh1jHGfXmafg%2Ferd%20icon%20updated.png?alt=media&amp;token=db95aeab-3f87-4e42-8480-eb61a0109497" alt=""><figcaption></figcaption></figure>

### **Inspecting ERD Details**:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FuuRjd0Beu17rz4rrr9Du%2FCleanShot%202024-03-11%20at%2017.33.01%402x.png?alt=media&amp;token=76030e73-b179-4ebe-bdc8-4c720b0784af" alt="" width="563"><figcaption></figcaption></figure>

* **Block**: A block in an ERD view represents an object (table/collection in PostgreSQL and MySQL) or an innerObject (MongoDB only - embedded document) in a database, with each row representing a specific attribute or property of that entity.
* **Lines**: In an ERD view, a line shows that entities are linked in the database model. Neurelo's ERD view enhances clarity with multi-color connection lines, resembling a rainbow.

{% hint style="success" %}
You can click on a block to narrow the focus to only those entities that are connected to the selected entity&#x20;
{% endhint %}

{% hint style="success" %}
You can click on particular line linking two blocks, to focus on the two entities connected with that line
{% endhint %}

* **Navigation Helper:** To aid in navigating extensive schemas, Neurelo offers a visual navigation helper located at the bottom right of the screen, providing users with a clear indication of their current location within the expansive data schema.
* **ERD Settings:** Neurelo offers users to customize ERD navigation direction, background, and connection line colors, tailoring the visual representation to suit their preferences and workflow.

####


# Custom APIs for Complex Queries

### Overview

You can create Custom REST or GraphQL API endpoints for your user-defined complex queries for specific read/write operations on the database. &#x20;

Neurelo auto-generates a rich set of APIs from your schema for the project. However, there are times when you need to extend this capability for complex operations you may want to run from your application. A complex query normally involves more intricate and sophisticated operations than can be supported using Neurelo's Auto-Generated APIs.&#x20;

* Custom APIs for Complex Queries is a powerful feature that allows users to leverage native query code (SQL or MQL), save them as API endpoints, and run operations in the database using these endpoints from your application.&#x20;
* Custom APIs can be created for MySQL, PostgreSQL, or MongoDB databases, and can be integrated into a wide range of applications and websites.
* Custom APIs are supported both as REST endpoints or GraphQL endpoints

Complex queries usually involve multiple criteria, conditions, or operations to extract specific and nuanced information from the database.&#x20;

For example in relational databases, complex queries often include features such as:

1. **Multiple Tables:** Involving complex joins across multiple database tables to retrieve data from related sources.
2. **Aggregation:** Using aggregate functions (like `sum`, `avg`, `count`) to perform calculations on groups of data.
3. **Subqueries:** Nesting one query inside another to retrieve data in a step-by-step manner.
4. **Conditional Logic:** Applying complex conditions using logical operators (AND, OR) for filtering data based on specific criteria.

While many of these complex queries can be performed using Neurelo's Auto-Generated API endpoints, sometimes users need to extend the capability to beyond what can be done with the auto-generated APIs.&#x20;

Neurelo offers users the ability to write and test custom queries against their data sources in a project and to create API endpoints from these custom queries. This capability allows users to extend Neurelo's APIs and to have complete flexibility to query and update the data from their data sources.&#x20;

### Navigating and Utilizing the Custom Queries Section in Neurelo

Here’s how to access and use this section:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FlWMpQTRfrIM6EUnyWXdI%2FScreenshot%202024-01-11%20at%202.57.04%E2%80%AFPM.png?alt=media&amp;token=57e578b2-0de6-448b-8bff-c2669c30e37b" alt=""><figcaption></figcaption></figure>

1. **Accessing Custom Queries**:
   * Navigate to the "Definitions" section on your Neurelo Dashboard inside a project. Within Definitions, you will fine the tabs "Schema," "Custom Queries," and "Docs."
   * Click on the "Custom Queries" tab to enter this section.
2. **Capabilities in Custom Queries Section**:
   * **Write Custom Queries**: Utilize the query editor to write and refine custom database queries.
   * **Search Feature**: Browse through all your available custom queries using the search functionality.
   * **Create API Endpoints**: Generate API endpoints with methods like "GET" "POST", "PATCH", and "DELETE" for REST and turning your queries into accessible endpoints for developers. You can also build Custom APIs for GraphQL for Queries or Mutations.&#x20;
   * **Custom API Endpoint Naming**: Assign names to your Custom Query API endpoints. Once deployed, you can call these endpoints using the assigned name at&#x20;
     * `/custom/<endpointName>` for REST using the configured HTTP method&#x20;
     * `custom_endpointName` for GraphQL as the field name in a Query or Mutation
   * **AI-Assisted Query Generation**: Leverage AI assistance to generate custom queries using conversational text, simplifying the query creation process.
   * **Test Queries**: Test your queries written in the editor to ensure accuracy and expected outcomes.
   * **Set Execution Timeouts**: Define upper limits on the execution time for your queries, ranging from 0 to 60,000 milliseconds, to have predictable performance. If the query runs longer for the configured execution time, it will be terminated.&#x20;
   * **Commit on Branches**: Commit your queries into your working branch.&#x20;

The Custom Queries workspace in Neurelo is a powerful capability, empowering you to manage extend Neurelo capabilities for your application by utilizing AI for enhanced query code generation, all contributing to a more efficient and powerful application development process.


# Write and Commit Custom Queries

### Overview

The Custom Queries section in Neurelo is a dynamic workspace where you can manage and create custom queries in native query code. Here’s a step-by-step guide to writing your custom queries:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FqXfqw6ogcBv2rzjCNrlO%2FScreenshot%202024-01-11%20at%202.57.04%E2%80%AFPM.png?alt=media&amp;token=651d9234-f28a-4f1f-9442-61a9a14de009" alt=""><figcaption></figcaption></figure>

### Writing Custom Queries in Neurelo

Creating custom queries in Neurelo is a straightforward process, facilitated by a user-friendly query editor and built-in AI Assist capabilities. Here’s a step-by-step guide to writing your custom queries:

1. **Locating the Query Editor**:
   * Inside your Project, go to the Definition page from the left navigation panel.
   * Click on the Custom Query tab, this will open the custom query editor. This is where you can review and write your queries.
2. **Starting a New Custom Query**:

   * When accessing the Custom Query section for the first time, you have two options to start creating custom queries:
     * Look for a section labeled "Custom Queries" with a "Plus" sign next to it.
     * Alternatively, you can click on the "New" button located centrally on the page.
   * Clicking either option will open a pop-up prompt for creating a new endpoint

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FOEuzPg8hHaeny4QfYG9s%2Fcq1.png?alt=media&amp;token=d1ac9ad1-d75a-4573-bb5e-cc70c28b06c3" alt=""><figcaption></figcaption></figure>
3. **API Mode and Naming the Endpoint**:

   * In the pop-up, you will be asked to select a mode (REST/GraphQL) for your endpoint and provide an "Endpoint Name."
   * Remember, endpoint names can only contain alphanumeric characters, underscores, and dashes (no spaces). Examples: `cityQuery`, `city_query`, `QUERY500`, `200query`.
   * After entering a valid name, you can either finalize the creation by clicking "Submit",  or cancel by clicking "Cancel"

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FCKWm2ZOhgVfy457DdfuD%2Fcq2.png?alt=media&amp;token=834f265d-d30f-4512-9692-38639626f47f" alt="" width="375"><figcaption></figcaption></figure>
4. **Writing the Query**:

   * Once you submit the endpoint name, the query editor opens for you to type your query.
   * For instance, you can write a query like such as:

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F3XzacTM2Jk4oYOcyNxo1%2FScreenshot%202024-01-11%20at%203.02.25%E2%80%AFPM.png?alt=media&amp;token=fa71b745-bb39-4e4e-8ef0-3dc090deb72a" alt=""><figcaption></figcaption></figure>
5. **Prettifying Your Query**:

   * To enhance readability, you can prettify your query format.
   * Locate and click the "Prettify" button at the top of the Query editor. This will instantly format your query into a more readable and user-friendly layout.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F5Qm6ML6xaV0HsS8mAVWC%2FScreenshot%202024-01-11%20at%203.00.54%E2%80%AFPM.png?alt=media&amp;token=cbac4c35-932f-43d8-ba53-af49ee3640bf" alt=""><figcaption></figcaption></figure>
6. **Testing your Custom Query**

   * After writing a query, you can test the query right on the editing page.
   * Look for "▶️ Test Query" button. Clicking this will open a test playground
   * Enter the "API Key" for the running environment that you wish test this custom query against

   <mark style="color:orange;">Note - this query will actually run against the data source in use in the environment. You will need to acknowledge this by selecting the checkbox to be able to try this query</mark>

   * You will see the data-set result or any error (in case query was not formed correctly) in the playground window
7. **Saving Custom Queries (Commit)**
   * After writing a query, you will need to save it for future use.
   * Look for a "Commit" on the page. Clicking this will store your query within Neurelo and instantly create an API endpoint for this query which can be used in an environment.
8. **Searching for Saved Queries**:
   * To find a previously saved query, use the search feature on the Custom Query page.
   * Enter keywords or the exact name of the query in the search bar.
   * The search functionality helps you quickly locate the desired query among all the queries you've saved.

{% hint style="info" %}
Don’t forget to ***Commit*** your Custom Query before leaving the page. Committing will also automatically version your custom query.
{% endhint %}

These features on the Custom Query page allow for efficient management of your custom queries. Whether you're building complex queries for advanced data retrieval or simply experimenting with different data manipulations, Neurelo's environment supports and streamlines your workflow.


# AI-Assisted Query Generation

Using Neurelo’s AI Assist capability to generate Custom Queries

Custom Query with AI Assist runs on a smart AI engine based on a Large Language Model (LLM). This setup allows developers to easily generate query code, test and confirm the query, and quickly deploy complex queries as custom API endpoints without a hitch.

The AI assist part makes building these queries a breeze by giving clever suggestions and optimizations. The AI is trained to understand the specific language and rules of databases (MongoDB, PostgreSQL, MySQL), including syntax and meaning, along with the context of your application like schema and data models.

### Utilizing AI-Assisted Query Generation in Neurelo

This feature is particularly useful when you need to generate complex queries quickly and accurately. Here’s how to use it:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FwEo05lAfOfL8MAFqe3il%2FScreenshot%202024-01-11%20at%203.07.45%E2%80%AFPM.png?alt=media&amp;token=e1238ff6-d8b3-4aed-8490-5fabd5f65b32" alt=""><figcaption></figcaption></figure>

1. **Accessing AI Assist**:
   * Locate the "AI Assist" button on the Custom Query page. This button is situated next to the "Test Query" button. Refer to the provided image for its exact location.
   * Click on the "AI Assist" button to activate the feature.
2. **Entering Your Query Prompt**:
   * Upon clicking AI Assist, a side panel on the right will appear prompting you to enter your query requirements.
   * For example, if you need to retrieve all authors who have written a certain number of books, input a prompt that clearly states this requirement.
3. **Sending the Query Prompt**:
   * After typing your prompt, click the "Send" button.
   * The AI Assist module will then process your request and start generating the corresponding query.
4. **Reviewing the Generated Query**:
   * Once the query generation is complete, the AI Assist will display the query based on your provided prompt, as illustrated in the below image.
   * You can review this query to ensure it meets your requirements and make any necessary adjustments.
5. **Advantages of AI-Assisted Query Generation**:
   * This feature saves time and reduces the complexity involved in manually writing intricate queries.
   * It’s particularly beneficial for users who may not be proficient in query syntax but require specific data retrieval.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FqhgST30GB5Aw6zJCT3wd%2FScreenshot%202024-01-11%20at%203.06.51%E2%80%AFPM.png?alt=media&amp;token=534be30b-ef8e-4aa1-ac19-c05ba91bfeb1" alt=""><figcaption></figcaption></figure>

{% hint style="success" %}
The accuracy of the generated queries is high but not 100%. Neurelo uses OpenAI's models for generating these queries and continues to work on fine-tuning them, however as the AI technology is still evolving, sometimes this feature may not work as expected. Please try re-generating with the same prompt or use a different prompt if you don’t get the results you expected, or see a failure.&#x20;

You can also use the generated query as a starting point and edit those queries in the editor to get to the exact query you are looking to build
{% endhint %}

### Additional Options in Neurelo's AI-Assisted Query Generation

Beyond simply generating queries, Neurelo’s AI-Assisted Query Generation feature offers several tools to enhance user experience and efficiency. Here's an overview of these tools:

1. **"Use This" Option**:
   * The "Use This" option allows you to instantly copy the AI-generated query to the Query Editor.
   * Clicking this button transfers the query, making it ready for further editing, testing, or direct use.
2. **"Delete All Prompts" Option**:
   * If you have a list of prompts or queries previously generated, the "Delete All Prompts" options enables you to erase them all at once.
   * This is useful for clearing out old or irrelevant queries to maintain a clean workspace.
3. **API Key Configuration**:
   * The "API Key Configuration" option (Settings icon on the top right) lets you choose between using your own OpenAI API key or Neurelo's key (default). It is recommended to use your own OpenAI API key if possible.&#x20;
4. **"Re-generate" Option**:
   * If the generated query doesn’t meet your expectations, or you need a different iteration, the "Re-generate" tool allows you to create a new version of the query based on the same prompt. This feature is useful for refining query outputs.
5. **Copy Prompt Option**:
   * The copy icon next to a prompt enables you to quickly copy the text of the prompt. This is handy for reusing or referencing a prompt in other applications or contexts.
6. **Delete Option**:
   * For removing a specific prompt and results, use the "Delete" option.
   * This option helps in managing your query list by allowing you to remove individual queries that are no longer needed.

{% hint style="info" %}
Neurelo uses OpenAI to generate these queries and sends your schema to their models to be able to generate the queries for the prompt. You can use your own OpenAI API key if you would like the schema to sent to OpenAI in your account, rather than using Neurelo's account. No data from your database or other information about your organization or projects is send as part of this process.&#x20;

\
Here are OpenAI's privacy terms - <https://openai.com/enterprise-privacy>\
\
Please do not use this feature if you don't want your schema to be sent to OpenAI.&#x20;
{% endhint %}

These capabilities in the AI-Assisted Query Generation feature of Neurelo enhance the usability of the query generation process, offering options for customization, configuration, and organization.


# Deploying Custom API Endpoints

### Overview

Neurelo instantly creates an API end point for every custom query once it is committed in a branch. This custom query API end point can be deployed to one or many environments inside a project. Here is how to use it:

### Deploying your custom query endpoints with commit:

* Create a custom query using AI Assist or manually.
* Click on "Commit" to save this custom query
* At the time of the commit, Neurelo offers a choice to deploy this custom query to one or more running environment if there are no schema related migrations needed in the environment.
  * Select environment(s) that you would like to deploy this custom query as part of the commit step. You can always also go into the Environments
  * Your environment should be ready to go. Make sure you have the appropriate environment API Key so you can use it to hit the Custom Query Endpoint
  * You can access this custom query API endpoint at the URL for your Environment&#x20;
    * For REST, this endpoint can be accessed at `${API_URL_BASE}/custom/<endpointName>` (e.g. custom/authorsNumBooks) using the configured HTTP method (`GET`/`POST`/`PATCH`/`DELETE`) for the endpoint
    * For GraphQL, this endpoint can be accessed with a `POST` at `${API_URL_BASE}/graphql` using `custom_<endpointName>` (e.g. custom\_authorsNumBooks) as the field name in a Query or Mutation operation.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F9GPSajEXgZ5rtWD5JKmM%2FScreenshot%202024-01-11%20at%203.11.50%E2%80%AFPM.png?alt=media&amp;token=4ee2171d-6011-4e7b-b216-74e586a28f5e" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
If the "Deploy" option is not offered as part of the commit step (because migrations are needed in the environment) or you want to skip the "Deploy" step here, you can deploy this Commit later from Environment settings option.
{% endhint %}

### Deploying your custom query endpoints from Environment settings:

* To deploy custom queries in a specific environment, access the specific environment from the left navigation panel under a project
* You must Stop Runner sfrom the top right side of the page. And once the runners have been stopped, you can select the appropriate Commit of the Definition to be used for the environment from the Commit drop down right next to the Start/Stop Runner button
* Once the appropriate definition has been selected, click on Start Runner. Runners should start in a few seconds and the new definition would be deployed and be live in that specific environment.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FkLCjZd6Na7r2PpJI7rDI%2FScreenshot%202024-01-11%20at%203.16.12%E2%80%AFPM.png?alt=media&amp;token=d981284f-ae1e-493d-9269-bf85c28dc063" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
You can test your custom query using any HTTP Client (Postman, Insomnia, or even Curl) and write a request with the following format:

* `REST: GET/POST/PATCH/DELETE ${API_URL_BASE}/custom/<your_custom_query_name>`
* `GraphQL: Query or Mutation with custom_<endpointName> as the field name at POST ${API_URL_BASE}/graphQL`&#x20;

Headers needed:

`X-API-KEY`: `Your_Environment_API_KEY`
{% endhint %}

{% hint style="danger" %}
Custom Query Endpoints currently are only supported with API Keys that have both Read and Write permissions. Custom Query endpoints will not work with Read-Only keys and will return a "403 - Forbidden" error.&#x20;
{% endhint %}


# Using Variables in your Custom Query

### Overview

Neurelo custom queries support variables so that values can be passed in to your queries during run time execution. Here is how to add a variable"

```sql
SELECT * FROM "User" where id = {{ id }}
```

In the above query, {{ id }} is a variable that requires the user to pass the value of "id" at the when calling the endpoint for run-time execution.

{% hint style="info" %}
When you add a variable to a custom query, remember to specify the data-type for the variable
{% endhint %}

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fe9nLfAU9pTV6UJjpwIGE%2FScreenshot%202024-01-11%20at%203.19.27%E2%80%AFPM.png?alt=media&amp;token=e79e3e54-8215-48f1-9fac-01747c9517ae" alt=""><figcaption></figcaption></figure>

### Accessing custom query API endpoints with variables

Once you have a custom query with variables saved and deployed, you can use them depending on the `HTTP Method` defined in the custom query

* GET & DELETE methods will use the query string params to pass the values for the variables in the request URL. e.g.

  `${API_URL}/custom/query?id=1`
* POST, PATCH & PUT methods will use values for the variables specified in the request body, assuming the body is a valid JSON:

```sql
{
  "id": 1,
  "anotherParameter": "Here"
}
```

### Important considerations

* Variables do not need to be wrapped between single or double quotes for string datatypes, as we do the right parsing in our back end.

```sql
## Wrong
SELECT * FROM "Users" where id = '{{ id }}'

## Correct
SELECT * FROM "Users" where id = {{ id }}
```

* SQL Queries run as [Parametrized Queries](https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html), meaning queries are protected from SQL Injection.
* Supported variable types are:
  * Int
  * String
  * Array
  * Boolean
  * Float
* A `List` variables purpose is to provide a list of values to be **spread** as the different elements of an array to be used in an `IN` clause in SQL, so that your queries can look like this:

```sql
SELECT * FROM users WHERE id IN {{ ids }}

## Can turn into
SELECT * FROM users where id IN ($id1, $id2, ...)
```


# Branches and Commits

### Overview

Neurelo provides a Git style Version Control System (VCS) for all your data access meta-data. This meta-data set is called "Definitions" in Neurelo and comprises Schema (as code), Auto-generated APIs and Custom Query Endpoints.&#x20;

It helps you keep track of changes, so you can easily go back to an earlier version or review changes made over time. It's a handy tool that ensures your development journey is organized and you can undo or redo things whenever needed.

### Navigating and Managing Branches in Neurelo

In Neurelo, branches are used for managing different versions or stages of your project. Here’s how you can navigate and create branches:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F6KHvPuJP4LT3FWZOpqdm%2FScreenshot%202024-01-11%20at%203.20.48%E2%80%AFPM.png?alt=media&amp;token=1d24902f-bc89-4638-9ac7-a9d83687e123" alt=""><figcaption></figcaption></figure>

1. **Locating Branches**:
   * Refer to the provided screenshot to find the "Branches" option.
   * On the Definitions page, you’ll see a dropdown indicating the current branch, usually set to the main branch by default.
2. **Viewing All Branches**:

   * Click on "View All" in the branch dropdown to be redirected to the "Branches" section.
   * Here, you can view all the branches you have created.
     * Toggle "Include Other Branches" to switch the display between only the "Active Branches" and "All Branches".
   * If you have multiple branches, use the search bar to find a specific branch quickly.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FT2TOpunaMje1Lt1DzbGL%2FScreenshot%202024-01-11%20at%203.22.05%E2%80%AFPM.png?alt=media&amp;token=ff8bd812-6d2b-47ae-9c9a-6ef3f0c7d2b6" alt=""><figcaption></figcaption></figure>
3. **Creating a New Branch**:
   * You can create a new branch from either the Definitions page or directly in the Branches section.
   * **From Definitions Page**: Click on the branch dropdown and select "New Branch".
   * **From Branches Section**: Go to the Branches section (by clicking "View All" from the Definitions page). Click the "New" button.
4. **Creating a Branch - The Process**:

   * Clicking "New Branch" (inside the drop down) or "New" (on the Branches sub-section) triggers a popup for creating a new branch.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FQFv3D8APoG1HeE6xEqm6%2Fimage.png?alt=media&amp;token=d3ba1741-5171-4cea-914f-eb9974b44720" alt="" width="375"><figcaption></figcaption></figure>

   * Enter the "Branch Name" and click on "Submit" to create the branch.
   * The new branch will appear in the branch dropdown on both the Definitions page and the Branches section.

   Branches View:

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FLBwnKn5J2FpcK00OJzbs%2Fimage.png?alt=media&amp;token=8771e3ba-22ac-4f42-87ad-1bbba4d63c95" alt="" width="563"><figcaption></figcaption></figure>

   Definitions Editor View:

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FdMU2xGjqe6ufV27QgUpE%2Fimage.png?alt=media&amp;token=c3bd4411-7eee-4f0e-b5ec-55d1a34dfd7a" alt="" width="375"><figcaption></figcaption></figure>
5. **Navigating Back to Definitions**:
   * To return to the Definitions page, click on the small back arrow located before the "Branches" title.

This functionality allows for efficient management of different project versions or stages, providing flexibility and control over your project’s development in Neurelo.

### History (of Commits)

The History button is located right next to the branch button. Clicking on this will show the history of your previous commits on your branches.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FovbRmSBhgdaVWdUzEB0O%2Fimage.png?alt=media&amp;token=f374ebd2-0f07-4401-b4a4-716532d3d6ce" alt="" width="563"><figcaption></figcaption></figure>

### View a specific Commit

You can select a particular previous commit from the commit history list and click on View commit button. This will open a new screen with the details of selected commit. The page opens in "Diff mode" by default where changes in this commit (schema as well as custom queries) are highlighted

The diff mode is enabled by default, you can disable the diff mode by sliding the Diff mode toggle button to see all the definitions in the commit.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FvbLWbk1dDsnyRL9mxBbp%2FScreenshot%202024-01-11%20at%203.23.30%E2%80%AFPM.png?alt=media&amp;token=1d8c1d38-4bfc-4bea-ad69-8c83c7eac077" alt=""><figcaption></figcaption></figure>


# API Docs

### Overview

API documentation is auto-generated for your schema definitions and is intended to provide an overview of the APIs Neurelo generates based on your data definition. It will go into detail on how to perform operations using these APIs using a sample schema as a reference. You can then apply these concepts and patterns to your own schema. Reference documentation generated specifically for your data definition is included in the API documentation.

Neurelo provides two types of APIs that are automatically generated and available for use.&#x20;

* The REST API has predictable resource-oriented URLs, accepts JSON-encoded request bodies, returns JSON-encoded responses, and uses standard HTTP response codes, authentication, and verbs.&#x20;
* The GraphQL API exposes a single endpoint where clients can send GraphQL queries or mutations and a strictly-typed schema that be be shared across consumers.&#x20;

You can toggle between the GraphQL and REST API documentation above.

{% hint style="info" %}
Reference - [Neurelo Supported Databases](/references/supported-databases)&#x20;
{% endhint %}

### Exploring API Docs in Neurelo

Here is how you can access and navigate the Auto Generated API docs:

1. Viewing API Docs at the definitions level:

   * Step into your project from Neurelo's dashboard
   * Inside the project, select Definition from left navigation panel. This should open a new page with different definition components - Schema, Custom Query and API Docs
   * Click on API Docs on this screen. This will load a detailed API Doc on your screen.
   * By default, the page will load with RESTful API. You can select GraphQL API from the toggle button on this screen
   * The inner left navigation panel, provides all the different exploration options for this API endpoint set<br>

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FxE3MfqSwkF94JaSw3DUD%2FScreenshot%202024-01-11%20at%202.15.40%E2%80%AFPM.png?alt=media&amp;token=303622f0-1292-4ee0-b359-1142df173993" alt=""><figcaption></figcaption></figure>
2. Viewing API Docs at the definitions level:

   * Navigate into your project from Neurelo's dashboard
   * Inside the project, select Environments from the left navigation panel. This should open a new page that list all your Environments inside this project.
   * Select an environment. This will open up a detailed environment page. By default this page loads the APIs page.<br>

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F9lAZyJoRIa6Nuujm9bru%2FScreenshot%202024-01-11%20at%202.16.44%E2%80%AFPM.png?alt=media&amp;token=faece9bb-cf4f-4bdb-a6ec-449bf24d15a2" alt=""><figcaption></figcaption></figure>

   * From here, you can test any API using Neurelo's Playground feature. Click "Play" icon from the right side of the screen.&#x20;
   * This will open a Playground page with all APIs listed in the left navigation panel. Select any API, enter the required information including the API Key and hit the Send button
   * The Playground should display the results or error accordingly.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FO4WwkIiS65UUpS7SueVQ%2FScreenshot%202024-01-11%20at%202.22.44%E2%80%AFPM.png?alt=media&amp;token=e56261fa-088f-43d4-b81a-2775b616e616" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
While using Neurelo's API Playground, please have the  environment specific API Key ready as Neurelo does not store your API Keys
{% endhint %}


# Environments

### Overview

Neurelo Environments align naturally with typical Software Development LifeCycles (SDLC) as developers work on their application from development to testing to production. Developers can create and run various environments and for each environment they can provision definitions (JSON Schema, APIs, Custom queries), and link the working database. This process ensures that all the necessary components work together as a run-time workspace, letting developers build, debug and test their changes seamlessly from their application to Neurelo's  environment to the connected database.

For each project, Neurelo supports multiple environments allowing users to seamlessly operate across ephemeral dev and test workspaces to robust and persisting staging and prod deployments.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F66qnO4tb3RqvIC1xwnPR%2FScreenshot%202024-01-11%20at%203.24.36%E2%80%AFPM.png?alt=media&amp;token=96f86638-45e2-4c11-ba2f-33d2eb841ed2" alt=""><figcaption></figcaption></figure>

### Components of an Environment

Three key components of each environment:

1. **Data Source:** Each environment must connect with one database. Users can change the connected database anytime from Environment settings page.
2. **Definitions to be used:** Each environment must have a commit of the definitions for the project attached to it. This ensures all the relevant meta-data (Schema, APIs, Custom Query Endpoints) are provisioned in this environment and map to the connected database. Users can change the attached definition for an environment by stopping the runners and changing the commit being used. Runners can be restarted once the commit has been changed.&#x20;
3. **Runner:** A Neurelo runner is the API handling engine for an environment, which handles the API requests between applications and dat sources. The runners operate by listening for incoming API requests, translating those requests into the corresponding datasource queries and then promptly responds with the relevant and appropriate information from the datasource.&#x20;

{% hint style="danger" %}
To conserve platform resources, running environments which are inactive (no api calls) for more than 7 days may be automatically stopped. When the runners are auto-stopped for inactive environments, their configuration is not impacted. Runners can be restarted anytime by clicking on "Start Runners" when you need to use the environment again.&#x20;
{% endhint %}

### **Exploring the Environments Section**:

* In the Environments section, you'll find various options and features for building, debugging, testing, and managing your APIs.
* This section is a hub where you can interact with different aspects of your project, such as:
  * **Experiment with APIs**: Test and explore your REST and GraphQL APIs.
  * **Observability Tools**: Utilize tools to observe and monitor the performance and usage of your APIs.
  * **Migrations**: View and handle database migrations.
  * **API Keys**: Manage and create new API Keys as required for API access.
* Additionally, you can adjust environment settings to suit your testing needs.


# Creating a new Environment

### Overview

The Environment Dashboard in Neurelo is the central hub for managing all your environments in a specific project. Each environment is a runtime workspace for using the APIs from your project for development, testing, and deployment.&#x20;

### Environments Dashboard

To go to the environments dashboard, select a project from the left sidebar or from the Home screen and then select "Environments" under the selected project

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FFTEIx6Mg9deJlq1b0Fbk%2FScreenshot%202024-01-11%20at%203.24.36%E2%80%AFPM.png?alt=media&amp;token=3660591d-143a-438e-a8dd-5d507034c3d8" alt=""><figcaption></figcaption></figure>

1. **Creating New Environments**:

   * Click on the “New” button at the top of the dashboard to create a new environment.
   * Specify the Environment Name, choose a region for the deployment, select a definition commit, choose a Data Source, and configure additional settings like Observability and Automatic Migrations (only for Relational Databases such as PostgreSQL and MySQL).&#x20;

     * **Region**: Select the region you would like to spin up this environment in. We currently support 3 regions

       * AWS us-east-2 (Ohio, US)
       * AWS us-west-2 (Oregon, US)
       * AWS ap-south-1 (Mumbai, India)

       <div data-gb-custom-block data-tag="hint" data-style="info" class="hint hint-info"><p>It is highly recommended that you create your Neurelo environments geographically as close to where the data source is as possible, for the best performance and lowest latency for your projects.</p></div>

       <div data-gb-custom-block data-tag="hint" data-style="warning" class="hint hint-warning"><p>If you added Neurelo IPs to the allowed-list for your firewalls/security groups, as part of connecting your data source to Neurelo, please make sure to select the same region for your environment as you did when adding the data source</p></div>
     * **Observability** enables collecting for metrics around the APIs that are invoked.&#x20;
     * **Automatic Migrations** is a preview feature which enables schema migrations to be directly applied from Neurelo to the configured data source for the environment.&#x20;

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FlJZQeCd3mmydf9VfGYPD%2Fimage.png?alt=media&amp;token=6509459a-9aeb-4959-a7f7-52b97e455aea" alt="" width="224"><figcaption></figcaption></figure>

2. **Configure a Definition for the Environment**:

   * Select a specific version (commit) of the definitions from your version controlled branches to provision into a specific environment.

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F3ME3Y9PX1xeaxSO19EGD%2FScreenshot%202024-01-11%20at%203.34.19%E2%80%AFPM.png?alt=media&amp;token=f18cbf8d-b21d-40a5-b4c2-c4789c408df8" alt=""><figcaption></figcaption></figure>

3. **Starting and Stopping Environments**:
   * Use the “Start Runner” button to activate your environment. API endpoints for the environment can be used once the Runners have been started.&#x20;
   * You can also stop the environment for configuration changes or when it’s not in use.

4. **Modifying Environment Settings**:
   * The “Settings” button allows you to modify the settings of your environment.

5. **API Endpoint Base URL**:
   * The dashboard displays the base URL for your API endpoints. This URL will vary depending on the region your environment is deployed in.
     * REST endpoints are available at $Environment\_URL/rest
     * Custom Query endpoints are at $Environment\_URL/custom
     * GraphQL endpoints are at $Environment\_URL/graphql

6. **Managing API Keys**:
   * By clicking on “API Keys”, you can create new keys, view and manage existing api keys, or revoke a key. API Keys are necessary for making secure API calls.

7. **Reviewing APIs**:
   * The “APIs” tab opens a new dashboard dedicated to managing and reviewing your APIs and their references.&#x20;

{% hint style="danger" %}
To conserve platform resources, running environments which are inactive (no api calls) for more than 7 days may be automatically stopped. When the runners are auto-stopped for inactive environments, their configuration is not impacted. Runners can be restarted anytime by clicking on "Start Runners" when you need to use the environment again.&#x20;
{% endhint %}

The Environment Dashboard in Neurelo is designed to streamline the management of multiple environments, ensuring efficient transition from development to testing to production, and offering comprehensive tools for environment setup, version control, and API management.


# API Playground

### Overview

Neurelo's API Playground provides the ability to run and test all of Neurelo Data APIs in a environment. With the playground capability, you can instantly validate your auto generated APIs, extensibility options as well as custom query API endpoints.

### API Docs and Playground for an environment inside a project

* Step into your project from Neurelo's dashboard
* Inside the project, select Environments from left navigation panel. This should open a new page that list all your Environments inside this project.
* Select an environment. This will open up a detailed environment page. By default this page loads APIs page.<br>

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F9lAZyJoRIa6Nuujm9bru%2FScreenshot%202024-01-11%20at%202.16.44%E2%80%AFPM.png?alt=media&amp;token=faece9bb-cf4f-4bdb-a6ec-449bf24d15a2" alt=""><figcaption></figcaption></figure>

* From here, you can test any API using Neurelo's Playground feature. Click the "Play" icon from the right side of the screen.&#x20;
* This will open a Playground page with all APIs listed in the left navigation panel. Select any API, enter the required information including the API Key and hit the Send button
* The Playground should display the results or errors accordingly.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FO4WwkIiS65UUpS7SueVQ%2FScreenshot%202024-01-11%20at%202.22.44%E2%80%AFPM.png?alt=media&amp;token=e56261fa-088f-43d4-b81a-2775b616e616" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
While using Neurelo's API Playground, it would be faster to keep that environment's specific API Key ready as Neurelo does not store the api keys
{% endhint %}


# Observability

### Overview

Neurelo's Query Observability feature gives users clear visibility into the performance of their APIs. It offers detailed metrics for each API endpoint, so one can understand and track every data operation. This helps users keep an eye on performance, catch any issues, and make queries work better.&#x20;

### API Observability

Query observability can be enabled for an environment allowing one to track API and database query performance for different setups across dev, test, prod, etc. With this constant visibility, your endpoints always perform their best, making your data work more smoothly and securely.

The Observability feature provides insight into the performance of Neurelo APIs and the underlying database queries, meticulously recording every API call. With a customizable dashboard, users can effortlessly view hourly, daily, weekly, and monthly summaries of API activities, offering a range of features:

1. **Slowest operations**
   * List of the slowest API operations with the ability to click into detailed insights for each operation, providing a comprehensive understanding of performance trends
2. **Response Codes**
   * List of all API responses such as 200 (success), 400 (client error), 500 (failure) for the API invocations
3. **Total API calls**
   * Total API calls is the cumulative number of API requests within a specified timeframe, providing an overview of usage and activity.
4. **API Usage**
   * The API usage trend provides a snapshot of the variations in API calls over the selected time interval (hourly, daily, weekly, monthly). This feature helps track your API usage trends and understand usage patterns.

### Accessing the observability dashboard for an environment

* For a project, access the environment page by clicking the "Environments" option from the left sidebar. This will load the page with the list of environments deployed for that project.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fidr1VkdVGKLcYl6nI5aP%2FScreenshot%202024-01-15%20at%201.04.39%E2%80%AFPM.png?alt=media&amp;token=28217519-a288-452f-931b-3d35bf2f10d1" alt=""><figcaption></figcaption></figure>

* Click on any specific environment and open the detailed environment page with the default view of APIs. From here, click on the Observability tab on this page. This will load the API observability details for this environment

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FQYMcnZFxsckbDL6ir0Gr%2FScreenshot%202024-01-15%20at%201.05.29%E2%80%AFPM.png?alt=media&amp;token=046240e0-0f20-4857-817a-b4560c38aff2" alt=""><figcaption></figcaption></figure>


# Migrations

### Overview

Neurelo's schema migration feature enables you to apply the changes to the database for the changes in the schema in your definitions. This feature allows users to modify, update, or enhance their database schema such as adding or modifying tables (or collection) and fields and instantiate those changes in the database. The goal is to keep your database in sync with any changes your application might need over time, providing flexibility and maintaining a well-organized data model. This is crucial for evolving your database along with your application requirements

### Using Migrations

Neurelo Schema Migrations is an optional feature that needs to enabled at the Project level. This feature is only supported for Relational Databases such as PostgreSQL and MySQL.

{% hint style="warning" %}
This feature is currently in preview and not intended for production use. Use with caution and provide feedback to help us improve.
{% endhint %}

{% hint style="danger" %}
Note - this feature can only be enabled during Project Creation. It cannot be re-enabled if this was disabled during project creation or subsequently
{% endhint %}

Once enabled at the Project level, this feature has two capabilities.

* Generating Migrations for every commit of the definition with schema changes. This is always enabled for every environment, once it has been enabled at the project level
* Applying Migrations directly from Neurelo to your data source. This setting needs to be enabled at the Environment level. You can do this while creating a new environment for a project or later from Environment settings page for an existing environment.

{% hint style="info" %}
Neurelo's definitions capability keeps a record of data model changes using its version control capabilities. This enables Neurelo to automatically generate all the required database migrations in the specific order they were made.&#x20;
{% endhint %}

### How to access Migrations for an envrionment

* For a project, access the environment page by clicking "Environments" option from the left sidebar panel. This will load the page with the list of environments deployed for that project.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fidr1VkdVGKLcYl6nI5aP%2FScreenshot%202024-01-15%20at%201.04.39%E2%80%AFPM.png?alt=media&amp;token=28217519-a288-452f-931b-3d35bf2f10d1" alt=""><figcaption></figcaption></figure>

* Click on any specific environment and open the detailed environment page. From here, click on "Migrations" tab on this page. This will load the detailed migration page for this environment

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FzByQXOiqPeTzH7QX1m1v%2FScreenshot%202024-01-15%20at%202.40.12%E2%80%AFPM.png?alt=media&amp;token=135f4866-be46-4935-95cc-b49d656b90f1" alt=""><figcaption></figcaption></figure>

This page will show the current schema in the data source (the "Source Schema") and the schema that will need to be migrated to based on the selected commit for the environment (the "Target Schema") and it will list all the commits between the source schema and the target schema. Each commit with a schema change will have one more migrations associated with it. If a commit does not have a schema change (e.g. only has changes for custom query endpoints), then it will not have a migration associated with it.

Each commit can be selected or unselected from the Migrations process.

{% hint style="danger" %}
It is recommended to select all migrations. Please be very careful when unselecting a specific migration, as generally all migrations need to be applied in the sequence they were generated in
{% endhint %}

Users can -

* Validate Migrations - This will validate migrations between the source and target schema to see if they can be applied cleanly without possible data loss.
* Download Migrations - This allows users to download all the migrations across the commits in SQL format. They can then edit these migrations as needed and then apply them directly to the database using a schema migrations tool
* Mark as Applied - If users want to download migrations and apply them outside of Neurelo, or if Automatic migrations have been disabled for the environment users can use this option to indicate to Neurelo that the migrations have been applied
* Apply Migrations - If Automatic migrations have been enabled, users can apply migrations directly from Neurelo to the data source

When the user applies a specific commit to the environment (can only be done with the runners stopped), it is recommended to do the following -&#x20;

1. Check in the Migrations tab of the environment, if any migrations are needed after the commit has been changed
2. If Migrations show as pending, then validate the migrations and apply them (manually or through Neurelo, depending on your preference and configuration)
3. If Migrations have been applied manually, mark them as Applied in Neurelo
4. Start the Runners


# API Keys

### Overview

In Neurelo, an API Key is a security credential that grants permissions to use the APIs for a specific environment. It serves as a form of authentication, allowing applications or users to make authorized requests to the API. API Keys are included in API requests to verify the identity and permissions of the requester. These keys help ensure secure and controlled access to the API's functionality and data.

### Creating an API Key in Neurelo

This is a necessary step as part of activating an environment, especially when working with API endpoints. This key acts as a key for securing and authorizing your API interactions. Here’s how to create one:

1. **Initiating API Key Creation**:

   * For a project, access the environment page by clicking the "Environments" option from the left sidebar. This will load the page with the list of environments deployed for that project.<br>

     <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FQbViZQhe90x7YSrSJBuP%2FAPI%20Key%201.png?alt=media&amp;token=0fe37d3e-1166-44fc-ab23-355d8a749149" alt=""><figcaption></figcaption></figure>
   * Click on the "API Keys" button for a specific environment from the overview, or click on the Environment and select the "API Keys" tab. This will load a page with the detailed list of created keys and the ability to create a new api key.&#x20;
   * Click on the "New" button on the API Keys tab. This action will open a prompt for API Key creation.

2. **Configuring Key Details**:
   * **API Key Name**: You will be asked to provide a name for your new api key. Choose a name that is indicative of its use or purpose.
   * **Permission Selection**: Decide the level of permission for the api key. The options are:
     * **Read**: This permission is always pre-selected and mandatory, allowing the key to read data.
     * **Write**: Optionally, you can also enable the "Write" permission if the key is needed to modify or add data. This selection depends on your project requirements.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fs5ORVYnr4b0oE8MNiyFd%2FAPI%20Key%202.png?alt=media&amp;token=43bdca96-4f88-466e-a6fa-0d0d95799438" alt="" width="375"><figcaption></figcaption></figure>

3. **Generating the API Key**:
   * After selecting the necessary options and filling in the information, click on "Create."
   * A new prompt will appear with an important alert message: "Store this private key securely - For security reasons, you won't be able to view it again in your Neurelo Account. If you lose this secret key, you'll need to generate a new one."&#x20;

{% hint style="danger" %}
Please make sure to copy and save this api key in a secure location. Neurelo does not save this key and it cannot be retrieved again from the Neurelo dashboard once this step is completed.&#x20;
{% endhint %}

4. **Copying Your Generated API Key**:
   * The dialog box will display your "Generated API Key"
   * You can either manually select and copy the contents or click on the "Copy" button next to the field with the key to copy it to your clipboard.
   * Below the api key, you’ll also see the permissions associated with it.
   * Once you have securely copied and stored the api key, click on "Close" to return to the Environment page and continue with your journey

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FRV5o8oFCFHgpjUqDrBvy%2FAPI%20Key%203.png?alt=media&amp;token=8ed05380-5ba2-414b-8e4d-b5d8bd925ff7" alt="" width="375"><figcaption></figcaption></figure>

{% hint style="info" %}
The "Close" option in the dialog box will not be activated until the API Key has been "Copied"
{% endhint %}

{% hint style="danger" %}
Custom Query Endpoints currently are only supported with API Keys that have both Read and Write permissions. Custom Query endpoints will not work with Read-Only keys and will return a "403 - Forbidden" error.&#x20;
{% endhint %}


# Data Sources

### Overview

In Neurelo, "Data Sources" refer to databases that serve as the foundation for building Data APIs and managing data. These databases, such as PostgreSQL, MongoDB, and MySQL, are seamlessly integrated into the Neurelo platform, allowing developers to leverage their existing data infrastructure and instantly auto-generate Data APIs. With Neurelo's Data Sources, developers can easily connect their databases, streamline API development, and accelerate the process of building and deploying applications.

{% hint style="info" %}
Neurelo supports PostgreSQL, MongoDB and MySQL as data sources
{% endhint %}


# PostgreSQL

## Overview

You can attach a PostgreSQL database to your project either by following the Quick Start guide or by going to the "Data Source" section of your project. You can connect any reachable PostgreSQL instance (Managed or Self-hosted) to the project. For managed instances, some examples of database cloud providers you can use are [AWS RDS](https://aws.amazon.com/rds/postgresql/), [Aiven](https://aiven.io/), [Supabase](https://supabase.com/), [Azure](https://azure.microsoft.com/en-us/products/postgresql), [Google](https://cloud.google.com/sql/postgresql), among others.

{% hint style="info" %}
Guides on [provisioning managed databases in the cloud](/guides/provisioning-cloud-databases-for-using-with-neurelo).
{% endhint %}

{% hint style="success" %}
[Supported Versions](/references/supported-databases) of PostgreSQL
{% endhint %}

## Adding a Data Source in a Neurelo Project

* Click on the "Data Sources" option from the left navigation bar in your project.
* Click on the "New" button.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FUUJc6lrP1q9J1NCpoMWF%2FCleanShot%202024-03-11%20at%2017.09.31%402x.png?alt=media&amp;token=3be00728-77d4-4883-87a0-aa229d5c86b4" alt="" width="563"><figcaption></figcaption></figure>

* Upon clicking, a popup window will appear, asking you to name your data source and provide the connection details

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FQlvxC3cqtDzwudzX4zW9%2FAdding%20a%20new%20postgresql%20database.png?alt=media&amp;token=82cc3126-4ce3-494d-917a-a6225169d639" alt="" width="375"><figcaption></figcaption></figure>

* **Using the Connection String**: If you have the connection string for your database, simply input the string in the field in the form. The connection string needs to be in the following format -

```
postgres://username:password@host:port/database?schema=public
```

{% hint style="warning" %}
If you have any special characters ('$', ':', '/', '?', '#', '\[', ']', '@') in your password, please make sure that the string is correctly encoded. Alternatively, you can use the "Advanced Settings" option and input the password with special characters there instead.&#x20;
{% endhint %}

* **Using Connection Details**: If you don't have the fully formed Connection String and need to enter the Connection Details instead, please click on "Advanced Settings" and enter the data in the relevant fields
  * **Host**: The URL endpoint of your database
  * **Port**: The port number for the database instance
  * **Database**: The exact name of the database in the instance to be used
  * **Username**: The username to be used for connecting to the database
  * **Password**: The password to be used for connecting to the database

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Ft8WOhmShhVvTURUlATzd%2FAdding%20a%20new%20postgresql%20database%20using%20connection%20details.png?alt=media&amp;token=b3c2a48a-7dbc-4b78-bd4b-34bf031be46f" alt="" width="375"><figcaption></figcaption></figure>

## Schema Selection

By default for PostgreSQL, Neurelo will use the 'public' schema.

**Multiple Schema support:** If you would like to use all the schemas within the database, simply choose the "all" option in the Schema field and Neurelo will automatically detect and introspect all available schemas. &#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FM6IfHw7wBJ8xHz7LS8Fs%2Fpostgres-schema.png?alt=media&amp;token=fffbb22d-c538-42cb-b9bf-fae8c7740515" alt="" width="375"><figcaption></figcaption></figure>

* This feature is only supported for PostgreSQL
* If the introspection process detects a schema which is empty, that schema will be skipped&#x20;

## **Selecting a Gateway and Allowing Neurelo IP Addresses**:

Please select the Gateway that is located nearest to the database. Below the connection details, there’s an option to select a Gateway. Choose one that best suits your operational needs.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FKq5QBWQqJpDRSOOR9Bko%2Fselect%20a%20gateway.png?alt=media&amp;token=94b47161-1b82-416e-a5ad-151346feff92" alt="" width="375"><figcaption></figcaption></figure>

If you have a firewall or security group configured in front of the database, you may need add Neurelo IPs to the allowed list so that Neurelo can connect to the database. There are multiple IPs for the selected gateway, all of which need to be permitted in the firewall or security group configuration

{% hint style="info" %}
If you needed to configure Neurelo IPs to connect to your database, please make sure you spin up Environments that will use this database in the same gateway as the configured IPs selected.&#x20;
{% endhint %}

## Testing and Saving the Data Source

To make sure that all the information has been correctly entered and the Neurelo IPs have been added to the allowlist, you can test the connection by clicking on "**Test Connection**", You will receive a pop up saying "Connection test in progress" and once the connection has been tested successfully, you receive a message "Connection test completed successfully".&#x20;

Once the connection has been successfully tested, you can proceed to click on the "**Submit**" button. This will create a new data source for your project. You can always come back to this Data Source section to verify database details including the health check history.


# MySQL

## Overview

You can attach a MySQL database to your project either by following the Quick Start guide or by going to the "Data Source" section of your project. You can connect any reachable MySQL instance (Managed or Self-hosted) to the project. For managed instances, some examples of database cloud providers you can use are [AWS RDS](https://aws.amazon.com/rds/mysql/), [Aiven](https://aiven.io/), [Azure](https://azure.microsoft.com/en-us/products/mysql), [Google](https://cloud.google.com/sql/mysql), among others.

{% hint style="info" %}
Guides on [provisioning managed databases in the cloud](/guides/provisioning-cloud-databases-for-using-with-neurelo).
{% endhint %}

{% hint style="success" %}
[Supported Versions](/references/supported-databases) of MySQL
{% endhint %}

## Adding a Data Source in a Neurelo Project

* Click on the "Data Sources" option from the left navigation bar in your project.
* Click on the "New" button.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FUUJc6lrP1q9J1NCpoMWF%2FCleanShot%202024-03-11%20at%2017.09.31%402x.png?alt=media&amp;token=3be00728-77d4-4883-87a0-aa229d5c86b4" alt="" width="563"><figcaption></figcaption></figure>

* Upon clicking, a popup window will appear, asking you to name your data source and provide the connection details

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FftHNvelXXKWMgaunx0K2%2FAdding%20a%20new%20mysql%20database.png?alt=media&amp;token=71259099-ba19-4def-b494-7750ad8831a8" alt="" width="375"><figcaption></figcaption></figure>

* **Using the Connection String**: If you have the connection string for your database, simply input the string in the field in the form. The connection string needs to be in the following format -

```
mysql://username:password@host:port/database
```

{% hint style="warning" %}
If you have any special characters ('$', ':', '/', '?', '#', '\[', ']', '@') in your password, please make sure that the string is correctly encoded. Alternatively, you can use the "Advanced Settings" option and input the password with special characters there instead.&#x20;
{% endhint %}

* **Using Connection Details**: If you don't have the fully formed Connection String and need to enter the Connection Details instead, please click on "Advanced Settings" and enter the data in the relevant fields

  * **Host**: The URL endpoint of your database
  * **Port**: The port number for the database instance
  * **Database**: The exact name of the database in the instance to be used
  * **Username**: The username to be used for connecting to the database
  * **Password**: The password to be used for connecting to the database

  <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FDuhFpB1S9YUJ7GTeU7tQ%2Fadding%20a%20mysql%20db%20with%20connection%20details.png?alt=media&amp;token=2f44b2b0-6f2e-43cd-a03d-da8fc3d0fbf5" alt="" width="375"><figcaption></figcaption></figure>

## **Selecting a Gateway and Allowing Neurelo IP Addresses**:

Please select the Gateway that is located nearest to the database. Below the connection details, there’s an option to select a Gateway. Choose one that best suits your operational needs.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FKq5QBWQqJpDRSOOR9Bko%2Fselect%20a%20gateway.png?alt=media&amp;token=94b47161-1b82-416e-a5ad-151346feff92" alt="" width="375"><figcaption></figcaption></figure>

If you have a firewall or security group configured in front of the database, you may need add Neurelo IPs to the allowed list so that Neurelo can connect to the database. There are multiple IPs for the selected gateway, all of which need to be permitted in the firewall or security group configuration

{% hint style="info" %}
If you needed to configure Neurelo IPs to connect to your database, please make sure you spin up Environments that will use this database in the same gateway as the configured IPs selected.&#x20;
{% endhint %}

## Testing and Saving the Data Source

To make sure that all the information has been correctly entered and the Neurelo IPs have been added to the allowlist, you can test the connection by clicking on "**Test Connection**", You will receive a pop up saying "Connection test in progress" and once the connection has been tested successfully, you receive a message "Connection test completed successfully".&#x20;

Once the connection has been successfully tested, you can proceed to click on the "**Submit**" button. This will create a new data source for your project. You can always come back to this Data Source section to verify database details including the health check history.


# MongoDB

## Overview

You can attach a MongoDB database to your project either by following the Quick Start guide or by going to the "Data Source" section of your project. You can connect any reachable MongoDB instance (Managed or Self-hosted) to the project. For managed instances, you can use [MongoDB Atlas](https://www.mongodb.com/products/platform/atlas-database).&#x20;

Please refer to guides on [provisioning managed databases in the cloud](/guides/provisioning-cloud-databases-for-using-with-neurelo).

{% hint style="info" %}
If you are using MongoDB Atlas, please review [MongoDB Atlas](/guides/provisioning-cloud-databases-for-using-with-neurelo/mongodb-atlas)
{% endhint %}

{% hint style="success" %}
[Supported Versions](/references/supported-databases) of MongoDB
{% endhint %}

## Adding a Data Source in a Neurelo Project

* Click on the "Data Sources" option from the left navigation bar in your project.
* Click on the "New" button.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FUUJc6lrP1q9J1NCpoMWF%2FCleanShot%202024-03-11%20at%2017.09.31%402x.png?alt=media&amp;token=3be00728-77d4-4883-87a0-aa229d5c86b4" alt="" width="563"><figcaption></figcaption></figure>

* Upon clicking, a popup window will appear, asking you to name your data source and provide the connection details

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F6uak6kEZYiLOIEtoCq1Y%2FAdding%20a%20new%20mongodb%20database.png?alt=media&amp;token=50d91d94-454f-479d-8793-70c37ad68bef" alt="" width="375"><figcaption></figcaption></figure>

The connection string needs to be in the following format -

```
mongodb://username:password@host:port/database
```

{% hint style="danger" %}
The **database** name must be included in the string. If the provided string does not include the database name, please add it manually
{% endhint %}

{% hint style="warning" %}
If you have any special characters ('$', ':', '/', '?', '#', '\[', ']', '@') in your password, please make sure that the string is correctly encoded. Alternatively, you can use the "Advanced Settings" option and input the password with special characters there instead.&#x20;
{% endhint %}

* **Using Connection Details**: If you don't have the fully formed Connection String and need to enter the Connection Details instead, please click on "Advanced Settings" and enter the data in the relevant fields

  * **Host**: The URL endpoint of your database
  * **Port**: The port number for the database instance
  * **Database**: The exact name of the database in the instance to be used
  * **Username**: The username to be used for connecting to the database
  * **Password**: The password to be used for connecting to the database

  <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F5XtibXrQHJuiijsst1qJ%2FAdding%20a%20new%20mongodb%20with%20connection%20details.png?alt=media&amp;token=f02d4d69-acf0-46ff-a203-1602343de6ff" alt="" width="375"><figcaption></figcaption></figure>

## **Selecting a Gateway and Allowing Neurelo IP Addresses**:

Please select the Gateway that is located nearest to the database. Below the connection details, there’s an option to select a Gateway. Choose one that best suits your operational needs.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FKq5QBWQqJpDRSOOR9Bko%2Fselect%20a%20gateway.png?alt=media&amp;token=94b47161-1b82-416e-a5ad-151346feff92" alt="" width="375"><figcaption></figcaption></figure>

If you have a firewall or security group configured in front of the database, you may need add Neurelo IPs to the allowed list so that Neurelo can connect to the database. There are multiple IPs for the selected gateway, all of which need to be permitted in the firewall or security group configuration

{% hint style="info" %}
If you needed to configure Neurelo IPs to connect to your database, please make sure you spin up Environments that will use this database in the same gateway as the configured IPs selected.&#x20;
{% endhint %}

## Testing and Saving the Data Source

To make sure that all the information has been correctly entered and the Neurelo IPs have been added to the allowlist, you can test the connection by clicking on "**Test Connection**", You will receive a pop up saying "Connection test in progress" and once the connection has been tested successfully, you receive a message "Connection test completed successfully".&#x20;

Once the connection has been successfully tested, you can proceed to click on the "**Submit**" button. This will create a new data source for your project. You can always come back to this Data Source section to verify database details including the health check history.


# Guides

This section has guides to help with using the various features and capabilities of Neurelo. Please review the following guides in this section.

* [Provisioning Cloud Databases for using with Neurelo](/guides/provisioning-cloud-databases-for-using-with-neurelo)
* [Mock Data Generation](/guides/mock-data-generation)
* [Wipe Data Source](/guides/wipe-data-source)
* [Remote Git Repository for Definitions](/guides/remote-git-repository-for-definitions)
* [Data Viewer](/guides/data-viewer)
* [Environment/Data Source Tags](/guides/environment-data-source-tags)
* [How to work with Embedded  documents and References in MongoDB](/guides/how-to-work-with-embedded-documents-and-references-in-mongodb)
* [How to download and use the Postman Collection for your Project](/guides/how-to-download-and-use-the-postman-collection-for-your-project)
* [Building Python applications with Postgres and FastAPI](/guides/building-python-applications-with-postgres-and-fastapi)
* [CI Integration using Neurelo CLI](/guides/ci-integration-using-neurelo-cli)
* [Schema Migrations](/guides/schema-migrations)
* [Schema AI Assist](/guides/schema-ai-assist)
* [Access Policies](/guides/access-policies)
* [MongoDB Atlas - Migrate GraphQL to Neurelo](/guides/mongodb-atlas-migrate-graphql-to-neurelo)
* [MongoDB Atlas - Migrate REST Data APIs to Neurelo](/guides/mongodb-atlas-migrate-rest-data-apis-to-neurelo)


# Provisioning Cloud Databases for using with Neurelo

Neurelo seamlessly integrates with PostgreSQL, MySQL, and MongoDB databases. Whether hosted on managed cloud platforms like AWS RDS or MongoDB Atlas, or self-hosted in hybrid or local environments, our APIs support these databases without restrictions, ensuring compatibility regardless of where or how they are deployed.

This section has guides on creating cloud databases for using with Neurelo - &#x20;

* [PostgreSQL](/guides/provisioning-cloud-databases-for-using-with-neurelo/postgresql)
* [MySQL](/guides/provisioning-cloud-databases-for-using-with-neurelo/mysql)
* [MongoDB Atlas](/guides/provisioning-cloud-databases-for-using-with-neurelo/mongodb-atlas)


# PostgreSQL

## Overview

This section outlines how to spin up PostgreSQL Cloud Databases and connect them with Neurelo. You can use an instance of PostgreSQL on any cloud provider such as -

* AWS RDS for PostgreSQL (including their serverless offering)
* Azure Databases for PostgreSQL
* Google Cloud PostgreSQL-compatible databases, and more

While we mention certain cloud providers here, it's important to note that Neurelo is designed to work seamlessly with supported PostgreSQL databases across any Cloud, Hybrid, On-Prem, or Local deployments

{% hint style="info" %}
Reference - [Neurelo Supported Databases and Versions](/references/supported-databases)
{% endhint %}

The following section has guides on creating cloud databases for using with Neurelo -

## Guides

* Using [AWS RDS (PostgreSQL)](/guides/provisioning-cloud-databases-for-using-with-neurelo/postgresql/aws-rds-postgresql) with Neurelo


# AWS RDS (PostgreSQL)

## Overview

Amazon Relational Database Service ([Amazon RDS](https://aws.amazon.com/rds/)) is a collection of managed services that makes it simple to set up, operate, and scale databases in the cloud. RDS offers several [features](https://aws.amazon.com/rds/features/) and is one of the most popular managed database providers

[AWS RDS for PostgreSQL](https://aws.amazon.com/rds/postgresql/?pg=ln\&sec=hiw) is a managed Postgres database service which can be used to set up, operate, and scale a postgresql database in the cloud with just a few clicks

## Get Started with AWS RDS for PostgreSQL

1. [Sign up for an account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) with AWS. AWS offers a [free tier](https://aws.amazon.com/free) to get you started and you can upgrade to paid services when needed.
2. Create a RDS for PostgreSQL instance in your account. Here are some AWS tutorials to help you get started
   * Tutorial 1 - [Creating a PostgreSQL DB instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.CreatingConnecting.PostgreSQL.html#CHAP_GettingStarted.Creating.PostgreSQL)
   * Tutorial 2 - [Getting started with a PostgreSQL instance](https://aws.amazon.com/getting-started/hands-on/create-connect-postgresql-db/)
   * **Important Notes** -&#x20;

     * Remember to choose "PostgreSQL" as the engine type and not "Aurora (PostgreSQL Compatible)" to get started
     * You can choose "Free tier" as the template for your instance if you plan to use this for evaluation purposes with Neurelo
     * You don't need this DB to be connected to an EC2 instance
     * Use Password authentication for the database authentication method
     * Remember the username and password used when creating this instance. You will need these to connect your DB to Neurelo
     * You can specify the database name under Additional Configuration -> Database options

     <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fhx9ZWKaeHHrEQMo8SngI%2FDBName%20configuration.png?alt=media&amp;token=948c7f01-37db-4aa6-ab8a-cc0104c4356e" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
To enable Neurelo to connect to your AWS RDS instance, please make sure that the Neurelo IP addresses are enabled in your security groups to connect, or make the instance publicly accessible (not recommended -- use with caution only for testing purposes)
{% endhint %}

## Collect PostgreSQL connection details from the AWS Console

1. To connect your newly created instance to Neurelo, you will need the following information&#x20;
   * Host / Endpoint for the DB instance
   * Port
   * Username
   * Password
   * Database name&#x20;
2. Login to the AWS console to [fetch the host/endpoint and the port](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.CreatingConnecting.PostgreSQL.html#CHAP_GettingStarted.Connecting.PostgreSQL). You will need to remember the username, password and database name used when creating the instance.

## Add the AWS RDS for PostgreSQL instance as a Data Source in a Neurelo Project

For each new project in Neurelo, you can utilize the Quick Start feature, a guided wizard for step-by-step onboarding, including [adding a new Data Source](https://docs.neurelo.com/getting-started/starting-your-neurelo-project/step-1-add-a-data-source) like AWS RDS for PostgreSQL. Additionally, you can create new Data Sources anytime within your project from the left navigation panel.

### Connecting AWS RDS for PostgreSQL to Neurelo with the Database Connection details

1. Login to your Neurelo Dashboard
2. Choose the project where you want to add a new data source or create a new project for this purpose.
3. For new projects, follow the Quick Start Guide and click on "Connect Data Source" button. For existing projects, navigate to "Data Sources" from the left navigation bar in the project and click on the "New" button and provide the details needed.&#x20;
4. Please refer to [this page](/data-sources/postgresql) for additional information.


# MySQL

## Overview

This section outlines how to spin up MySQL Cloud Databases and connect them with Neurelo. You can use an instance of MySQL on any cloud provider such as -

* AWS RDS for MySQL (including their serverless offering)
* Azure Databases for MySQL,&#x20;
* Google Cloud MySQL-compatible databases, and more

While we mention certain cloud providers here, it's important to note that Neurelo is designed to work seamlessly with supported MySQL databases across any Cloud, Hybrid, On-Prem, or Local deployments

{% hint style="info" %}
Reference - [Neurelo Supported Databases and Versions](/references/supported-databases)
{% endhint %}

The following section has guides on creating cloud databases for using with Neurelo -

## Guides

* Using [AWS RDS (MySQL)](/guides/provisioning-cloud-databases-for-using-with-neurelo/mysql/aws-rds-mysql) with Neurelo


# AWS RDS (MySQL)

## Overview

Amazon Relational Database Service ([Amazon RDS](https://aws.amazon.com/rds/)) is a collection of managed services that makes it simple to set up, operate, and scale databases in the cloud. RDS offers several [features](https://aws.amazon.com/rds/features/) and is one of the most popular managed database providers

[AWS RDS for MySQL](https://aws.amazon.com/rds/mysql/) is a managed mysql database service which can be used to set up, operate, and scale a mysql database in the cloud with just a few clicks

## Get Started with AWS RDS for MySQL

1. [Sign up for an account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) with AWS. AWS offers a [free tier](https://aws.amazon.com/free) to get you started and you can upgrade to paid services when needed.
2. Create a RDS for MySQL instance in your account. Here are some AWS tutorials to help you get started
   * Tutorial 1 - [Creating a MySQL Instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.CreatingConnecting.MySQL.html#CHAP_GettingStarted.Creating.MySQL)
   * Tutorial 2 - [Getting started with a MySQL instance](https://aws.amazon.com/getting-started/hands-on/create-mysql-db/)
   * **Important Notes** -&#x20;

     * Remember to choose "MySQL" as the engine type and not "Aurora (MySQL Compatible)" to get started&#x20;
     * You can choose "Free tier" as the template for your instance if you plan to use this for evaluation purposes with Neurelo
     * You don't need this DB to be connected to an EC2 instance
     * Use Password authentication for the database authentication method
     * Remember the username and password used when creating this instance. You will need these to connect your DB to Neurelo
     * You can specify the database name under Additional Configuration -> Database options

     <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fhx9ZWKaeHHrEQMo8SngI%2FDBName%20configuration.png?alt=media&amp;token=948c7f01-37db-4aa6-ab8a-cc0104c4356e" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
To enable Neurelo to connect to your AWS RDS instance, please make sure that the Neurelo IP addresses are enabled in your security groups to connect, or make the instance publicly accessible (not recommended -- use with caution only for testing purposes)
{% endhint %}

## Collect MySQL connection details from the AWS Console

1. To connect your newly created instance to Neurelo, you will need the following information&#x20;
   * Host / Endpoint for the DB instance
   * Port
   * Username
   * Password
   * Database name&#x20;
2. Login to the AWS console to [fetch the host/endpoint and the port](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.CreatingConnecting.MySQL.html#CHAP_GettingStarted.Connecting.MySQL). You will need to remember the username, password and database name used when creating the instance.

## Add the AWS RDS for MySQL instance as a Data Source in a Neurelo Project

For each new project in Neurelo, you can utilize the Quick Start feature, a guided wizard for step-by-step onboarding, including [adding a new Data Source](https://docs.neurelo.com/getting-started/starting-your-neurelo-project/step-1-add-a-data-source) like AWS RDS for MySQL. Additionally, you can create new Data Sources anytime within your project from the left navigation panel.

### Connecting AWS RDS for MySQL to Neurelo with the Database Connection details

1. Login to your Neurelo Dashboard
2. Choose the project where you want to add a new data source or create a new project for this purpose.
3. For new projects, follow the Quick Start Guide and click on "Connect Data Source" button. For existing projects, navigate to "Data Sources" from the left navigation bar in the project and click on the "New" button and provide the details needed.&#x20;
4. Please refer to [this page](/data-sources/mysql) for additional information.


# MongoDB Atlas

## Overview

This section outlines how to spin up [MongoDB](https://www.mongodb.com/) Cloud Databases and connect them with Neurelo. While we mention certain cloud providers here, it's important to note that Neurelo is designed to work seamlessly with supported MongoDB databases across any Cloud, Hybrid, On-Prem or Local deployments

{% hint style="info" %}
Reference - [Neurelo Supported Databases and Versions](/references/supported-databases)
{% endhint %}

## Get Started with MongoDB Atlas

MongoDB Atlas (<https://www.mongodb.com/atlas/database>) is a managed multi-cloud database service. You can use Atlas free clusters for a small-scale development environment to host your data. Free clusters never expire, and provide access to a [subset](https://www.mongodb.com/docs/atlas/reference/free-shared-limitations/#std-label-atlas-free-tier) of Atlas features

{% hint style="info" %}
MongoDB Atlas offers both a user interface (UI) and a command-line interface (CLI) for accessing its services. Be sure to click on the "Atlas UI" option when using the MongoDB documentation website.
{% endhint %}

* **Sign up:** If you don't already have an account, you can [get started for free with Atlas](https://www.mongodb.com/cloud/atlas/register).
* **MongoDB Atlas Database Service:** Instructions to [create MongoDB Atlas free cluster service](https://www.mongodb.com/docs/atlas/tutorial/deploy-free-tier-cluster/). You must complete following steps:
  * Create an [organization with a project](https://www.mongodb.com/docs/atlas/tutorial/create-atlas-account/#create-an-service-organization-and-project)
  * Create an [active database cluster in your account](https://www.mongodb.com/docs/atlas/tutorial/deploy-free-tier-cluster/#deploy-a-free-cluster)
  * Configure a[ database user in your cluster](https://www.mongodb.com/docs/atlas/tutorial/create-mongodb-user-for-cluster/#manage-the-database-users-for-your-cluster)

## Connection String Formats for Neurelo&#x20;

Neurelo will accept the connection string in either of these formats&#x20;

1. mongodb+srv://<mark style="color:red;">username:password</mark>@cluster0.<mark style="color:red;">cluster</mark>.mongodb.net/<mark style="color:red;">database\_name</mark>&#x20;
2. mongodb://<mark style="color:red;">username</mark>:<mark style="color:red;">password</mark>@<mark style="color:red;">host</mark>:<mark style="color:red;">port</mark>/<mark style="color:red;">database\_name</mark>

You need to replace the **username**, **password**, **host, port, cluster**, and **database\_name** in the above strings as appropriate

## Collect MongoDB connection details from the Atlas UI

To enable communication between Neurelo and your MongoDB database, configure your MongoDB instance on Atlas in your Neurelo project. You will need following information from Atlas Cloud:

* [Log in to Atlas](https://account.mongodb.com/account/login?_ga=2.74544657.2039135292.1706673522-835773854.1705298079).
* Go to the Overview page for your project. If your desired project is not active in the UI, choose the appropriate project from the Projects menu in the top-left navigation panel.
* Select "Databases" from the options in the left navigation panel.
* On the "Database Deployments" page, locate the database deployment (cluster) you wish to connect to, then click on the "Connect" button associated with that deployment.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FnSfDEZes8W0csKaVj1KA%2FCleanShot%202024-01-30%20at%2018.23.38%402x.png?alt=media&amp;token=f2964caf-2002-4a17-a1b5-ff796c47467e" alt=""><figcaption><p>MongoDB Atlas Cloud - Database Deployment View</p></figcaption></figure>

* From the Connect page, select "**Compass**". Copy the connection string from the Compass view as shown (you can use the Copy icon on the right of the string)

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FZtWE4WmSvDHtcynPuN2M%2FCleanShot%202024-01-30%20at%2018.42.14%402x.png?alt=media&amp;token=93a59768-163e-4911-9758-84610c63105a" alt="" width="563"><figcaption></figcaption></figure>

{% hint style="danger" %}
Neurelo requires database\_name to be present in the connection string. Atlas Cloud UI does not display the \<database\_name> in the connection string -- you will need to append it to the string.&#x20;
{% endhint %}

## Getting MongoDB database\_name from the Atlas UI

* To find and add the <mark style="color:red;">\<database\_name></mark> in your connection string, go to the "Database Deployments" page in the Atlas UI, and locate the deployment (cluster) you wish to connect to, then click on the "Browse Collections" button associated with that deployment.
* In the Collection view, you will find the list of databases. Copy the database name you wish to connect with Neurelo and append it to your connection string
* In the below screenshot, there is a database called "**nyc\_civil\_service**" on "Cluster0". Use this database name in your connection string.&#x20;
* Your connection string would be -> mongodb+srv://<mark style="color:red;">\<username>:\<password></mark>@cluster0.<mark style="color:red;">\<cluster></mark>.mongodb.net/<mark style="color:red;">nyc\_civil\_service</mark>

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FKlwFk9pPdhmqUqnXVyBb%2Fdbname.jpeg?alt=media&amp;token=dc3d562d-64dc-4643-8775-03f5cf5e4217" alt=""><figcaption><p>Atlas Database Deployment page with the list of databases</p></figcaption></figure>

{% hint style="info" %}
**MongoDB Compass:** You can also get the connection string and database name using the MongoDB Compass client -- details [here](https://www.mongodb.com/docs/compass/current/).
{% endhint %}

## Add MongoDB as a Data Source in a Neurelo Project

For each new project in Neurelo, you can utilize the Quick Start feature, a guided wizard for step-by-step onboarding, including [adding a new Data Source](https://docs.neurelo.com/getting-started/starting-your-neurelo-project/step-1-add-a-data-source) like MongoDB Atlas. Additionally, you can create new Data Sources anytime within your project from the left-navigation panel.

### Connecting MongoDB Atlas with a Connection String

1. Login to your Neurelo Dashboard
2. Choose the project where you want to add a new data source or create a new project for this purpose.
3. For new projects, follow the Quick Start Guide and click on "Connect Data Source" button. For existing projects, navigate to "Data Sources" from the left navigation bar in the project and click on the "New" button
4. Access the New Data Source dialog box. Enter the connection string obtained earlier from the MongoDB Atlas UI (and make sure it has *\<database\_name>* added).&#x20;
5. Add Neurelo IP addresses to your [Atlas IP access list](https://www.mongodb.com/docs/atlas/security/add-ip-address-to-list/#manage-the-ip-access-list). The Neurelo IP addresses to use for your project will be displayed in this dialog box.&#x20;

   <div data-gb-custom-block data-tag="hint" data-style="danger" class="hint hint-danger"><p><strong>Allowed inbound IP addresses:</strong> The default setting for Atlas Cloud services does not allow access from all IP ranges. You must add Neurelo's IPs to your allowed list on Atlas Cloud</p></div>
6. After entering the connection details, click on "Test Connection" to verify that Neurelo can successfully connect to MongoDB Atlas. Once the test is successful, click Submit to save the configuration in Neurelo. Please refer to [this page](/data-sources/mongodb) for additional information.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FhDDKA4Tlt1DDihXzG3sI%2FCleanShot%202024-01-30%20at%2019.14.42%402x.png?alt=media&amp;token=673187eb-3671-4e0b-82f1-666af04428f1" alt="" width="563"><figcaption><p>New MongoDB Data Source with Connection String in Neurelo</p></figcaption></figure>


# Mock Data Generation

## Overview

Mock data generation is the process of creating realistic synthetic datasets to populate databases with representative data for testing, prototyping, and demonstration purposes..

Neurelo offers users this capability to rapidly populate your databases with mock data. We utilize AI to intelligently generate mock data that aligns with your schema and its attribute contexts. All our supported data sources (PostgresSQL, MySQL, MongoDB) are compatible with this feature.

This functionality is especially valuable in testing and development scenarios, allowing for the validation of new features, bug fixes, and performance optimizations within a controlled environment.&#x20;

## How to generate mock data?

To generate mock data, you must have an existing project with a defined schema and an environment that connects to your schema and its corresponding data source.&#x20;

* Select your project from Neurelo's dashboard
* Inside the project, select Environments from the left navigation panel. This should open the page that list all your Environments inside this project.

From this page select "Data Generator" for a specific environment in the list.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FvZV1sR0hXd67Wyy8oWYF%2Fmcd1.avif?alt=media&amp;token=f1f16f6c-e145-40d9-b65d-4f7dafd9bf24" alt=""><figcaption></figcaption></figure>

or,  you can select and go into the details for a specific environment and you will find the "Data Generator" button in the card at the top for that environment.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FBBq1VT1eR32jXTf9sJxB%2Fmdg1.png?alt=media&amp;token=eac3567a-103e-4ffb-ade0-19cd61212bfe" alt="" width="563"><figcaption></figcaption></figure>

Click on the button to launch our Mock Data Generator dialog. You will then be prompted to select the size of the dataset you wish to generate.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FXo55vHQAyCbB0Q8mJeXX%2Fmdg2.png?alt=media&amp;token=9125569e-6963-42c5-bd70-11aa2306ff5f" alt="" width="375"><figcaption></figcaption></figure>

Currently, we offer three sizes: small (with approx. 10 rows), medium (with approx. 100 rows), and large (with approx. 1000 rows). Essentially, this means that each table/collection will be populated with the number of rows you select. Choose the desired size and click on the "Start" button. A notification stating “Mock data generation in progress” will appear in the top right corner of the environments page.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FKUzK0VVhLST6kK9b9Ixg%2Fmdg3.png?alt=media&amp;token=29387d0e-ae65-47b1-a3aa-b11f03181399" alt="" width="375"><figcaption></figcaption></figure>

Please wait until the mock data generation is complete. Note that populating 1000 rows may take longer, especially with complex schemas. Upon successful mock data generation, a “Mock data generation completed” message will be displayed.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FSWuuGaAUMr0hkDW5SCCJ%2Fmdg4.png?alt=media&amp;token=b684262b-655e-44ab-9446-57d4a6231b15" alt="" width="375"><figcaption></figcaption></figure>

## Restrictions and Limitations

Please note the following requirements for the Mock Data Generation service:

* The database **must not contain any existing data** in any of the tables. This constraint ensures that users do not inadvertently overwrite their existing data. We strongly advise only utilizing this feature within a test environment that incorporates a test database. For those looking to conveniently erase their existing test databases, we offer a "Wipe Data Source" option under the Data Sources tab. By default, this feature is disabled and requires the disabling of wipe protection. Please refer to [Wipe Data Source](/guides/wipe-data-source) for more details.&#x20;
* If there are **pending migrations,** they need to be applied before performing mock data generation. This ensures that the schema for which you are generating your mock data is consistent with the schema in your database.

Furthermore, our Mock Data Generation service has the following limitations:

* If your schema contains **warnings**, we cannot guarantee the successful generation of mock data. In such cases, you might encounter partially mocked data. We advise resolving any warnings prior to proceeding with the mock data generation for your database.
* **Cyclical references** within the schema's relationships are not supported.
* Schemas that include **composite types** are not supported.
* The generation of mock data for **multiple schemas with PostgreSQL** is currently not supported.


# Wipe Data Source

## Overview

Neurelo offers the “Wipe Data Source” feature, designed to erase all data from your database and reset your database schema. This feature is especially valuable for clearing your test databases, helping in troubleshooting, or facilitating a rapid environment refresh.

{% hint style="danger" %}
It is recommended that you ONLY use this feature with test databases. Do NOT use this feature with data sources with data you may not want to lose e.g. staging or production&#x20;
{% endhint %}

To initiate the wipe, navigate to your “Data Sources” tab and select the Data Source you wish to wipe.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FIzE1oFA301cXMk7uJ2qJ%2Fwds1.png?alt=media&amp;token=0851d3aa-9036-4825-8311-05a78cf36dfb" alt="" width="563"><figcaption></figcaption></figure>

In the “Data Sources” view, the Wipe Data Source option is available in the Danger Zone section at the bottom of the settings. You will notice that the Wipe Data Source action in the “Danger Zone” is disabled by default.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FM6ftKd7f1DGae0fZv4gM%2Fwds2.png?alt=media&amp;token=15230ab4-f677-401a-86f5-2ace74298032" alt="" width="563"><figcaption></figcaption></figure>

This is a safety measure and is due to Neurelo's default setting of enabling “Wipe Protection” for every project. This helps safeguard against unintended data loss. Neurelo will not proceed with wiping your data source as long as this flag is active.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fkn6UDQMwTiTZKuYLwwpL%2Fwds3.png?alt=media&amp;token=b5e5bb0d-3907-4ff8-8f30-02ba2e99c34d" alt="" width="563"><figcaption></figcaption></figure>

To proceed with wiping the data source, you must disable this flag. You can do this by toggling off the “Wipe Protection” switch and then clicking on “Save.”

{% hint style="warning" %}
It is also important to ensure that your environment runners are stopped before wiping your data source to avoid any inconsistent behavior with your API queries.&#x20;
{% endhint %}

Once these actions are complete, you can click on the “Wipe” button located in the “Danger Zone” section. A dialog for wiping the data source will then appear.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FJcYKRpNYgaHkgHWsjUaV%2Fwds4.png?alt=media&amp;token=c5a123d8-a695-4a2f-8d9c-9141d6a395e3" alt="" width="375"><figcaption></figcaption></figure>

Input the specified confirmation text to confirm your intention to wipe your data source. Be mindful that this action is irreversible. After confirmation, click on the “Wipe Data Source” button.

A notification will appear in the top right corner of the page, indicating that the wipe data source process has started. Following successful completion, a message stating “Data Source wiped successfully” will be displayed. This action will also be reflected in Neurelo’s audit logs.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FlJW3M7mv1p4zbHahgNCT%2Fwds5.png?alt=media&amp;token=b05e7d34-8dd0-4ed3-8338-31b9915951ed" alt="" width="375"><figcaption></figcaption></figure>


# Remote Git Repository for Definitions

When creating a new project in Neurelo, you can choose to use your own git repository for the Definitions (Schema, Migrations, Custom APIs, etc.) in your project. This guide goes through the details of connecting your remote git repository to a project in Neurelo and using the remote repo in your project.&#x20;

* [Connecting a Remote Git Repo](/guides/remote-git-repository-for-definitions/connecting-a-remote-git-repo)
* [Creating Commits from Neurelo](/guides/remote-git-repository-for-definitions/creating-commits-from-neurelo)
* [Syncing Branches](/guides/remote-git-repository-for-definitions/syncing-branches)


# Connecting a Remote Git Repo

In this example, we will be using [Github](https://github.com/) as a representative example of a platform where you have your git repository. You can use similar steps to connect git repos in other plaforms such as [Gitlab](https://about.gitlab.com/), [BitBucket](https://bitbucket.org/) and others.&#x20;

### Setup with GitHub using Deploy Keys

Let’s say we have a private GitHub Repository named `my-app` and want to use it for the Neurelo definitions in the project. The recommended way to connect the repository with Neurelo is to use the “Deploy Keys” feature.

* Copy the SSH URL for the Repository from GitHub

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FH0VpnhjKF5feA0tJWIQS%2Frg10.png?alt=media&amp;token=40550430-0c98-4ce6-85a5-28c5c4aadff9" alt=""><figcaption></figcaption></figure>

* Next, Create a new Project in Neurelo, set the name and the database engine, check the “Use Remote Git Repository” check box, and click “Next.”

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FeVM5uHHLV6WZxEPusW3t%2Frg11.png?alt=media&amp;token=b378fbce-cf3f-4a22-b7aa-5ba5d0ecef4a" alt="" width="375"><figcaption></figcaption></figure>

* This will open the Repository Configuration. Select the “SSH” mode and enter the SSH URL we copied from GitHub in the “Repository URL.” In our example, the `main` is the default branch.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FnU2yfymtGhoedwFDRQRr%2Frg121.png?alt=media&amp;token=9b3a565d-ba9e-44e2-9c2d-9b75be2e2218" alt="" width="375"><figcaption></figcaption></figure>

Next we need to add the Neurelo Public Key into the GitHub Repository

* Copy the Public Key from the Neurelo project

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FOzg2rZbUYlAZPSRChKRi%2Frg12.png?alt=media&amp;token=4f64132c-436c-4f65-8262-02ea4d9e93c8" alt="" width="375"><figcaption></figcaption></figure>

* Navigate to the Settings tab in your GitHub repository and open the “Deploy keys” page

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FWeIv295WPQfGbdbfWqok%2Frg13.png?alt=media&amp;token=5525637f-9682-4012-909d-c53bbe20cabd" alt=""><figcaption></figcaption></figure>

* Paste the Public Key from the Neurelo Remote Git Configuration Dialog. Ensure that “Allow write access” is enabled so Neurelo can commit the definitions.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FZNzcnZu0S0iU2Xb4stH6%2Frg14.png?alt=media&amp;token=96822b86-459d-47ec-86a9-51aafa5842b3" alt=""><figcaption></figcaption></figure>

* Once added, the key will show up on the Deploy Keys page. It should have the “Read/write” permissions.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FxUrPq5Svbb0ljqXSVvf6%2Frg15.png?alt=media&amp;token=decac4fe-f4c7-482a-8a0d-0efa331b3029" alt=""><figcaption></figcaption></figure>

### Test the Connection

* Once the Public key has been added, click “Test Connection” to ensure Neurelo can connect with your repository.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FHhzsIp67ee45VKi2tYjT%2Frg16.png?alt=media&amp;token=6b7f0fe7-f689-48ed-93b8-dc4a7b6bb6b3" alt="" width="375"><figcaption></figcaption></figure>

* Wait for Neurelo to try to test the connection. Upon success, you will see a “Remote repo connection test completed successfully” toast. Click on “Create.”

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FNR2UdZDxjvDgiGuAj48k%2Frg17.png?alt=media&amp;token=971cbf09-5745-4637-b26c-643f4bba6e67" alt=""><figcaption></figcaption></figure>

* If you navigate to the “Definitions” and open the history, you should be able to see the commits from your Git Repository.


# Creating Commits from Neurelo

### Creating Commits from Neurelo

You can edit your schema, custom apis etc. in Neurelo and commit them to the remote git repo. For example, let's commit our changes by clicking on the Commit button in the top right corner of the Definitions page. This will open the "Commit changes" dialog box.

* Set a commit message, and click “Commit.” This will start the process of creating a commit on the Remote Repository.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FRL8W65lPW9m0dnPPs0i6%2Frg20.png?alt=media&amp;token=57bff7c7-3b78-4ee0-8ba9-c3362d9ebbe5" alt=""><figcaption></figcaption></figure>

* Once Neurelo confirms that the commit is created successfully, you can see that the last commit in the GitHub Repository is the same commit created above.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FvsHpFENvrwnrXG19sMYr%2Frg21.png?alt=media&amp;token=8d410857-c1ed-4a16-a9c0-653c1d8297e9" alt=""><figcaption></figcaption></figure>

* You can also confirm this by comparing Neurelo's commit history and GitHub's commit history - the commit hashes match.

**Neurelo Commit History**

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FMz8U7ahXWgWvwUQ4Lz3J%2Frg22.png?alt=media&amp;token=242578a6-c2a5-4564-a59e-024e0e5334c0" alt="" width="563"><figcaption></figcaption></figure>

**GitHub Commit History**

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FOpBNkrLREZuFqX0SBT5s%2Frg23.png?alt=media&amp;token=66daaed9-309e-43da-8467-c9ea13c9043b" alt="" width="563"><figcaption></figcaption></figure>


# Syncing Branches

By default, the project will use the branch specified as the "Default Branch" when connecting the Remote Git repository to the project.&#x20;

### Branch Setup

* You can sync an existing branch from the repo or create a new branch in Neurelo by using the Branch selector and clicking on the “New branch”

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FwFvYbGE8xIyr6W81j45D%2Frg30.png?alt=media&amp;token=8717764b-e1b5-4eb1-826f-f3765ccc8ddf" alt="" width="563"><figcaption></figcaption></figure>

* You can enter the name of the branch and “Submit”

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FTunAKXEUc1k2sBDO0ExJ%2Frg301.png?alt=media&amp;token=4954714b-6c7d-4c28-9d1b-610d8c9c5649" alt="" width="375"><figcaption></figcaption></figure>

* This will pull the branch from the remote git repository if it is found; or otherwise, create a new branch off the default branch.
* New changes will be pulled every 5 minutes, or you can manually pull the changes by clicking on the “Sync” button.

### Manual Sync

Once you push new commits to your branch, you can sync those changes in Neurelo by clicking on the “Sync” button.

* For example, let’s say we have a branch named `feature-1` at commit `8a9731...9f6553`

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FRMjVbMQV4VwLh462kEfA%2Frg31.png?alt=media&amp;token=0d65a509-e6bb-41e7-962a-8471f4c61edd" alt="" width="563"><figcaption><p>Commit History in Neurelo</p></figcaption></figure>

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FiykGXFtU3Aeja39Ax2vM%2Frg32.png?alt=media&amp;token=ac31d428-fb5e-4d87-90e7-c60f6954bb2a" alt="" width="563"><figcaption><p>Commit History in GitHub</p></figcaption></figure>

* If we push commits to the branch on the remote git, they will appear in the repository’s commit history. The new commit here is `f7559f8`.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FAMTKQZ6Ya9q2k9ZGcYp9%2Frg33.png?alt=media&amp;token=0849becf-7b3f-4d5a-b9c6-d6cfe792caf4" alt="" width="563"><figcaption></figcaption></figure>

* Then, we can go to Neurelo and click on Sync for the `feature-1` branch. This will start a sync in the background and pull the new commit.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fo34R0hJYCjPlJ17z7jss%2Frg34.png?alt=media&amp;token=62d94ecb-1c6c-44d4-a21e-33b8f584536e" alt="" width="563"><figcaption></figcaption></figure>

* If we open the Commit History in Neurelo, we see that the “new commit” with the same commit ID as GitHub appears.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FieC8X7Mu48b9J2oh4qXY%2Frg35.png?alt=media&amp;token=b3969789-dde9-4039-a222-04ea7c89af2c" alt="" width="375"><figcaption></figcaption></figure>


# Data Viewer

## Introduction

During the development and testing process, there is sometimes the need to view the data in the database being used to validate and debug api outputs, or to construct access operations. Neurelo offers a handy data viewer inside environments to quickly view data from the database attached to the environment.&#x20;

Also, the Data Viewer uses the same API key to access the data as you would use in your API/SDK calls to Neurelo, which makes it easier to confirm and validate, or debug the data you are working with when using the key. Any access control policies applied to the API Keys will also be enforced.

{% hint style="success" %}
This feature is supported for PostgreSQL, MySQL, and MongoDB
{% endhint %}

## Video Guide

If you prefer a more visual experience, please check out this video overview for this feature

{% embed url="<https://www.loom.com/share/9f4761a82dca4f15aeceaa379037f16e?sid=e18feefc-bbec-4a97-9ee5-e688576d4f39>" %}

## Using the Data Viewer in an environment

### Loading the Data Viewer

Step into your project from Neurelo's dashboard and navigate to the Environments section of your project using the left side navigation bar.&#x20;

Select the Environment you wish to use and you will find the **“Data Viewer”** button on the environment card. Click the “Data Viewer” button to take you to the "Data Viewer" tab under Environment Detail Page.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FLMyPXwOzHIJ6LvPhf9HP%2FData%20Viewer%20Updated.png?alt=media&amp;token=78c3ff95-5558-49f9-8807-e76d47349258" alt="" width="563"><figcaption></figcaption></figure>

{% hint style="warning" %}
The data viewer feature needs the environment to be running before you can use it. Please make sure the runners for the environment have been started. You can validate the runner status from the status dot next to the environment name -- *green* means running, *red* means stopped, and *orange* means they are in the process of being deployed.
{% endhint %}

{% hint style="info" %}
Make sure the environment is using the commit with the schema you are working on, has all migrations applied and is using the database that you want to view.
{% endhint %}

To use the Data Viewer, you need a valid API Key. If no API Key has been configured for the data viewer, you will see this message: “Please enter a valid API Key to view data” and the “Enter API Key” button will be shown. Click on this button to see API Key dialog box for Data Viewer.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FuzzwvTdsICLbFXUcKnT6%2FUntitled%201.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

If you already have an API Key for your environment, you can paste it into the displayed input box. If not, you can click the “Plus” button inside the input box to create a new API Key. Now you can hit the “Save & Apply” button. This will refresh the page and you will be able view the data from your tables and collections.

{% hint style="info" %}
If you do not have any data, you can check our “[Data Generator](/guides/mock-data-generation)” feature to populate your data source with some random data to get you started.
{% endhint %}

### Hide Columns

This feature lets you hide selected fields from your table view, you can view them later by simply un-checking the column name.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fn3oZigLyd3cjLZmGELow%2Fhide%20columns.png?alt=media&amp;token=e63817df-c56f-4101-8b4c-55311a66ee1f" alt="" width="563"><figcaption></figcaption></figure>

### Rows per page

* This feature is a select box that lets you configure how many rows are fetched and displayed on a single page.
* By default, 20 rows per page will be displayed

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fy8fM6Xo2R8xXjKncK0x4%2Frows%20per%20page.png?alt=media&amp;token=911060d5-8c6f-4388-937d-a98ae571e103" alt="" width="563"><figcaption></figcaption></figure>

### Pagination

* Displayed data is paginated and you can click on the right and left arrows to view the previous or next page respectively.
* It also lets you input a page value directly. Click the current page number to view an input box. You can directly navigate to any page and click outside the input box to apply changes.
* When the input box is focused, you can click up or down to increase or decrease page number respectively.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FoslWokCWBstSdr0Alm6X%2Fpagination.png?alt=media&amp;token=255d6bac-6195-4e5e-9ca3-e79a9326ca8f" alt="" width="563"><figcaption></figcaption></figure>

### Long values inside the table cell

* Long values inside displayed cells will be auto truncated. To see the fulls values inside your “Data Viewer” table, you can click the cell to expand the value in a scrollable section.
* To collapse and view the previous state, click the expanded cell.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FCK6ScM3a27nPn69XfIS7%2Fexpand%20data.png?alt=media&amp;token=64aa43a0-0692-4782-82ee-63e0253d363b" alt="" width="563"><figcaption></figcaption></figure>

### Refresh Data

* At times when you are testing your application you might need to reload the displayed data to view updated results.
* For this you can use the “Refresh Data” button located above the content section of “Data Viewer”
* Clicking on this button will instantly reload data without the need to refresh the page.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fg0WKh9MMq5pz5JkqovJ6%2Frefresh%20data.png?alt=media&amp;token=8e4b1152-9779-48af-a025-1958ef9a5869" alt="" width="563"><figcaption></figcaption></figure>


# Environment/Data Source Tags

To protect your environments and data sources from accidental changes, as well as better organization, you can add a tag to them. This is currently done on the settings pages for data source and environment respectively.

Currently we allow the following tags

* **Development**: Used for development
* **Staging**: Production-like, but without actual production data
* **Production**: We will disallow certain actions depending on your role (see [Roles/Permissions](/getting-started/dashboard/user-management/permissions-member-v-s-admin))
* **Test**: Used in your CI or for manual/automated

{% hint style="info" %}
Please refer to [this page](/getting-started/dashboard/user-management/permissions-member-v-s-admin) to review the permissions for member v/s admin roles across the platform
{% endhint %}


# How to work with Embedded  documents and References in MongoDB

## Overview

MongoDB is a NoSQL database and does not support classic relationships as in SQL databases. However, you can build references across entities in MongoDB in a couple of ways -

* Inner objects (equivalent to embedded documents, i.e., documents nested within another document)
* References across collections using an ObjectID field in a collection to reference an ID in another collection

For a more comprehensive overview on this topic, refer to MongoDB's docs on [Embedded Data Versus References](https://www.mongodb.com/docs/manual/data-modeling/concepts/embedding-vs-references/). In this guide, we will see how you can work with inner objects and references in MongoDB with Neurelo.

## Inner Objects (Embedded Documents)

An embedded document in MongoDB is a document nested inside another MongoDB document. That is, it is not just a reference to another document but it is fully contained within the parent document.

In the Neurelo Schema Language and in the APIs, embedded documents can be used as **innerObjects**.

For example, consider the following document

```json
{
  "_id": "5fc89ecd1e602ff6c856e811",
  "name": "Twinkle Truffles",
  "flavor": "Milk Chocolate",
  "brand": "Cadbunny's",
  "price": 2.99,
  "inStock": true,
  "nutritionalInfo": {
    "calories": 250,
    "fat": "10g",
    "sugar": "25g",
    "protein": "5g"
  }
}
```

Here, `nutritionalInfo` is an inner object.

Inner objects enhance read performance by reducing database queries and ensuring atomic updates within a single document. They are optimal for closely related data that is frequently accessed together, remains relatively static, and adheres to the 16MB MongoDB document size limit. However, they might lead to data redundancy and scalability challenges as your database grows.

The Neurelo Schema for this will be something like this -

```json
{
  "objects": {
    "foodItem": {
      "properties": {
        "id": {
          "type": "string",
          "identifier": true,
          "sourceName": "_id",
          "sourceType": "ObjectId",
          "default": {
            "function": "auto"
          }
        },
        "name": {
          "type": "string"
        },
        "flavor": {
          "type": "string"
        },
        "brand": {
          "type": "string"
        },
        "price": {
          "type": "number",
          "format": "float"
        },
        "inStock": {
          "type": "boolean"
        },
        "nutritionalInfo": {
          "$ref": "#/innerObjects/nutritionalInfo"
        }
      }
    }
  },
  "innerObjects": {
    "nutritionalInfo": {
      "properties": {
        "calories": {
          "type": "integer"
        },
        "fat": {
          "type": "string"
        },
        "sugar": {
          "type": "string"
        },
        "protein": {
          "type": "string"
        }
      }
    }
  }
}
```

For guidance on building APIs using inner objects, refer to the API reference materials for [REST](/neurelo-api-reference-rest) and [GraphQL](/neurelo-api-reference-graphql).

## References

References in MongoDB are used to link documents across different collections. This is a commonly used technique to represent one-to-one, one-to-many, or many-to-many relationships.

To do this, instead of embedding all data within a single document, we can reference data from other collections. For example, consider the following three documents from three different collections:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Femdf9gPj2INX9Zx0Ydvj%2FUntitled.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

Here, there is a one to one reference between `NutritionalInfo` and `Products`. Furthermore, there is a one to many reference between `Products` and `Reviews`.

The Neurelo Schema for this will be something like this -

<pre class="language-json"><code class="lang-json">{
<strong>  "objects": {
</strong>     "nutritionalInfo": {
      "properties": {
        "id": {
          "type": "string",
          "identifier": true,
          "sourceName": "_id",
          "sourceType": "ObjectId",
          "default": {
            "function": "auto"
          }
        },
        "calories": {
          "type": "string"
        },
        "fat": {
          "type": "string"
        },
        "sugar": {
          "type": "string"
        },
        "protein": {
          "type": "string"
        }
      }
    },
    "products": {
      "properties": {
        "id": {
          "type": "string",
          "identifier": true,
          "sourceName": "_id",
          "sourceType": "ObjectId",
          "default": {
            "function": "auto"
          }
        },
        "name": {
          "type": "string"
        },
        "flavor": {
          "type": "string"
        },
        "brand": {
          "type": "string"
        },
        "price": {
          "type": "number",
          "format": "float"
        },
        "inStock": {
          "type": "boolean"
        },
        "nutritionalInfoId": {
          "type": "string",
          "sourceType": "ObjectId"
        },
        "reviewIds": {
          "type": "array",
          "items": {
            "type": "string",
            "sourceType": "ObjectId"
          }
        }
      }
    },
    "reviews": {
      "properties": {
        "id": {
          "type": "string",
          "identifier": true,
          "sourceName": "_id",
          "sourceType": "ObjectId",
          "default": {
            "function": "auto"
          }
        },
        "productId": {
          "type": "string",
          "sourceType": "ObjectId"
        },
        "rating": {
          "type": "integer"
        },
        "comment": {
          "type": "string"
        }
      }
    }
  }
}
</code></pre>

Unlike embedded documents, references are more suitable for large or frequently changing data. They excel in many-to-many relationships by offering flexibility to link documents across different collections, preventing data duplication, and maintaining database normalization. However, this approach may require additional queries to access related data, potentially affecting performance.

Now, consider the same database structure as shown in the example above. To create references using Neurelo, it is important to structure your create queries in a specific order. This will ensure that all documents are created in the correct sequence to initiate the references between them. For instance,

* You can begin by creating the `NutritionalInfo` document, as this does not depend on any other documents.
* Next, you can create the `Products` document. Initially, you can include the `nutritionalInfoId` with the ID of the previously created `NutritionalInfo` document and initialize the `reviewIds` with an empty array.
* After this, you can proceed with creating individual `Reviews` documents, where each document references the `productId` of the `Products` document.
* And finally, you can update the `Products` document to include the `_id`s of the newly created `Reviews` documents.

For guidance on building create and update APIs, refer to the API reference materials for [REST](/neurelo-api-reference-rest) and [GraphQL](/neurelo-api-reference-graphql).


# How to download and use the Postman Collection for your Project

## Overview

With Neurelo, you can easily download a **Postman collection** for your automatically generated endpoints. This guide will help you start using this resource from the API documentation page.

## Download the Postman Collection for your Project

To get the Postman collection, you can either&#x20;

* Download the collection from under the "Docs" section with the Definitions for your project, or&#x20;
* Download the collection from the "APIs" section in your environment. &#x20;

In this guide, we will go over the details of how to download the spec from the environment view, but the process is similar for downloading the spec from the "Docs" section in the definitions view.&#x20;

Navigate to your environment's tab:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F5lXSPwc82MDK5WOd3AFI%2FUntitled.png?alt=media&amp;token=ccc92324-b005-4ecb-9d77-b51bb9e8b7d1" alt=""><figcaption></figcaption></figure>

This action will display the API section tailored to the commit selected for your environment.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FDxgByVpFr2hdhejnhHzv%2FUntitled%201.png?alt=media&amp;token=6433b446-f127-4185-a51c-d81beff1909d" alt=""><figcaption></figcaption></figure>

Look for a download (↓) icon at the top-right corner of this tab. Clicking this icon reveals the specifications and SDK download dropdown.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FZvcqWzQ7zFh0uyUcCeZu%2FUntitled%202.png?alt=media&amp;token=03c920e0-bdc2-4723-b695-d52275c48825" alt="" width="363"><figcaption></figcaption></figure>

Selecting the Postman collection option will initiate the download of a JSON-based Postman collection file.

**Note:** The downloaded spec varies depending on whether you are in the REST or GraphQL section. To download a Postman collection for GraphQL, ensure you switch to the GraphQL tab in the API documentation before downloading.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FXB8gx2rFtEamorZAseMM%2FUntitled%203.png?alt=media&amp;token=94f61f4d-a57d-471c-bb67-4a202f428315" alt=""><figcaption></figcaption></figure>

## **Importing the Collection into Postman**

To import the downloaded collection into your Postman app, start by clicking the 'Import' button within Postman.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F0iyBRoqcWaYMU2nx4aBI%2FUntitled%204.png?alt=media&amp;token=a4b36660-c10d-4586-a8b6-1a396cf33f18" alt=""><figcaption></figcaption></figure>

Then, import the JSON-based Postman collection file you downloaded from Neurelo.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FSWiKU5ck4EAdVoCnQyHL%2FScreenshot_2024-03-08_at_8.38.59_AM.png?alt=media&amp;token=8d4cabcf-a50c-412d-98dd-8fe13941ad56" alt=""><figcaption></figcaption></figure>

Completing these steps will generate a new Postman collection corresponding to your schema.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F9orfjlIBpU8GhIVOZWHV%2FUntitled%205.png?alt=media&amp;token=96197869-d442-4bd8-a7ac-a9ed8a4c7520" alt=""><figcaption></figcaption></figure>

## **Using Neurelo’s Postman Collections**

Neurelo structures each collection by creating individual folders for each object in your schema, organizing these folders according to the auto-generated API endpoints. Each object is equipped with auto-generated GET (to find, aggregate, and group objects), POST (to create one or multiple objects), PATCH, and DELETE HTTP methods.

{% hint style="info" %}
Note - this section discusses the Postman collection for Neurelo REST endpoints. For GraphQL, the only support HTTP method will be POST
{% endhint %}

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FNxwEF6dZo3p354HV8yxg%2FUntitled%206.png?alt=media&amp;token=5bd5e037-97aa-4e87-b0b1-dea81796940c" alt=""><figcaption></figcaption></figure>

### Required Setup

Once the Postman collection has been imported into Postman, you need to configure the <mark style="color:green;">{{baseUrl}}</mark> and set the <mark style="color:green;">X-API-KEY</mark> to be used in the header for the API calls.&#x20;

* You can get the <mark style="color:green;">{{baseUrl}}</mark> for your environment by navigating to the Environments section in your project<br>

  <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FECVTkva2n2mnCACEhxyk%2FbaseUrl.png?alt=media&amp;token=16a74493-0d33-407f-900d-a4c11be8b97c" alt=""><figcaption></figcaption></figure>
* Use the [API Key associated with your environment](/environments/api-keys) for the value of the <mark style="color:green;">X-API-KEY</mark> header

You can set these globally (and then they will be used for all the API calls), or set them per API.&#x20;

#### Global Settings

Click on the Collection Name in your Workspace and it will show you tabs including "Authorization" and "Variables"

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FIFKulFzAP20ePyUltpTW%2Fglobal-key.png?alt=media&amp;token=34763a7d-fd58-4936-9a2e-93be0dfafb5e" alt=""><figcaption></figcaption></figure>

1. Click on the "Authorization" tab and enter the X-API-KEY for your environment in the "Value" field. Once you input the API Key, the value should look something like this

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FcoDoXa8yBHgrgXC13EUy%2Fapikeyvalue.png?alt=media&amp;token=17f1e7ce-de0c-4663-abf1-52f947871b1d" alt="" width="563"><figcaption></figcaption></figure>
2. Click on the "Variables" tab and enter the URL for your environment under "Current Value" Once you enter the URL, it should look something like this

   <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FMXIvvBauZnaVUbU3of28%2Fbaseurlvalue.png?alt=media&amp;token=edabb7ae-51a2-4bc8-a0d7-c41d62f07fb8" alt="" width="563"><figcaption></figcaption></figure>

{% hint style="success" %}
Important - Remember to click "Save" at the top right to make sure your changes will be used
{% endhint %}

### Per API Setting

If you have configured the {{baseUrl}} and the X-API-KEY globally, you do not need to set them per API. However, if you have not enabled them globally, then you can configure them per API

* You can replace the {{baseUrl}} with the value directly in the request next to the GET/POST/PATCH/DELETE methods
* You can set the X-API-KEY value under the "Headers" for the request&#x20;

### Using the APIs

To execute an API request, simply populate the query parameters and the request body as needed. For guidance on building APIs, refer to the API reference materials for [REST](/neurelo-api-reference-rest) and [GraphQL](/neurelo-api-reference-graphql).

{% hint style="warning" %}
Note - The Postman client selects (enables) all parameters by default. Please unselect the parameters that are not needed for your API call
{% endhint %}

You're all set! You can now send your requests using the "Send" option for each API


# Building Python applications with Postgres and FastAPI

In this guide, we will walk through the process of creating a Python application using [FastAPI](https://fastapi.tiangolo.com/) together with Postgres using Neurelo.

{% hint style="info" %}
This guide can be easily adapted to other web frameworks, such as [Flask](https://flask.palletsprojects.com/en/3.0.x/).
{% endhint %}

Our goal is to create a "Fun Facts" application. This app will display a random animal fact to the user upon each site refresh. The facts, stored in a database on a remote server, will be managed through Python, with FastAPI serving as our chosen web framework.

Central to our application is Neurelo which will significantly simplify the database interactions by leveraging Neurelo’s auto-generated API endpoints.

Before we dive into building this application, let us lay the groundwork. This involves creating a new project, setting up a data source, and formulating a database schema suitable for our app. For this, we will use Postgres.

The first step is to [create a new project in Neurelo](/getting-started/starting-your-neurelo-project). Following the project creation, [add a data source to this project](/getting-started/starting-your-neurelo-project/step-1-add-a-data-source).&#x20;

Next, a database schema must be defined. For the sake of simplicity, our schema will include the following fields: `id`, `animal_name`, `fact`, and `created_at`. With this, we can [create our schema](/definitions/neurelo-schema-editor) as:

```json
{
  "objects": {
    "animal_facts": {
      "properties": {
        "animal_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            255
          ]
        },
        "created_at": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamptz",
            6
          ],
          "default": {
            "function": "now"
          },
          "nullable": true
        },
        "fact": {
          "type": "string"
        },
        "id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        }
      }
    }
  }
}
```

For more information on Neurelo’s Schema Language, see the [Neurelo Schema Language (NSL) documentation](/neurelo-schema-language-nsl).

Once your schema is ready, [commit it](/definitions/branches-and-commits) and then [create an environment attached to this commit](/environments/creating-a-new-environment).

After the environment is set up, applying a migration to your data source is straightforward. Just follow [these steps to migrate your schema](/environments/migrations).

Once migrations are completed, your database will be updated to match your schema in Neurelo. At this point, you are ready to use Neurelo's auto-generated API endpoints for your project. You can view these in the environment’s **APIs** tab.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FpGkKExDyDMGnzXCPiT2q%2Fimage.png?alt=media&amp;token=f7901494-cbe0-4a99-96d6-46a63069bcaa" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
We provide an [API Playground](/environments/api-playground) to easily run and test these auto-generated APIs!
{% endhint %}

It's now time to develop the application code in Python. We will begin by creating a class named `Neurelo` to facilitate interaction with Neurelo’s API endpoints, and consequently, our database. The code for this is straightforward:

```python
# neurelo.py
import os
import argparse
import json

import requests
from dotenv import load_dotenv


class Neurelo:
    def __init__(self):
        load_dotenv()
        self.headers = {
            "X-API-KEY": os.getenv("X_API_KEY"),
            "Content-Type": "application/json",
        }
        # For an object named `animal_facts`, the following GET MANY endpoint is auto-generated.
        # Details on these endpoints can be found in the API reference under the APIs tab.      
        self.api_url = "https://us-west-2.aws.neurelo.com/rest/animal_facts/"

    def store(self):
        """
        Stores the initial animal facts in the database.
        The 'facts.json' file should follow this format:
        [ {"id": 1, "fact": "Fact 1", "animal_name": "Animal 1"}, ..... ]
        """
        with open("./facts.json") as f:
            facts = json.load(f)
        response = requests.post(self.api_url, headers=self.headers, json=facts)
        print(f"Stored: {response}")

    def fetch(self):
        """
        Fetches all the animal facts from the database
        """
        response = requests.get(self.api_url, headers=self.headers)
        return response.json()["data"]

    def delete_all(self):
        """
        Deletes all the animal facts whose id is greater than or equal to 1
        """
        req = self.api_url + "?filter={%22id%22%3A%20{%22gte%22%3A%201}}"
        response = requests.delete(req, headers=self.headers)
        print(f"Deleted: {response}")

if __name__ == "__main__":
    neurelo = Neurelo()

    parser = argparse.ArgumentParser(
        prog="Animal Fun Facts", description="Shows animal-based fun facts"
    )
    parser.add_argument(
        "-c",
        "--cmd",
        default="f",
        help="f/s/d (fetches/stores/deletes) all data using Neurelo's API.",
    )
    args = parser.parse_args()
    actions = {"f": neurelo.fetch, "s": neurelo.store, "d": neurelo.delete_all}
    result = actions.get(args.cmd, lambda: "Wrong cmd. It should be one of (f/s/d)")()
    print(result)
```

Before running this code, it is essential to [generate an API Key in the environments tab](/environments/api-keys#creating-an-api-key-in-neurelo). Subsequently, store this key in an `.env` file as `X_API_KEY="<KEY>"`. Ensure the `.env` file is located in the same directory as your Python script.

And that's it! We have now established an interface with our database via Neurelo. This setup helps us to integrate this class with our preferred web framework to build our application. As previously mentioned, we will be using **FastAPI** to illustrate this process,

```python
import random

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from neurelo import Neurelo

app = FastAPI()
api = Neurelo()

templates = Jinja2Templates(directory="templates")


@app.get("/random-fact/", response_class=HTMLResponse)
async def read_random_fact(request: Request):
    random_fact = random.choice(api.fetch())
    if random_fact is None:
        raise HTTPException(status_code=404, detail="No facts available")
    return templates.TemplateResponse(
        "fact_page.html",
        {
            "request": request,
            "fact": random_fact["fact"],
            "animal": random_fact["animal_name"],
        },
    )

```

The server mentioned above includes an endpoint (`/random-fact/`) that retrieves a random fact from the `animal_facts` table via the `Neurelo` class, returning an HTML response rendered with a Jinja2 template. This code is assumed to be in a `main.py` file. The template, `fact_page.html`, can be straightforward:

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Random Animal Fact</title>
</head>
<body>
    <div>
        <h2>Random Animal Fact</h2>
        <p><strong>Animal:</strong> {{ animal }}</p>
        <p><strong>Fact:</strong> {{ fact }}</p>
    </div>
</body>
</html>

```

This template uses Jinja2 syntax to display the random fact. That's all there is to it! You can launch your FastAPI application with `uvicorn main:app --reload` and go to `http://127.0.0.1:8000/random-fact/` to see your application powered by Neurelo in action.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F8uWBxWzUhv2D4jtHHsVF%2Fimage.png?alt=media&amp;token=d2004862-3204-45fb-81e5-f7489645d83b" alt="" width="563"><figcaption></figcaption></figure>

As can be imagined, this code can be easily adapted to other web frameworks, such as [Flask](https://flask.palletsprojects.com/en/3.0.x/).

Now, imagine your database holds thousands of random animal facts, and you wish to avoid fetching all to select one on the server side. While you can use filters and other capabilities in Neurelo's auto-generated APIs for such queries, we will use [Neurelo’s Custom Queries](/definitions/custom-apis-for-complex-queries) feature to create custom endpoints as an example here.&#x20;

To begin, go to the Definitions view and click on the Custom Queries tab.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FAWDFZWMZkfn1rSD2YmTX%2Fimage.png?alt=media&amp;token=0feb7a88-6df0-416f-b230-0e8b2d7f6788" alt=""><figcaption></figcaption></figure>

Next, create a new custom query endpoint as shown below:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FJTFbUpc3pTPXjquzd8nO%2Fimage.png?alt=media&amp;token=f35d557c-6496-4e3b-8d8c-b1b21d101e87" alt="" width="563"><figcaption></figcaption></figure>

You can use Neurelo's [AI assistant](/definitions/custom-apis-for-complex-queries/ai-assisted-query-generation) for swift construction of a custom query. For this scenario, the prompt we will use is "fetch a random animal fact".

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FkhMNLkC5FDxhzKps7Dr5%2Fimage.png?alt=media&amp;token=33294f3e-a412-4bd6-9237-e705b3e13e61" alt="" width="563"><figcaption></figcaption></figure>

And there you have it! The endpoint and its corresponding query are ready in just a few seconds. Our [custom query testing playground](/definitions/custom-apis-for-complex-queries/write-and-commit-custom-queries#writing-custom-queries-in-neurelo) is also available for convenient query testing and iterations, if needed. The remaining step is to commit this new custom query definition, update our environment to incorporate this change, and then proceed with using the new endpoint.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F6ik7xAkGAnSmYrZuDUZx%2Fimage.png?alt=media&amp;token=408effde-b83d-469a-a5d1-46d8920fa0e6" alt=""><figcaption></figcaption></figure>

You can read more on [Custom Query Endpoints and AI-Assisted Query Generation](/definitions/custom-apis-for-complex-queries) in our documentation. Do not forget to update the `self.api_url` in the `Neurelo` class with your new custom endpoint, which, in this example, is `/custom/random_animal`.


# CI Integration using Neurelo CLI

## Overview

Testing is a critical step in the software development lifecycle. [Neurelo CLI](/cli-preview-version) makes it really easy to set up a "CI" environment that can be used for testing purposes.

## Creating a Machine User

The first step to automating your testing process with Neurelo is to create a new "Machine User" for your Organization. This user will have access to all projects in your Organization, and can be removed at any time.&#x20;

To create one,&#x20;

* Go to the [Org members page](https://dashboard.neurelo.com/members)&#x20;
* Click on the dropdown next to "Invite User" on the top right
* Click "Create Machine User"
* Set an identifier for your "Machine User" and click "Submit".

{% hint style="danger" %}
Once the "Machine User" has been created, you will be shown two pieces of information: the "client id" and the "client secret", make sure to store them safely and don't lose them, as the "client secret" won't be shown again.
{% endhint %}

This "client id" and "client secret" can now be used to authenticate the CLI and execute commands without any human interaction. For more details on the Neurelo CLI, please refer [here](/cli-preview-version)

## Using the machine user in the CLI

Before running the CLI,

* Setup  environment variables `NEURELO_CLIENT_ID` and `NEURELO_CLIENT_SECRET` using the "client\_id" and "client\_secret" from the prior step

Then,

* Run `neurelo login`

The CLI will look for the environment variables `NEURELO_CLIENT_ID` and `NEURELO_CLIENT_SECRET`, and will use them automatically when `neurelo login` is invoked.

## Using the CLI for CI tests

Once the CLI is authenticated, you can invoke&#x20;

{% code overflow="wrap" %}

```bash
neurelo ci start --projectId=.. --commitId=.. --region=.. --connectionString=.. --runId=.. --resetDb
```

{% endcode %}

which will do multiple things:

* Use the project configured with the `--projectId=` value
* Create a Data Source pointing to the provided `--connectionString=` value
* Create an Environment using the provided `--region=` and `--commitId=` values and attaching the previously created Data Source to it
* Create an API Key for the created Environment
* Start the Environment runners and wait for them to be ready
* Present the API Key as the output for it to be used in your tests
* The `--runId=` value is used to generate the Data Source, Environment, and API Key names. It is recommended to use unique and easy-to-identify values for this, like the short version of a commit hash or similar
* The `--resetDb` flag indicates that a full reset of the database should be applied before the runners are started. This means, delete the existing db schema and execute the available migrations for the environment

{% hint style="info" %}
Note - Mock Data Generation support is coming soon which will also enable you to generate mock data for your testing automatically as part of this piepline
{% endhint %}

After your tests have finished executing, by just invoking `neurelo ci stop`, all the previously created resources will be deleted.

## Sample Script

Here is a sample bash script that makes use of the Neurelo CLI to execute tests for a nodejs project:

{% code overflow="wrap" %}

```sh
#####################################################
#                    SET UP                         #
#####################################################

NEURELO_CLIENT_ID=3cf50a07...
NEURELO_CLIENT_SECRET=jj2h...

NEURELO_PROJECT_ID=prj_613d3826...
NEURELO_COMMIT_ID=cmt_e020f328...
DS_CONN_STRING=postgres://user:pass@psqlinstance:5432/cli
CI_IDENTIFIER=my-unique-identifier

neurelo login

ci_start_output=$(neurelo ci start --projectId=$NEURELO_PROJECT_ID --commitId=$NEURELO_COMMIT_ID --region=us-west-2 --connectionString=$DS_CONN_STRING --runId=$CI_IDENTIFIER)

NEURELO_API_KEY=$(echo $ci_start_output | grep 'Key: neurelo_' | cut -d ' ' -f 2| cut -b 1-245)

#####################################################
#                    RUN TESTS                      #
#####################################################

npm run test

#####################################################
#                   TEAR DOWN                       #
#####################################################

neurelo ci stop
```

{% endcode %}


# Schema Migrations

## Introduction

As we make changes to the schema for our PostgreSQL and MySQL databases, Neurelo also helps us auto-generate corresponding schema migrations and review/edit them, add migrations manually, and manage migrations in a version-controlled way. These migrations can be applied to our databases directly from within Neurelo, or we can download these migration files and apply them using schema migration systems we may be using like [Liquibase](https://www.liquibase.com/), [Flyway](https://github.com/flyway/flyway), or others.&#x20;

In this guide, we will look at how to create, edit, and apply migrations as we work on our schema.

## Video Guide

If you prefer a more visual experience, please check out the video version of this guide.&#x20;

{% embed url="<https://www.loom.com/share/5ce4f0adcc984a03bd88249e68478bb7>" %}
Creating and Editing Migrations
{% endembed %}

{% embed url="<https://www.loom.com/share/935d8d00564748cebb0253d32d677375?sid=9c12a8bb-bbb6-42a5-857a-4a11a487fb7e>" %}
Applying Migrations in Environments
{% endembed %}

## Creating and Editing Migrations

For the purposes of this guide, we will start with an empty project and build a schema and the migrations for that schema.&#x20;

Let’s start with a “New Empty Schema” from the Quick Start guide as we start a project, or by going to "Definitions" in the left sidebar for our project. We will see a dialog box like the following -&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FkvM7ZSzcVvA2DMkyzG1w%2FScreenshot_2024%2008%2022_at_19.58.57.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

We will create a simple schema with a `books` object, with `id` and `title` properties. This is how the schema will look in the Schema Builder view.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fy4h0IGpyktkaoF89RBnM%2FScreenshot_2024%2008%2022_at_20.02.23.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

Once we have our schema changes done, the corresponding migration file for this schema can be generated in a couple of ways -&#x20;

1. The migration file will be auto-generated if we commit the schema without manually creating an associated migration file.
2. Creating a migration file by going to the "Migrations" tab under Definitions&#x20;

Both of these will be detailed in this guide. Let's start with the case where the migration file is auto-generated on commit&#x20;

### Auto-Generate on Commit

The next step after we have made our schema changes is to commit the schema into the version control system. After clicking on the “Commit” button at the top right under the Definitions view, the “Commit changes” dialog box will be opened, and Neurelo will detect the schema changes and generate a migration automatically, if a migration has not been manually created by the user.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FGIEl0r2yJpG2NAnyZGh6%2FScreenshot_2024%2008%2022_at_20.03.28.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

Notice the information bar in blue in this modal is indicating that a migration (10\_migration, in this case) has been auto-generated to correspond with the schema changes we are committing.

### Creating a Migration

Let's make some additional schema changes to review how to add a migration manually. Let’s add a `summary` property to our `books` object. After adding the summary property, here is what the schema  diff looks like.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fr0SyTGvL2g5870jJVFYC%2FScreenshot_2024%2008%2021_at_11.15.06.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

Now, to generate the migration for this schema change, navigate to the “Migrations" tab and click “+” to add a new Migration. If this is the first migration, we can also use the "New" button to add a new Migration. In our case, we already have a "10\_migration" which was auto-generated in the earlier step.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FLIbxuxNzPbCAI2L09GqK%2FScreenshot_2024%2008%2021_at_11.16.17.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

This will bring up the “New Migration” dialog box. Here we can name the migration and enable the "Auto-Generate" option to generate the migration from the schema changes we just made. If we do not select the auto-generate option, then an empty migration file will be created for us to edit.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fq8lX4NOtR99EEXP6sn3f%2FNew%20Migration.png?alt=media&amp;token=b45707a3-0668-4b52-b6f2-573c9e425c1a" alt="" width="205"><figcaption></figcaption></figure>

{% hint style="info" %}
The *number* in the migration name determines the order in which migrations will be executed against your data source.&#x20;

When a new migration is created, we generate the number in the name for you based on the last migration number. The previous migration was 10\_migration, so the next recommended migration name is 20\_migration.&#x20;

You can edit this number, but make sure it's sequentially after the number used in the previous migration, if there is one. The part of the name after the "number\_" can be anything you prefer to help you understand this migration. It defaults to the text  "migration"
{% endhint %}

In our case, let’s name the migration as “20\_add\_summary” and click on “Create”. Since we selected the "Auto-Generate" option, the migration is automatically generated based on the schema edits.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fqg45sudKt8dMuO0q060I%2FScreenshot_2024%2008%2021_at_11.22.54.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

We can review the generated migration and edit it to make any adjustments. Once done, we can "Commit" these changes, but notice that there is a warning in this generated migration.&#x20;

Let’s solve that in the next section.

### Editing a Migration

Here is the warning from the above step.

{% code overflow="wrap" %}

```
Added the required column `summary` to the `books` table without a default value. This is not possible if the table is not empty.
```

{% endcode %}

Since we have added a non-nullable property `summary` without any default, it will cause issues during the migration because if there are existing rows, the summary column may not have any data and it won't be successfully migrated.

There are two ways to solve this in the schema -&#x20;

1. We can make the `summary` nullable
2. We can add a default string value

Let’s go with Option 1 to make the property nullable. We will go back to the "Schema" tab and mark the `summary` as nullable. Here is how the property and the schema diff look after this change.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F9S8XroDljWh22hmn0m4l%2FScreenshot_2024%2008%2021_at_11.29.20.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FXa0KHcV1fkp0gMj4Hm9o%2FScreenshot_2024%2008%2021_at_11.29.33.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

Then, we can navigate back to the “Migrations Tab” and select the migration for this commit which is `20_add_summary`. Here we can click on the "Regenerate migration" icon to auto-generate the migration again with the latest schema changes. We could also manually edit the migration as well, if we don't want to auto-generate this migration again.

{% hint style="info" %}
The "Regenerate migration" option is only available for new migrations being created. It is not available for already committed migrations.
{% endhint %}

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FsRAr11J47BSAKtRdsS0s%2FScreenshot_2024%2008%2021_at_11.33.20.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

Here is the diff of the migration that is now generated. In the new migration, the `NOT NULL` instruction is removed; therefore, the warning is gone. Click on “Continue” to use this.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FImNObto8Hd5xo2e4Bbt4%2FScreenshot_2024%2008%2021_at_11.35.11.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

We can now commit the schema with it's associated migration and use it in our Environments.

## Using Migrations in Environments

In the [Create and Edit Migrations](#creating-and-editing-migrations) section, we created two commits, each with schema changes and the corresponding migrations. Let’s look at how to use them in the environments.&#x20;

{% hint style="info" %}
In the Commit History, you might also see an "Initial empty commit" which is created when the project is first initialized. This is an empty commit and does not have any schema or migrations in it.
{% endhint %}

Let's say we already have an environment (if not, please create one -- see the [Environments](/environments) section for more information). Let's navigate to the environment we want to work on by selecting "Environments" from the left sidebar for our project.&#x20;

Once the environment is loaded, let's make sure the environment is using the latest commit of the definitions. Then navigate to the “Migrations Tab", and we can see that there are two migrations available there for that commit.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FYtF1hYw4ZjYBQenhC2Lj%2FScreenshot_2024%2008%2023_at_10.12.32_(1).png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

### Apply Migrations using Neurelo

We can apply these Migrations to the database attached to this environment by clicking the “Apply 2 Migrations” button.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FkXbXm1iMIoJSXwCd4CjA%2FScreenshot_2024%2008%2023_at_10.12.32.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

This will open the Apply Migrations confirmation dialog.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FZqRamBDy0hvzBmlnLBRG%2FScreenshot_2024%2008%2023_at_10.15.14.png?alt=media" alt="" width="375"><figcaption></figcaption></figure>

Once confirmed, the migrations will start to be applied to the database

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FMOrgJ7RnV2QoAeI7RM4L%2FScreenshot_2024%2008%2023_at_10.17.11.png?alt=media" alt="" width="375"><figcaption></figcaption></figure>

After the migration process completes successfully, the “Your data source is up to date with your current schema" message will be displayed.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FlxfsNc64sHKnOcXNYWJt%2FScreenshot_2024%2008%2023_at_10.18.10.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

And this is how we can use Neurelo to directly migrate our data source. Now, let’s see how to migrate the data source manually.

### Manually Applying the Migrations

For this let's make another change to the schema first. Let's navigate back to "Definitions" and add an `authors` object to the schema with `id` and `name` as properties, and commit it.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F0MatjjNzxUxRaswl4Qmx%2FScreenshot_2024%2008%2023_at_10.29.53.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

Notice that the migration was autogenerated in this case.&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FDQVN6cwgliXka8kYl2w6%2FScreenshot_2024%2008%2023_at_10.30.00.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

Now, let's go back to the environment we were using and update the commit using the “Commit Selector” to this latest commit.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FrFQG7VDmzaZdAdpsm5Cy%2FScreenshot_2024%2008%2023_at_10.32.51.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

Once we update the commit, let's navigate to the "Migrations" tab. You will notice that the sidebar now  reflects the new `30_migration`. To apply it manually, we can copy the migration contents from the editor or download the migrations using the download button in the sidebar.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F2ZMDvbYaXuSgAHFU8hrH%2FScreenshot_2024%2008%2023_at_10.34.56.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

This will download all the migration files as `.sql` in a zip file. The downloaded files will look something like this&#x20;

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F31oPqHhB1lm78xlZu6Zl%2FScreenshot_2024%2008%2023_at_10.38.32.png?alt=media" alt="" width="375"><figcaption></figcaption></figure>

Now we can use these migrations and apply them manually to the database using tools like [TablePlus](https://tableplus.com/), [Liquibase](https://www.liquibase.com/), [Flyway](https://www.red-gate.com/products/flyway/community/), and others.&#x20;

Once we execute `30_migration.sql`, we can mark the migration as applied in Neurelo to keep the migrations in sync. To do that, we can click on the “Mark as Applied” option.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FKEAra9VTsmfKbS12uzi4%2FScreenshot_2024%2008%2023_at_10.40.53.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

This will open the “Mark as Applied” dialog box where we can select which migrations we want to mark as applied outside of Neurelo.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FhN4Sq2rcLVcwUc2PQOiS%2FScreenshot_2024%2008%2023_at_10.46.52.png?alt=media" alt="" width="375"><figcaption></figcaption></figure>

In our case, we will select the `30_migration` and click on “Mark 1”

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fa1mo1uNBwfWUv2SHcbkk%2FScreenshot_2024%2008%2023_at_10.47.53.png?alt=media" alt="" width="375"><figcaption></figcaption></figure>

After that, we can see that the green checkbox against the `30_migration` and the “data source is up to date with the schema" message as before.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FIcwmL30HyZEXvrii4J3G%2Fmark%20as%20applied.jpg?alt=media&amp;token=1249632a-3324-40ec-9d63-ac1ef4a26db4" alt="" width="563"><figcaption></figcaption></figure>


# Schema AI Assist

## Overview <a href="#jgde7658dk28" id="jgde7658dk28"></a>

Traditionally, creating a database schema involves a detailed analysis of business requirements, followed by designing tables and relationships using tools and languages like SQL. This process can be time-consuming, complex, and prone to human error. Now, you can leverage the power of artificial intelligence to automate and enhance the process of designing and optimizing database structures with **Neurelo's AI Schema**<span data-gb-custom-inline data-tag="emoji" data-code="2728">:sparkles:</span>feature.&#x20;

Neurelo's AI Schema Assist capability helps construct schemas for your application, just by specifying the intent of the application you want to build. If you already have an existing schema, it also allows you to extend and enhance your schema.&#x20;

This feature significantly reduces the time and effort required to design complex database schemas and also helps adapt the schema to changing business requirements and data patterns.

{% hint style="info" %}
This feature is supported for MongoDB, MySQL, and PostgreSQL
{% endhint %}

## Using Schema AI Assist <a href="#tx7y5nt37vw6" id="tx7y5nt37vw6"></a>

### For a New Project <a href="#id-6qaabe60nksw" id="id-6qaabe60nksw"></a>

To generate the schema using AI Assist for new projects, start by creating a new project. Once done, you will be presented with the option to either "Connect to a Data Source" or "Build Definitions" in your project dashboard.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FtoKeAxjarnqS4L8Hw6rY%2F0.png?alt=media" alt="" width="563">

Click on the "**Build Schema**" button under "Build Definitions." This will present you with the "Build a Schema" view.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FePEiZYHPW1foPYHy8E4E%2F1.png?alt=media" alt="" width="563">

In this view, click on the "**Schema AI Assist**" option. This will present you with a playground to build and iterate over your schema.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FbVLqdJsRgP9Qtig74U21%2F2.png?alt=media" alt="" width="375">

Let us say we would like to create a new schema for a "Retro CD Collection." To build this schema, you can send the following prompt in the playground: "Build a schema to store Retro CD Collection data." The database engine we will be using for this example is MongoDB.

Once the schema is generated, the playground will automatically close, and you can visualize your schema in our "Schema Builder" view. Here is an example of a schema generated by Schema AI Assist for MongoDB:

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FY1uV881kqyFqKNTAjtiI%2F3.png?alt=media" alt="" width="563">

As you can observe, it generated a single object "cdCollection" with properties such as the album name, artist name, release year, genre, track list, duration, label, and the condition of the CD (mint, good, fair, etc.).

Notice also how the types are correctly aligned with what’s usually expected from such schemas.&#x20;

{% hint style="info" %}
You can also open the schema in the "ERD" view to review the schema
{% endhint %}

If you are satisfied with the first iteration, make sure to commit your changes. If you would like to further iterate over it, click on the "**AI Assist**" button on the top right of the "Schema" view to open up the playground again.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FpIe6M2V8zzmwjaeZFjdh%2F4.png?alt=media" alt="" width="375">

Let us say for the second iteration, we would like to update the “condition” property so that the options (mint, good, fair, etc.) are not of type “*String*” but instead should be an “*Enum*” with a couple of options.&#x20;

To do this, you can simply use a prompt such as “Let us use an enum for the condition property.”&#x20;

Et voila! The “condition” property is now an enum.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FnM9Y1a849NTNlON04hPo%2F5.png?alt=media" alt="" width="563">

You can also ask it to create complex schemas, such as extending the existing schema to store cover art details and the CD’s physical appearance details. For instance, doing so generates the following schema (visualized using our ERD viewer):

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F3Ml6nANlH3ikestuIYEr%2F6.png?alt=media" alt="" width="563">

As you can notice, it generated two “Inner Objects” (Embedded Documents in MongoDB) inside the “cdCollection” object to store the details for cover art and the CD’s physical appearance. To read more about how we support Embedded Documents, check out our tutorial on [how to work with Embedded Documents and References in MongoDB](/guides/how-to-work-with-embedded-documents-and-references-in-mongodb).&#x20;

You can also edit this schema manually using the Schema Builder, or the JSON/YAML editors. Once you have a schema you like, you can **Commit** the schema and use it in your environments.

### For an Existing Project <a href="#fnkrytf7b0l6" id="fnkrytf7b0l6"></a>

Using Schema AI Assist for existing projects is similar to using it for new projects. Simply click on the “**AI Assist**” button in the “Schema” view under the Definitions for your project.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FWzhyz3as2l4V2YngpHsQ%2F7.png?alt=media" alt="" width="375">

The Schema AI playground should pop up. You can then specify a new prompt and iterate over your existing schema.

## Limitations <a href="#ph6p1gweqxxx" id="ph6p1gweqxxx"></a>

Please note the following when using the Schema AI Assist feature:

* While it is rare, there might be cases where Schema AI Assist generates inaccuracies in certain parts of the schema. This should be immediately flagged by our “Schema Validation” functionality. Should this happen, we recommend you either:
  * Iterate again with Schema AI Assist over your previously working schema
  * Or, switch to the “JSON/YAML Editor'' and directly correct the inaccuracies in the Neurelo Schema Language (NSL). To read more about how to work with NSL, check out our guide on [Neurelo Schema Language (NSL)](/neurelo-schema-language-nsl).
* Note - If there are inaccuracies, before using Schema AI Assist again make sure to fix the schema first or switch back to your previous working schema before iterating again. We use the most recent schema present in the Schema definitions editor to generate a new schema


# Auto-Introspection

## Overview

If you have an existing database that is managed externally, you can opt to have Neurelo run introspections on this database periodically.

## Setup

To enable Auto-Introspection, go to the project settings page and enable Auto-Introspection.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FZlpq6lyRfHT0s9FOJwhk%2FScreenshot%202025-01-27%20at%2015.17.31.jpg?alt=media&amp;token=31c158da-04e5-41e9-83fd-9a025a76c2af" alt=""><figcaption></figcaption></figure>

## Usage

Once you activated Auto-Introspection, you will find a new item in the in the schema-editor view, showing the current introspection status.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fu1TQu14Ed3EXGLgZyZcQ%2FScreenshot%202025-01-13%20at%2016.03.42.jpg?alt=media&amp;token=86224f4a-a8c6-4f09-b738-8d2a49e55424" alt=""><figcaption></figcaption></figure>

If there are changes to the schema, you should either see "Changes Detected" or "Applied", depending on whether you selected "Commit to main branch" in the setup.

<div><figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FL8WTqB8H4t7DAbn0gTzw%2FScreenshot%202025-01-13%20at%2014.45.04.jpg?alt=media&amp;token=1ebe8edc-e8ba-42cb-932c-6a1836bdeb36" alt=""><figcaption></figcaption></figure> <figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FRe2Uin2Z6Azo1atAyiAd%2FScreenshot%202025-01-13%20at%2014.46.10.jpg?alt=media&amp;token=16a822e5-3ecf-493f-a110-dd548a09d1f9" alt=""><figcaption></figcaption></figure></div>

From here, you can review the found changes, run an introspection manually or view the history of introspections and their found changes. Here you will also see when the next introspection will run.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FqRLWFmRgJEiCztONfYb6%2FScreenshot%202025-01-13%20at%2014.45.55.jpg?alt=media&amp;token=ade9e61f-6a0c-4179-87bc-178cf1f00664" alt=""><figcaption></figcaption></figure>


# Access Policies

## Overview

When creating an [API Key](/environments/api-keys) for using Neurelo APIs in the Environment for your Project, by default you can allow Read-Only or Read/Write permissions for the entire Environment. Access Policies allow more fine-grained control, where you can configure permissions at an object and property level for the schema being used in the environment.

## Using Access Policies

### **Define your schema**

Before you start with access policies, you should have your schema already in place (see <https://docs.neurelo.com/definitions>). This is because you will reference objects and their properties when defining access policies.&#x20;

### **Define Access Policies**

* Navigate to the “Access Policies” tab under the Definitions for your Project
* Create one or more access policies. See [Access Policy definitions](#access-policy-definitions) for a description of the supported policy definitions and their format.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FKBbArjRwb1xJH3xf0WPd%2FScreenshot_2024%2006%2028_at_10.34.01.jpg?alt=media" alt="" width="563"><figcaption></figcaption></figure>

* Once you have defined your access polices, create a new **commit** for your definitions.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FKoDYplzIpJZILIQbkBB9%2FScreenshot_2024%2006%2028_at_10.34.39.jpg?alt=media" alt="" width="563"><figcaption></figcaption></figure>

### **Create an API Key**

* First, if you don’t already have one, you will now have to create an environment (see <https://docs.neurelo.com/environments/creating-a-new-environment>) and use the Commit of the definitions which include the Access Policy definitions.
* If you already have an environment, navigate to the Environment for your project from the left side navigation bar or from the dashboard for your project and update the Environment to use the **Commit** of the definitions which include the Access Policy definitions.&#x20;
* Create the API Key as described in <https://docs.neurelo.com/environments/api-keys>. Now you will find there an option to choose your access policy to be attached to this key

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FJ3HwxSxCgUaaUsZApwKM%2FScreenshot_2024%2005%2029_at_14.03.01.jpg?alt=media" alt="" width="375"><figcaption></figcaption></figure>

### **Use the API Key**

* You can use your access policies enabled API key anywhere you would use a regular key.&#x20;
* The operations that can be performed using the key will follow the policies you have defined and attached to that key.&#x20;

## Access policy definitions

Each Access Policy is defined as a list of CRUD (<mark style="color:red;">`create`</mark>/ <mark style="color:red;">`read`</mark> / <mark style="color:red;">`update`</mark> /<mark style="color:red;">`delete`</mark>) permissions on an object or inner object.

### <mark style="color:red;">**`create`**</mark>

Create an object. This also allows creation of contained inner objects (for MongoDB projects).

Example:&#x20;

```json
[
   {
      "create":"Book"
   }
]
```

### <mark style="color:red;">**`createAnyObject`**</mark>

Create any object (regardless of the object name). This also allows creation of contained inner objects (for MongoDB projects).

Example:

```
[
    "createAnyObject"
]
```

### <mark style="color:red;">**`read`**</mark>

Read fields in an object or inner object (for MongoDB projects). This includes checks in a `where`.

Checks must have these keys

* `objectName`/`innerObjectName`: Name of the object or inner object (for MongoDB)
* `properties`: The properties allowed to be inspected

Example:&#x20;

```json
[
   {
      "read":{
         "objectName":"Publisher",
         "properties":[
            "id",
            "location",
            "name"
         ]
      }
   },
   {
      "read":{
         "innerObjectName":"Location",
         "properties":[
            "city_name",
            "state_name",
            "zip_code"
         ]
      }
   }
]
```

### <mark style="color:red;">**`readAnyProperty`**</mark>

Read any field in an object or inner object (for MongoDB projects), regardless of the property name. This includes checks in a `where`.

Checks must have these keys

* `objectName`/`innerObjectName`: Name of the object or inner object (for MongoDB)

Example:&#x20;

```json
[
   {
      "readAnyProperty":{
         "objectName":"Publisher",
      }
   },
   {
      "readAnyProperty":{
         "innerObjectName":"Location",
      }
   }
]
```

### <mark style="color:red;">**`readAnyObject`**</mark>

Read fields in any object or inner object (for MongoDB projects), regardless of the object name. This includes checks in a `where`.

Example:&#x20;

```json
[
   "readyAnyObject"
]
```

### <mark style="color:red;">**`update`**</mark>

Alter the contents of an object or inner object (for MongoDB). This is parameterized by a list of properties, allowing only some fields to be modified.

Checks must have these keys

* `objectName`/`innerObjectName`: Name of the object or inner object (for MongoDB)
* `properties`: The properties allowed to be inspected

Example:

```json
[
   {
      "update":{
         "objectName":"Publisher",
         "properties":[
            "id",
            "location",
            "name"
         ]
      }
   },
   {
      "update":{
         "innerObjectName":"Location",
         "properties":[
            "city_name",
            "state_name",
            "zip_code"
         ]
      }
   }
]
```

### <mark style="color:red;">**`updateAnyProperty`**</mark>

Alter the contents of an object or inner object (for MongoDB), regardless of the property names.

Checks must have these keys

* `objectName`/`innerObjectName`: Name of the object or inner object (for MongoDB)

Example:

```json
[
   {
      "updateAnyProperty":{
         "objectName":"Publisher",
      }
   },
   {
      "updateAnyProperty":{
         "innerObjectName":"Location",
      }
   }
]
```

### <mark style="color:red;">**`updateAnyObject`**</mark>

Alter the contents of any object or inner object (for MongoDB), regardless of object name.&#x20;

Example:

```json
[
    "updateAnyObject"
]
```

### <mark style="color:red;">**`delete`**</mark>

Delete an object. This will also allow delete for any inner objects (for MongoDB projects).

Example:&#x20;

```json
[
   {
      "delete":"Book"
   }
]
```

### <mark style="color:red;">**`deleteAnyObject`**</mark>

Delete any object, regardless of object name. This will also allow delete for any inner objects (for MongoDB projects).

Example:&#x20;

```json
[
    "deleteAnyObject"
]
```

### <mark style="color:red;">**`customQuery`**</mark>

Allow a specifc custom query, specified by name.

Example:&#x20;

```json
[
   {
      "customQuery": "find_books_by_publishers_in_new_york"
   }
]
```

### <mark style="color:red;">**`customQueryAny`**</mark>

Allow any custom query, regardless of name.

Example:&#x20;

```json
[
    "customQueryAny"
]
```

## Usage Notes

### Response Code&#x20;

If the request attempts to perform an operation that isn’t allowed by the policies specified, the response will have the status code <mark style="color:red;">**`HTTP 403 - Forbidden`**</mark>

### Updating Policies

If you would like to update the existing attached policies for an api key,

* Edit the policies in the Access Policies tab under Definitions
* Create a new Commit
* Update the Environment to use this new Commit. This step will need Runners for the environment to be stopped and re-started.

Once the environment is updated, new incoming requests with that key will be evaluated against the updated policy definitions

### Multiple Policies

You can create and attach multiple policies to an API Key. When multiple policies are identified for an API operation, the operation will be allowed based on the cumulative set of permissions from all of the policies. For example, consider the following permissions:

```jsx
# `read_city_state` permissions:

[{
    "read": {
        "objectName": "Location",
        "properties": ["city_name", "state_name"]
    }
}]
```

```jsx
# `read_zip_code` permissions:

[{
    "read": {
        "objectName": "Location",
        "properties": ["zip_code"]
    }
}]
```

A `GET` request to the `/rest/Location` endpoint with&#x20;

* the select parameter `{"city_name":true,"state_name":true,"zip_code":true}`&#x20;
* specifying the roles `["read_city_state","read_zip_code"]`&#x20;

will be allowed because each selected field is permitted by a rule in one of the policies.&#x20;

However, the same operation only with the `"read_city_state"` role but not `"read_zip_code"` would receive an `HTTP 403` response due to no permissions allowing inspection of the `zip_code` field to be found.

### Relations

When performing an operation that accesses or modifies across a relation, permissions for the related object will be checked as needed.&#x20;

For example, if a schema contains an object called `User` with a field called `blog_post_ids` that relates to one or more `Post` objects,&#x20;

* querying the `blog_posts` field of the `Users` object will require read permissions for the relevant `id` field of `Post` that the `blog_post_ids` field of `User` references.&#x20;
* Similarly, an update to the `User` object that uses the `"create"` operator to add a reference to new existing `Post` would require permission to create that


# User Auth

This features enables you to add support in your applications for your users to log in using social logins (Google, Github, ...). The data (user accounts and credentials) are stored within *your* database so you can query them like any other object.

{% hint style="info" %}
We currently support this feature with MySQL and MongoDB. If you are interested in using User Auth with PostgreSQL, please reach out to us.
{% endhint %}

## Setup

### **Enable User Auth in the schema**

To use User Auth, your schema needs to have it enabled first. To do this, just click the "Enable User Auth" toggle in the schema editor and create a new commit with the schema.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FyUFaPZb6c29HFaNMqfBt%2FScreenshot%202024-09-19%20at%2013.48.31.jpg?alt=media&amp;token=3461d542-7484-4796-a7de-cb21141e7a13" alt="" width="375"><figcaption></figcaption></figure>

### **Configuring User Auth**

Before configuring User Auth, make sure that you have an environment with the new Auth-enabled Commit running (see [Creating a new Environment](/environments/creating-a-new-environment)).

Once you configured the environment to use your new commit, you will see a "User Auth" tab in the environment dashboard.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FRQl86Va1E21jzwlgu0b9%2FScreenshot%202024-09-19%20at%2014.01.38.jpg?alt=media&amp;token=6b72440a-5425-4606-b597-78c4384ff8cf" alt="" width="375"><figcaption></figcaption></figure>

In this tab you'll first set the redirect URL. This is where your application is running at and where your users will be redirected to after a successful login. Here this example is showing `http://example.com`

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FCog4xEGYe1hWsuFzduDV%2FScreenshot%202024-09-19%20at%2013.55.04.jpg?alt=media&amp;token=773a9871-6031-49bb-b0ab-4dd1bf232dd2" alt="" width="375"><figcaption></figcaption></figure>

After that you will be prompted to add one or more Authentication Providers.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FASK6c8Xei5c5NpzT5OdA%2FScreenshot%202024-09-19%20at%2013.55.30.jpg?alt=media&amp;token=378e3cbe-45de-4df5-96a1-42f42c4ef861" alt="" width="375"><figcaption></figcaption></figure>

For every provider you will need a *Client ID* and *Client Secret*.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FrzJWD1pdtg1FXDlbxPSJ%2FScreenshot%202024-09-19%20at%2013.56.06.jpg?alt=media&amp;token=4e763a89-f01a-4565-b163-9a2046e57827" alt="" width="563"><figcaption></figcaption></figure>

To set up the clients at the providers, see one of the following:

* [Google](/guides/user-auth/google)
* [GitHub](/guides/user-auth/github)
* [GitLab](/guides/user-auth/gitlab)

After you are done adding your providers, you can test your login by following the sign-in link below the provider table.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FBR4jQab9nciy1RlyrMdI%2FScreenshot%202024-09-19%20at%2013.58.28.jpg?alt=media&amp;token=67c68020-a893-4765-b209-4fea9f9df388" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FaOnosYSiJzFgCUcMBTk5%2FScreenshot%202024-09-19%20at%2013.58.53.jpg?alt=media&amp;token=74221ab8-a603-4f5f-9507-a8c385d6f18c" alt="" width="375"><figcaption></figcaption></figure>

### Integration into your application

We make it very easy to add User Auth to your NextJS Application. Just head to<https://github.com/neurelo-public/neurelo-auth-next> and follow the README to get started.

If you would like to use User Auth with a different framework please reach out to us.


# Google

To set up OAuth for Google navigate to <https://console.cloud.google.com/apis/credentials> and create a new Client ID. If this is your first time doing this you may need some initial setup (see <https://support.google.com/cloud/answer/6158849>).

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FH84P3oaP0w6Bjbgvda5s%2FScreenshot%202024-09-19%20at%2015.54.49.jpg?alt=media&amp;token=06fd5b46-dfa2-4da9-8a03-34c800d23dad" alt="" width="563"><figcaption></figcaption></figure>

In the create form, set the fill in the following:

* **Application type**: Web application
* **Name**: The name of your application
* **Authorized redirect URIs**: Add the callback URL from the Auth Provider dialog

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fez0trC288vL2GiHqGsEN%2FScreenshot%202024-09-19%20at%2016.01.46.jpg?alt=media&amp;token=38dbf3f1-f936-4a90-9b67-26de5997a942" alt="" width="375"><figcaption></figcaption></figure>

After adding the new OAuth client, you can copy the Client ID and Client secret into the Auth Provider dialog and save.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F3aJWjUOb4HBCxDZShlip%2FScreenshot%202024-09-19%20at%2015.58.46.jpg?alt=media&amp;token=e2625a46-d67c-4f01-890d-92800b3383a1" alt="" width="375"><figcaption></figcaption></figure>


# GitHub

To set up an OAuth App navigate to <https://github.com/settings/developers> and click on "New OAuth App"

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fm3sbUJscMMmGKCWlmCUE%2FScreenshot%202024-09-19%20at%2015.11.51.jpg?alt=media&amp;token=3b846c82-74bf-4b18-be72-1e8b7777b81b" alt=""><figcaption></figcaption></figure>

On the setup screen you then fill out the fields as follows:

* **Application Name**: The name of your application.
* **Homepage URL**: Where your application is running.
* **Authorization callback URL**: Paste the URL from the Authentication Provider edit dialog in Neurelo.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FaIhCe2lFB78d99x17oj2%2FScreenshot%202024-09-19%20at%2015.19.02.jpg?alt=media&amp;token=af3b0590-146d-4897-bc1e-9be17ba46361" alt="" width="375"><figcaption></figcaption></figure>

On the following screen you will have to generate a Client Secret.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FHEixKpSRZt7IJkdCcTo9%2FScreenshot%202024-09-19%20at%2015.24.47.jpg?alt=media&amp;token=b405da4e-0255-4bbe-a14f-f2b05c3903b5" alt="" width="375"><figcaption></figcaption></figure>

Lastly you will copy the Client ID and Client Secret into the Auth Provider dialog and save.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FSmcCFsq6fM1IDuIhCNDX%2FScreenshot%202024-09-19%20at%2015.27.20.jpg?alt=media&amp;token=f664b1c5-4635-404e-bb7e-1f26c1b972e0" alt="" width="375"><figcaption></figcaption></figure>


# GitLab

To set up an OAuth App navigate to <https://gitlab.com/-/profile/applications> and click on "Add new application"

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FneSyRTxvxpC9w8tix2YG%2FScreenshot%202024-09-19%20at%2015.34.22.jpg?alt=media&amp;token=8e84000c-6020-4712-abf6-dafc55108857" alt=""><figcaption></figcaption></figure>

You then fill in the following:

* **Name**: The name of your application
* **Redirect URI**: The callback URL from the Auth Provider dialog
* **Scopes**: `read_user` needs to be enabled but you can choose more if you want to use the GitLab API from your application backend.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FS745HQRAyql7YFpkkEZI%2FScreenshot%202024-09-19%20at%2015.35.27.jpg?alt=media&amp;token=081e28ee-15ad-42f4-897c-00c8e0297ac3" alt=""><figcaption></figcaption></figure>

After confirming, you can copy the *Application ID* and *Secret* in to the *Client ID* and *Client Secret* fields in the Auth Provider dialog and save.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FyZKmu2XwKOkthU219AGW%2FScreenshot%202024-09-19%20at%2015.35.58.jpg?alt=media&amp;token=56fec698-9426-4e3d-9b7c-10c6c27482af" alt=""><figcaption></figcaption></figure>


# MongoDB Atlas - Migrate GraphQL to Neurelo

## Introduction

Neurelo is a platform designed to simplify the process of working with databases for developers. It offers features such as building and managing schemas with Text-to-Schema support, GraphQL APIs (with SDKs) auto-generated from your schema with documentation and a playground, custom GraphQL API endpoints for complex queries with MQL support, multiple CI/CD environments, schema-aware mock data generation, and more.

This is a guide to help MongoDB Atlas users get started with Neurelo and Neurelo's GraphQL APIs.

For a complete reference on Neurelo's auto-generated GraphQL APIs, check out our [Neurelo API Reference (GraphQL)](https://docs.neurelo.com/neurelo-api-reference-graphql) documentation.

## Video Guide

If you prefer a more visual experience, please check out the video version of this guide.&#x20;

{% embed url="<https://www.loom.com/share/193d85ea169846ec94ea30e3c1f29fb9?sid=f262d1fa-326b-4d8c-ad03-bf4b327b735b>" %}

## Creating a Neurelo Account <a href="#b1puftb7rbol" id="b1puftb7rbol"></a>

Navigate to[ https://dashboard.neurelo.com/](https://dashboard.neurelo.com/) to access the Neurelo dashboard. Once there, you'll find the option to sign in to your existing account if you already have one, or if you don't have an account, you can create a new Neurelo account using the "**New to Neurelo?**[ **Create an Account**](https://dashboard.neurelo.com/register)" option on the page. A step-by-step guide on [how to create an account](https://docs.neurelo.com/getting-started/sign-in-sign-up) can be found in Neurelo’s documentation.

## Creating a Neurelo project <a href="#ttrcqwqat7or" id="ttrcqwqat7or"></a>

Projects are applications that developers build and run with Neurelo. This is the primary “working” entity where all things start inside Neurelo. A project exists inside an Organization and has its own set of entities such as data definitions, environments, dashboards, data sources, etc.

After signing in to your Neurelo account, you will be directed to your Neurelo Dashboard. This is your central hub for managing your projects.

If you have a new account, you will see the option to create a new project as one of the first things you need to do to get stated. If you already have another project in your account, look for an orange button on the top-right of the Dashboard with a + icon and the word "New" inside it. This button is designed for creating new projects.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F3cGwxYtVJE8Tw60RhlSC%2F0.png?alt=media" alt="" width="375">

Clicking on it will open the “New Project” modal. Enter the project information and click “Create”.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F9zOfec9JUmf11rBh182D%2F1.png?alt=media" alt="" width="375">

## Getting Started - Quick Start Guide <a href="#lldeb9ya9ea1" id="lldeb9ya9ea1"></a>

Once done, you will be presented with Neurelo’s quick start guide, which provides a simple step-by-step onboarding process to Neurelo.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FvIw2p2pbJQqhfPSoWwbB%2FQuick%20Start%20for%20New%20Projects.png?alt=media&amp;token=f6acfd6a-e1cb-40dd-95d6-a3c716c3c10b" alt="" width="563"><figcaption></figcaption></figure>

### Connecting a MongoDB Data Source

As we are migrating an existing MongoDB Atlas App Services app, we will use the “Connect a Data Source” option. On clicking the “Connect Data Source” button in there, a “New Data Source” modal opens up.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FeMkTi6iT9n6RPq6Rw5wz%2F3.png?alt=media" alt="" width="375">

To find the “Connection String”, we need to collect MongoDB connection details from the Atlas UI. To do this, start by logging in to Atlas.

Next, go to the Overview page for your project. If your desired project is not active in the UI, choose the appropriate project from the Projects menu in the top-left navigation panel. Select "Databases" from the options in the left navigation panel.

On the "Database Deployments" page, locate the database deployment (cluster) you wish to connect to, then click on the "Connect" button associated with that deployment.

![](https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FppPfe4evCIf5iiO2YAR3%2F4.png?alt=media)

Now, from the Connect page, select "Compass". Copy the connection string from the Compass view as shown:

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fm0w9cKdZy6yFkj3HV7r9%2F5.png?alt=media" alt="" width="375">

{% hint style="success" %}
The connection string is needed in the following format -

*mongodb+srv://\<username>:\<password>@\<cluster-num>.\<cluster-name>.mongodb.net/\<database-name>*

You must replace the username, password, cluster-num, cluster-name and add the database-name in the above string
{% endhint %}

Once done, copy the connection string over to the “New Data Source” modal. If your password has special characters, you can open up "Advanced Settings" and input the password there. Neurelo will encode the password and update the connection string it will use.&#x20;

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FC67Fp15NyIS0osyEY2g1%2F6.png?alt=media" alt="" width="375">

Please select the Neurelo Gateway that is nearest to your MongoDB Atlas instance.&#x20;

{% hint style="danger" %}
You may need to allow Neurelo IPs to connect to your Atlas instance. In which case, please select "Yes" for the "Is your database behind a firewall or a security group?" option and then copy the IPs displayed for your project. Once you have the IPs, please go into MongoDB Atlas’ Network permissions and add them there to allow Neurelo to connect to your instance.&#x20;
{% endhint %}

Make sure to test your connection details with Neurelo’s "Test Connection" button. If all’s good, click on Submit to connect this data source with Neurelo. This will create a new data source for your project. You can always come back to the Data Sources view to verify database details including the health check history.

### Introspection and Schema

Once the data source is added, Neurelo will introspect your schema in the database. To visualize the introspected schema, go back to the quick start guide (navigate back to the Quick Start guide by clicking on "Dashboard" in the left sidebar of your project view) and in the “Build Definitions” section click on your schema name.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FkJ1Fr4Oo6L6w8hzXZPbm%2F7.png?alt=media" alt="" width="480">

This should open up Neurelo’s Visual Schema Builder view, where you can visualize and iterate on the introspected schema. You can refer to this further by reading our documentation on [Neurelo Schema Editor](https://docs.neurelo.com/definitions/neurelo-schema-editor).

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F8OHSstIbItY8JoB2oyKN%2F8.png?alt=media" alt="" width="558">

### Creating an Environment <a href="#hzg3i1t0pnl2" id="hzg3i1t0pnl2"></a>

Now, let us create a Neurelo environment, followed by starting the runners. Think of environments in Neurelo as runtime workspaces that allow you to run your Neurelo GraphQL APIs using a specific version (commit) of your schema definition against a specific data source (in this case, our "Atlas" one).

Neurelo environments are designed to naturally align with typical Software Development Life Cycles (SDLC) as applications are developed, tested, deployed, and operated. Simply put, they help manage different stages of your project, whether it's development, testing, or production. In our scenario, we will create a testing environment.

To do so, navigate back to the Quick Start guide by clicking on "Dashboard" in the left sidebar of your project view and click on the "Create Environment" button. Next, fill in the environment details, which include the commit you’d like your environment to run against, and your gateway preferences. For now, we will select the introspected commit and use the gateway we used when adding our Atlas data source in the earlier step. We have also enabled observability, which will allow us to monitor and analyze the environment's GraphQL API performance.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FIS3ZeeRGTEdgG6tezDww%2F9.png?alt=media" alt="" width="563">

Upon creating an environment, you will see an environment view similar to the following:

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FSvtVZWwlGhQma8puNFDN%2F10.png?alt=media" alt="" width="563">

The APIs tab is generated and automatically updated in sync with your schema. It shows two things: a comprehensive documentation of your auto-generated API endpoints and an API reference for all the API endpoints that Neurelo has created for your schema.

Neurelo supports both REST and GraphQL APIs for your schema. To switch to the GraphQL mode of the APIs tab, click on the GraphQL option on the top.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FQS7sOYPV4PfkKZrzURuU%2F11.png?alt=media" alt="" width="563">

Here is an example of an API reference created for a sample Posts object:

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FwzrObLnSHqO4vDDMimEN%2F12.png?alt=media" alt="" width="563">

Furthermore, Neurelo also creates a GraphQL specification using your schema, which you can download by clicking on the "Specs" option.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FQx8HpdFBkN9WnAGRO3F3%2FGraphQL%20Specs.png?alt=media&amp;token=249fa145-17b5-48e6-a91b-b41af725b0df" alt="" width="252"><figcaption></figcaption></figure>

The APIs tab is also a hub where you can test and explore the provisioned GraphQL APIs using the “API playground”. However, before we explore it further, it is important to start the environment runners and create an API key.

### API Keys and Runners (API Server)

A runner (API server) in Neurelo is the main component that executes and manages all API calls. In Neurelo's Cloud Data API Platform, a runner is a part of every environment inside a project. Runners need to be started for the application to be able to handle GraphQL API requests and process them against the configured data source within an environment.

To do so, click on the "Start Runners" button on the top right of your environment’s view.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FsdyRO3njC09QaErts5Dm%2F14.png?alt=media" alt="" width="563">

Next, to create an authentication token to use with the APIs, navigate to the “API keys” tab. You will be prompted to create a new API key. Make sure to copy and save this key somewhere safely, as we will be using this quite a bit in the following sections.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F2eRMJyZAhvTzxbGgmo18%2F15.png?alt=media" alt="" width="563">

Neurelo also supports fine-grained access control mechanisms. To learn more about it, refer to our documentation on [Access Policies](https://docs.neurelo.com/guides/access-policies).

Well done! Your GraphQL APIs are now ready to be used.&#x20;

## API Playground - Try Neurelo Data APIs

It's time now to experiment with Neurelo's API endpoints. Navigate back to the “APIs” tab and click on the “API playground” button, which should open Neurelo's API playground. Once open, click on the "GraphQL” view on the top-right side of the playground to toggle into the GraphQL mode.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FRAdYTLH4qd4VzgudUnFT%2F16.png?alt=media" alt="" width="563">

To learn more about how to build and test your provisioned GraphQL APIs, check out our comprehensive [Neurelo API Reference docs for GraphQL](https://docs.neurelo.com/neurelo-api-reference-graphql).

Once you have built and tested your GraphQL API, you can then use Neurelo’s “Code Examples” located in the playground itself to easily integrate the API over to the language of your choice.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FnlpBSmZvU8J6Kbom2UpV%2F17.png?alt=media" alt="" width="563">

## Custom API endpoints & SDKs

If you would like to define a rather complex query for some operations on your database, you can leverage Neurelo’s “Custom Queries” feature. These essentially allow you to create Custom GraphQL API endpoints. You can learn more about them in our guide on [Writing and Committing Custom Queries](https://docs.neurelo.com/definitions/custom-apis-for-complex-queries/write-and-commit-custom-queries).

Neurelo also provides a range of SDKs designed to work seamlessly with the APIs generated from your schema. Currently, we offer SDKs for Python, Typescript/Javascript, and Golang. To learn more about their integrations check out our [step-by-step installation guide](https://docs.neurelo.com/sdks) and our [tutorial on its usage](https://docs.neurelo.com/tutorials/building-a-real-time-chat-application-with-neurelo-and-mongodb-using-python#working-with-neurelos-python-sdks-and-building-our-chat-app).

To learn more about how you can get up and running with Neurelo’s GraphQL APIs, check out our sample tutorial on [Building a Restaurant Management System with Neurelo and MongoDB using GraphQL in just a few minutes](https://docs.neurelo.com/tutorials/building-a-restaurant-management-system-with-neurelo-and-mongodb-using-graphql-in-just-a-few-minutes).

## Conclusion

Neurelo lets you build your applications (working with a MongoDB Atlas database) very quickly and easily, all the way from building and extending a schema for your intent, mock data generation, multiple environments with observability, and instant GraphQL APIs with an API Server ready for consumption.

Feel free to try other [examples](https://docs.neurelo.com/tutorials), and check out the many other features of Neurelo which makes it way easier to build your applications with databases.

{% hint style="success" %}
Once you have confirmed that your GraphQL API endpoints are fully migrated and operational with Neurelo, you may proceed to delete your MongoDB Atlas App Services app to prevent incurring unnecessary costs. Please remember that Atlas GraphQL endpoints will no longer be supported starting March 12, 2025.
{% endhint %}

If you need help onboarding with Neurelo, or have questions about Neurelo's GraphQL APIs or any other capabilities, please send an email to <support@neurelo.com> or join Neurelo's Discord server using this [invite link](https://discord.gg/5VRK8vyFmG).&#x20;


# MongoDB Atlas - Migrate REST Data APIs to Neurelo

## Introduction <a href="#b1onq4k9n1bi" id="b1onq4k9n1bi"></a>

Neurelo is a platform designed to simplify the process of working with databases for developers. It offers features such as building and managing schemas with Text-to-Schema support, REST APIs (with SDKs) auto-generated from your schema with documentation and a playground, custom REST API endpoints for complex queries with MQL support, multiple CI/CD environments, schema-aware mock data generation, and more.

This is a guide to help MongoDB Atlas users get started with Neurelo and Neurelo's REST APIs.

For a complete reference on Neurelo's auto-generated REST APIs, check out our[ Neurelo API Reference (REST)](https://docs.neurelo.com/neurelo-api-reference-rest) documentation.

## Video Guide

If you prefer a more visual experience, please check out the video version of this guide.&#x20;

{% embed url="<https://www.loom.com/share/a1fdd8672d0c4c04b8b9b19d12da5987?sid=afe59018-a265-49b9-85bf-df96e4324849>" %}

## Creating a Neurelo Account <a href="#r8kw89115iln" id="r8kw89115iln"></a>

Navigate to[ https://dashboard.neurelo.com/](https://dashboard.neurelo.com/) to access the Neurelo dashboard. Once there, you'll find the option to sign in to your existing account if you already have one, or if you don't have an account, you can create a new Neurelo account using the "**New to Neurelo?**[ **Create an Account**](https://dashboard.neurelo.com/register)" option on the page. A step-by-step guide on[ how to create an account](https://docs.neurelo.com/getting-started/sign-in-sign-up) can be found in Neurelo’s documentation.

## Creating a Neurelo project <a href="#g44z2h2ij83g" id="g44z2h2ij83g"></a>

Projects are applications that developers build and run with Neurelo. This is the primary “working” entity where all things start inside Neurelo. A project exists inside an Organization and has its own set of entities such as data definitions, environments, dashboards, data sources, etc.

After signing in to your Neurelo account, you will be directed to your Neurelo Dashboard. This is your central hub for managing your projects.

If you have a new account, you will see the option to create a new project as one of the first things you need to do to get started. If you already have another project in your account, look for an orange button on the top-right of the Dashboard with a + icon and the word "New" inside it. This button is designed for creating new projects.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FrZ8A0kyvpnR1IoooVT9G%2F0.png?alt=media" alt="" width="375">

Clicking on it will open the “New Project” modal. Enter the project information and click “Create”.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F2uiU0HcJF5d1s3iFy6ER%2FNew%20Project%20-%20Rest%20Data%20APIs.png?alt=media&amp;token=33cd1eea-8f61-46cf-b64c-8c3df1a79f3d" alt="" width="375">

## Getting Started - Quick Start Guide <a href="#mi5bwlzc0z43" id="mi5bwlzc0z43"></a>

Once done, you will be presented with Neurelo’s quick start guide, which provides a simple step-by-step onboarding process to Neurelo.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F7Mm8OaQHPAVJJULtB3vW%2F2.png?alt=media" alt="" width="563">

### Connecting a MongoDB Data Source <a href="#uvr90odok7ms" id="uvr90odok7ms"></a>

As we are migrating an existing MongoDB Atlas App Services app, we will use the “Connect a Data Source” option. On clicking the “Connect Data Source” button there, a “New Data Source” modal opens up.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FTfg5C4wZEXM9Z59WtWU2%2F3.png?alt=media" alt="" width="375">

To find the “Connection String”, we need to collect MongoDB connection details from the Atlas UI. To do this, start by logging in to Atlas.

Next, go to the Overview page for your project. If your desired project is not active in the UI, choose the appropriate project from the Projects menu in the top-left navigation panel. Select "Databases" from the options in the left navigation panel.

On the "Database Deployments" page, locate the database deployment (cluster) you wish to connect to, then click on the "Connect" button associated with that deployment.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FyfTpnSR5eo5uPUpC1f1D%2F4.png?alt=media" alt="" width="563">

Now, from the Connect page, select "Compass". Copy the connection string from the Compass view as shown:

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FTYYWgYUw6KTdjYNrNuqQ%2F5.png?alt=media" alt="" width="375">

{% hint style="success" %}
The connection string is needed in the following format -

*mongodb+srv://\<username>:\<password>@\<cluster-num>.\<cluster-name>.mongodb.net/\<database-name>*&#x20;

You must replace the username, password, cluster-num, cluster-name and add the database-name in the above string
{% endhint %}

Once done, copy the connection string over to the “New Data Source” modal. If your password has special characters, you can open up "Advanced Settings" and input the password there. Neurelo will encode the password and update the connection string it will use.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FX4dR4R44nfEtkPIkHUwY%2F6.png?alt=media" alt="" width="375">

Please select the Neurelo Gateway that is nearest to your MongoDB Atlas instance.

{% hint style="danger" %}
You may need to allow Neurelo IPs to connect to your Atlas instance. In which case, please select "Yes" for the "Is your database behind a firewall or a security group?" option and then copy the IPs displayed for your project. Once you have the IPs, please go into MongoDB Atlas’ Network permissions and add them there to allow Neurelo to connect to your instance.
{% endhint %}

Make sure to test your connection details with Neurelo’s "Test Connection" button. If all’s good, click on Submit to connect this data source with Neurelo. This will create a new data source for your project. You can always come back to the Data Sources view to verify database details including the health check history.

### Introspection and Schema <a href="#rzxc21ujnhkc" id="rzxc21ujnhkc"></a>

Once the data source is added, Neurelo will introspect your schema in the database. To visualize the introspected schema, go back to the quick start guide (navigate back to the Quick Start guide by clicking on "Dashboard" in the left sidebar of your project view) and in the “Build Definitions” section click on your schema name.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FBMHPPRA4OVInNbsEC26L%2F7.png?alt=media" alt="" width="320">

This should open up Neurelo’s Visual Schema Builder view, where you can visualize and iterate on the introspected schema. You can refer to this further by reading our documentation on[ Neurelo Schema Editor](https://docs.neurelo.com/definitions/neurelo-schema-editor).

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F2V8MEKnBciRhGmsUsknn%2F8.png?alt=media" alt="" width="558">

### Creating an Environment <a href="#b4239fcrg0a7" id="b4239fcrg0a7"></a>

Now, let us create a Neurelo environment, followed by starting the runners. Think of environments in Neurelo as runtime workspaces that allow you to run your Neurelo REST APIs using a specific version (commit) of your schema definition against a specific data source (in this case, our "Atlas" one).

Neurelo environments are designed to naturally align with typical Software Development Life Cycles (SDLC) as applications are developed, tested, deployed, and operated. Simply put, they help manage different stages of your project, whether it's development, testing, or production. In our scenario, we will create a testing environment.

To do so, navigate back to the Quick Start guide by clicking on "Dashboard" in the left sidebar of your project view and click on the "Create Environment" button. Next, fill in the environment details, which include the commit you’d like your environment to run against, and your gateway preferences. For now, we will select the introspected commit and use the gateway we used when adding our Atlas data source in the earlier step. We have also enabled observability, which will allow us to monitor and analyze the environment's REST API performance.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FWDHHtL0doN0kc6umhK0u%2F9.png?alt=media" alt="" width="563">

Upon creating an environment, you will see an environment view similar to the following:

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FZ1n2SOs9uhZEIYkDIIKO%2F10.png?alt=media" alt="" width="563">

The APIs tab is generated and automatically updated in sync with your schema. It shows two things: a comprehensive documentation of your auto-generated API endpoints and an API reference for all the API endpoints that Neurelo has created for your schema.

Neurelo supports both REST and GraphQL APIs for your schema. By default, the REST mode is selected in the APIs tab.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fg829xq6umYWTwLAvftRa%2F11.png?alt=media" alt="" width="375">

Here is an example of an API reference created for a sample Posts object:

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FWe8w6Vpu9vutErwl4fOt%2F12.png?alt=media" alt="" width="563">

Furthermore, Neurelo also creates an OpenAPI specification using your schema, which you can download by clicking on the "Specs" option.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FGLTnLJeNeZwILcgGMvqq%2F13.png?alt=media" alt="" width="375">

The APIs tab is also a hub where you can test and explore the provisioned REST APIs using the “API playground”. However, before we explore it further, it is important to start the environment runners and create an API key.

### API Keys and Runners (API Server) <a href="#eynfxgc37078" id="eynfxgc37078"></a>

A runner (API server) in Neurelo is the main component that executes and manages all API calls. In Neurelo's Cloud Data API Platform, a runner is a part of every environment inside a project. Runners need to be started for the application to be able to handle REST API requests and process them against the configured data source within an environment.

To do so, click on the "Start Runners" button on the top right of your environment’s view.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FycJw8ltUZKPv4HHqyF7D%2F14.png?alt=media" alt="" width="563">

Next, to create an authentication token to use with the APIs, navigate to the “API keys” tab. You will be prompted to create a new API key. Make sure to copy and save this key somewhere safely, as we will be using this quite a bit in the following sections.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FWp1rFGy0XsGf3777mj30%2F15.png?alt=media" alt="" width="563">

Neurelo also supports fine-grained access control mechanisms. To learn more about it, refer to our documentation on[ Access Policies](https://docs.neurelo.com/guides/access-policies).

Well done! Your REST APIs are now ready to be used.

## API Playground - Try Neurelo Data APIs <a href="#nxiuxa8sc12p" id="nxiuxa8sc12p"></a>

It's time now to experiment with Neurelo's API endpoints. Navigate back to the “APIs” tab and click on the “API playground” button, which should open Neurelo's REST API playground.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fk9b65eRFPDWy43lZlXMH%2F16.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

To learn more about how to build and test your provisioned REST APIs, check out our comprehensive [Neurelo API Reference docs for REST](https://docs.neurelo.com/neurelo-api-reference-rest).

Once you have built and tested your REST APIs, you can then use Neurelo’s “Code Examples” located in the playground itself to easily integrate the API over to the language of your choice.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fq7gxE6d0wXrQDShBK4WA%2F17.png?alt=media" alt="" width="563">

Neurelo’s API Playground also offers a schema-aware AI Assist feature to help you quickly build and iterate over your APIs.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FHEu8curGnXXWgGJ8cEWR%2F18.png?alt=media" alt="" width="563">

## Custom API endpoints & SDKs <a href="#fl5lkc6tqvfl" id="fl5lkc6tqvfl"></a>

If you would like to define a rather complex query for some operations on your database, you can leverage Neurelo’s “Custom Queries” feature. These essentially allow you to create Custom REST API endpoints. You can learn more about them in our guide on[ Writing and Committing Custom Queries](https://docs.neurelo.com/definitions/custom-apis-for-complex-queries/write-and-commit-custom-queries).

Neurelo also provides a range of SDKs designed to work seamlessly with the APIs generated from your schema. Currently, we offer SDKs for Python, Typescript/Javascript, and Golang. To learn more about their integrations check out our[ step-by-step installation guide](https://docs.neurelo.com/sdks) and our[ tutorial on its usage](https://docs.neurelo.com/tutorials/building-a-real-time-chat-application-with-neurelo-and-mongodb-using-python#working-with-neurelos-python-sdks-and-building-our-chat-app).

To learn more about how you can get up and running with Neurelo’s REST APIs, check out our sample tutorial on [Building a Real Time Chat Application with Neurelo and MongoDB using Python](https://docs.neurelo.com/tutorials/building-a-real-time-chat-application-with-neurelo-and-mongodb-using-python).

## Conclusion <a href="#m3in2chx4cz6" id="m3in2chx4cz6"></a>

Neurelo lets you build your applications (working with a MongoDB Atlas database) very quickly and easily, all the way from building and extending a schema for your intent, mock data generation, multiple environments with observability, and instant REST APIs with an API Server ready for consumption.

Feel free to try other[ examples](https://docs.neurelo.com/tutorials), and check out the many other features of Neurelo which makes it way easier to build your applications with databases.

If you need help onboarding with Neurelo, or have questions about Neurelo's REST APIs or any other capabilities, please send an email to <support@neurelo.com> or join Neurelo's Discord server using this [invite link](https://discord.gg/5VRK8vyFmG).


# MongoDB Atlas - Migrate REST Data APIs to Neurelo

## Introduction <a href="#b1onq4k9n1bi" id="b1onq4k9n1bi"></a>

Neurelo is a platform designed to simplify the process of working with databases for developers. It offers features such as building and managing schemas with Text-to-Schema support, REST APIs (with SDKs) auto-generated from your schema with documentation and a playground, custom REST API endpoints for complex queries with MQL support, multiple CI/CD environments, schema-aware mock data generation, and more.

This is a guide to help MongoDB Atlas users get started with Neurelo and Neurelo's REST APIs.

For a complete reference on Neurelo's auto-generated REST APIs, check out our[ Neurelo API Reference (REST)](https://docs.neurelo.com/neurelo-api-reference-rest) documentation.

## Video Guide

If you prefer a more visual experience, please check out the video version of this guide.&#x20;

{% embed url="<https://www.loom.com/share/a1fdd8672d0c4c04b8b9b19d12da5987?sid=afe59018-a265-49b9-85bf-df96e4324849>" %}

## Creating a Neurelo Account <a href="#r8kw89115iln" id="r8kw89115iln"></a>

Navigate to[ https://dashboard.neurelo.com/](https://dashboard.neurelo.com/) to access the Neurelo dashboard. Once there, you'll find the option to sign in to your existing account if you already have one, or if you don't have an account, you can create a new Neurelo account using the "**New to Neurelo?**[ **Create an Account**](https://dashboard.neurelo.com/register)" option on the page. A step-by-step guide on[ how to create an account](https://docs.neurelo.com/getting-started/sign-in-sign-up) can be found in Neurelo’s documentation.

## Creating a Neurelo project <a href="#g44z2h2ij83g" id="g44z2h2ij83g"></a>

Projects are applications that developers build and run with Neurelo. This is the primary “working” entity where all things start inside Neurelo. A project exists inside an Organization and has its own set of entities such as data definitions, environments, dashboards, data sources, etc.

After signing in to your Neurelo account, you will be directed to your Neurelo Dashboard. This is your central hub for managing your projects.

If you have a new account, you will see the option to create a new project as one of the first things you need to do to get started. If you already have another project in your account, look for an orange button on the top-right of the Dashboard with a + icon and the word "New" inside it. This button is designed for creating new projects.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FrZ8A0kyvpnR1IoooVT9G%2F0.png?alt=media" alt="" width="375">

Clicking on it will open the “New Project” modal. Enter the project information and click “Create”.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F2uiU0HcJF5d1s3iFy6ER%2FNew%20Project%20-%20Rest%20Data%20APIs.png?alt=media&amp;token=33cd1eea-8f61-46cf-b64c-8c3df1a79f3d" alt="" width="375">

## Getting Started - Quick Start Guide <a href="#mi5bwlzc0z43" id="mi5bwlzc0z43"></a>

Once done, you will be presented with Neurelo’s quick start guide, which provides a simple step-by-step onboarding process to Neurelo.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F7Mm8OaQHPAVJJULtB3vW%2F2.png?alt=media" alt="" width="563">

### Connecting a MongoDB Data Source <a href="#uvr90odok7ms" id="uvr90odok7ms"></a>

As we are migrating an existing MongoDB Atlas App Services app, we will use the “Connect a Data Source” option. On clicking the “Connect Data Source” button there, a “New Data Source” modal opens up.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FTfg5C4wZEXM9Z59WtWU2%2F3.png?alt=media" alt="" width="375">

To find the “Connection String”, we need to collect MongoDB connection details from the Atlas UI. To do this, start by logging in to Atlas.

Next, go to the Overview page for your project. If your desired project is not active in the UI, choose the appropriate project from the Projects menu in the top-left navigation panel. Select "Databases" from the options in the left navigation panel.

On the "Database Deployments" page, locate the database deployment (cluster) you wish to connect to, then click on the "Connect" button associated with that deployment.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FyfTpnSR5eo5uPUpC1f1D%2F4.png?alt=media" alt="" width="563">

Now, from the Connect page, select "Compass". Copy the connection string from the Compass view as shown:

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FTYYWgYUw6KTdjYNrNuqQ%2F5.png?alt=media" alt="" width="375">

{% hint style="success" %}
The connection string is needed in the following format -

*mongodb+srv://\<username>:\<password>@\<cluster-num>.\<cluster-name>.mongodb.net/\<database-name>*&#x20;

You must replace the username, password, cluster-num, cluster-name and add the database-name in the above string
{% endhint %}

Once done, copy the connection string over to the “New Data Source” modal. If your password has special characters, you can open up "Advanced Settings" and input the password there. Neurelo will encode the password and update the connection string it will use.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FX4dR4R44nfEtkPIkHUwY%2F6.png?alt=media" alt="" width="375">

Please select the Neurelo Gateway that is nearest to your MongoDB Atlas instance.

{% hint style="danger" %}
You may need to allow Neurelo IPs to connect to your Atlas instance. In which case, please select "Yes" for the "Is your database behind a firewall or a security group?" option and then copy the IPs displayed for your project. Once you have the IPs, please go into MongoDB Atlas’ Network permissions and add them there to allow Neurelo to connect to your instance.
{% endhint %}

Make sure to test your connection details with Neurelo’s "Test Connection" button. If all’s good, click on Submit to connect this data source with Neurelo. This will create a new data source for your project. You can always come back to the Data Sources view to verify database details including the health check history.

### Introspection and Schema <a href="#rzxc21ujnhkc" id="rzxc21ujnhkc"></a>

Once the data source is added, Neurelo will introspect your schema in the database. To visualize the introspected schema, go back to the quick start guide (navigate back to the Quick Start guide by clicking on "Dashboard" in the left sidebar of your project view) and in the “Build Definitions” section click on your schema name.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FBMHPPRA4OVInNbsEC26L%2F7.png?alt=media" alt="" width="320">

This should open up Neurelo’s Visual Schema Builder view, where you can visualize and iterate on the introspected schema. You can refer to this further by reading our documentation on[ Neurelo Schema Editor](https://docs.neurelo.com/definitions/neurelo-schema-editor).

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F2V8MEKnBciRhGmsUsknn%2F8.png?alt=media" alt="" width="558">

### Creating an Environment <a href="#b4239fcrg0a7" id="b4239fcrg0a7"></a>

Now, let us create a Neurelo environment, followed by starting the runners. Think of environments in Neurelo as runtime workspaces that allow you to run your Neurelo REST APIs using a specific version (commit) of your schema definition against a specific data source (in this case, our "Atlas" one).

Neurelo environments are designed to naturally align with typical Software Development Life Cycles (SDLC) as applications are developed, tested, deployed, and operated. Simply put, they help manage different stages of your project, whether it's development, testing, or production. In our scenario, we will create a testing environment.

To do so, navigate back to the Quick Start guide by clicking on "Dashboard" in the left sidebar of your project view and click on the "Create Environment" button. Next, fill in the environment details, which include the commit you’d like your environment to run against, and your gateway preferences. For now, we will select the introspected commit and use the gateway we used when adding our Atlas data source in the earlier step. We have also enabled observability, which will allow us to monitor and analyze the environment's REST API performance.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FWDHHtL0doN0kc6umhK0u%2F9.png?alt=media" alt="" width="563">

Upon creating an environment, you will see an environment view similar to the following:

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FZ1n2SOs9uhZEIYkDIIKO%2F10.png?alt=media" alt="" width="563">

The APIs tab is generated and automatically updated in sync with your schema. It shows two things: a comprehensive documentation of your auto-generated API endpoints and an API reference for all the API endpoints that Neurelo has created for your schema.

Neurelo supports both REST and GraphQL APIs for your schema. By default, the REST mode is selected in the APIs tab.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fg829xq6umYWTwLAvftRa%2F11.png?alt=media" alt="" width="375">

Here is an example of an API reference created for a sample Posts object:

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FWe8w6Vpu9vutErwl4fOt%2F12.png?alt=media" alt="" width="563">

Furthermore, Neurelo also creates an OpenAPI specification using your schema, which you can download by clicking on the "Specs" option.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FGLTnLJeNeZwILcgGMvqq%2F13.png?alt=media" alt="" width="375">

The APIs tab is also a hub where you can test and explore the provisioned REST APIs using the “API playground”. However, before we explore it further, it is important to start the environment runners and create an API key.

### API Keys and Runners (API Server) <a href="#eynfxgc37078" id="eynfxgc37078"></a>

A runner (API server) in Neurelo is the main component that executes and manages all API calls. In Neurelo's Cloud Data API Platform, a runner is a part of every environment inside a project. Runners need to be started for the application to be able to handle REST API requests and process them against the configured data source within an environment.

To do so, click on the "Start Runners" button on the top right of your environment’s view.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FycJw8ltUZKPv4HHqyF7D%2F14.png?alt=media" alt="" width="563">

Next, to create an authentication token to use with the APIs, navigate to the “API keys” tab. You will be prompted to create a new API key. Make sure to copy and save this key somewhere safely, as we will be using this quite a bit in the following sections.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FWp1rFGy0XsGf3777mj30%2F15.png?alt=media" alt="" width="563">

Neurelo also supports fine-grained access control mechanisms. To learn more about it, refer to our documentation on[ Access Policies](https://docs.neurelo.com/guides/access-policies).

Well done! Your REST APIs are now ready to be used.

## API Playground - Try Neurelo Data APIs <a href="#nxiuxa8sc12p" id="nxiuxa8sc12p"></a>

It's time now to experiment with Neurelo's API endpoints. Navigate back to the “APIs” tab and click on the “API playground” button, which should open Neurelo's REST API playground.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fk9b65eRFPDWy43lZlXMH%2F16.png?alt=media" alt="" width="563"><figcaption></figcaption></figure>

To learn more about how to build and test your provisioned REST APIs, check out our comprehensive [Neurelo API Reference docs for REST](https://docs.neurelo.com/neurelo-api-reference-rest).

Once you have built and tested your REST APIs, you can then use Neurelo’s “Code Examples” located in the playground itself to easily integrate the API over to the language of your choice.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fq7gxE6d0wXrQDShBK4WA%2F17.png?alt=media" alt="" width="563">

Neurelo’s API Playground also offers a schema-aware AI Assist feature to help you quickly build and iterate over your APIs.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FHEu8curGnXXWgGJ8cEWR%2F18.png?alt=media" alt="" width="563">

## Custom API endpoints & SDKs <a href="#fl5lkc6tqvfl" id="fl5lkc6tqvfl"></a>

If you would like to define a rather complex query for some operations on your database, you can leverage Neurelo’s “Custom Queries” feature. These essentially allow you to create Custom REST API endpoints. You can learn more about them in our guide on[ Writing and Committing Custom Queries](https://docs.neurelo.com/definitions/custom-apis-for-complex-queries/write-and-commit-custom-queries).

Neurelo also provides a range of SDKs designed to work seamlessly with the APIs generated from your schema. Currently, we offer SDKs for Python, Typescript/Javascript, and Golang. To learn more about their integrations check out our[ step-by-step installation guide](https://docs.neurelo.com/sdks) and our[ tutorial on its usage](https://docs.neurelo.com/tutorials/building-a-real-time-chat-application-with-neurelo-and-mongodb-using-python#working-with-neurelos-python-sdks-and-building-our-chat-app).

To learn more about how you can get up and running with Neurelo’s REST APIs, check out our sample tutorial on [Building a Real Time Chat Application with Neurelo and MongoDB using Python](https://docs.neurelo.com/tutorials/building-a-real-time-chat-application-with-neurelo-and-mongodb-using-python).

## Conclusion <a href="#m3in2chx4cz6" id="m3in2chx4cz6"></a>

Neurelo lets you build your applications (working with a MongoDB Atlas database) very quickly and easily, all the way from building and extending a schema for your intent, mock data generation, multiple environments with observability, and instant REST APIs with an API Server ready for consumption.

Feel free to try other[ examples](https://docs.neurelo.com/tutorials), and check out the many other features of Neurelo which makes it way easier to build your applications with databases.

If you need help onboarding with Neurelo, or have questions about Neurelo's REST APIs or any other capabilities, please send an email to <support@neurelo.com> or join Neurelo's Discord server using this [invite link](https://discord.gg/5VRK8vyFmG).


# MongoDB Atlas - Migrate GraphQL APIs to Neurelo

## Introduction

Neurelo is a platform designed to simplify the process of working with databases for developers. It offers features such as building and managing schemas with Text-to-Schema support, GraphQL APIs (with SDKs) auto-generated from your schema with documentation and a playground, custom GraphQL API endpoints for complex queries with MQL support, multiple CI/CD environments, schema-aware mock data generation, and more.

This is a guide to help MongoDB Atlas users get started with Neurelo and Neurelo's GraphQL APIs.

For a complete reference on Neurelo's auto-generated GraphQL APIs, check out our [Neurelo API Reference (GraphQL)](https://docs.neurelo.com/neurelo-api-reference-graphql) documentation.

## Video Guide

If you prefer a more visual experience, please check out the video version of this guide.&#x20;

{% embed url="<https://www.loom.com/share/193d85ea169846ec94ea30e3c1f29fb9?sid=f262d1fa-326b-4d8c-ad03-bf4b327b735b>" %}

## Creating a Neurelo Account <a href="#b1puftb7rbol" id="b1puftb7rbol"></a>

Navigate to[ https://dashboard.neurelo.com/](https://dashboard.neurelo.com/) to access the Neurelo dashboard. Once there, you'll find the option to sign in to your existing account if you already have one, or if you don't have an account, you can create a new Neurelo account using the "**New to Neurelo?**[ **Create an Account**](https://dashboard.neurelo.com/register)" option on the page. A step-by-step guide on [how to create an account](https://docs.neurelo.com/getting-started/sign-in-sign-up) can be found in Neurelo’s documentation.

## Creating a Neurelo project <a href="#ttrcqwqat7or" id="ttrcqwqat7or"></a>

Projects are applications that developers build and run with Neurelo. This is the primary “working” entity where all things start inside Neurelo. A project exists inside an Organization and has its own set of entities such as data definitions, environments, dashboards, data sources, etc.

After signing in to your Neurelo account, you will be directed to your Neurelo Dashboard. This is your central hub for managing your projects.

If you have a new account, you will see the option to create a new project as one of the first things you need to do to get stated. If you already have another project in your account, look for an orange button on the top-right of the Dashboard with a + icon and the word "New" inside it. This button is designed for creating new projects.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F3cGwxYtVJE8Tw60RhlSC%2F0.png?alt=media" alt="" width="375">

Clicking on it will open the “New Project” modal. Enter the project information and click “Create”.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F9zOfec9JUmf11rBh182D%2F1.png?alt=media" alt="" width="375">

## Getting Started - Quick Start Guide <a href="#lldeb9ya9ea1" id="lldeb9ya9ea1"></a>

Once done, you will be presented with Neurelo’s quick start guide, which provides a simple step-by-step onboarding process to Neurelo.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FvIw2p2pbJQqhfPSoWwbB%2FQuick%20Start%20for%20New%20Projects.png?alt=media&amp;token=f6acfd6a-e1cb-40dd-95d6-a3c716c3c10b" alt="" width="563"><figcaption></figcaption></figure>

### Connecting a MongoDB Data Source

As we are migrating an existing MongoDB Atlas App Services app, we will use the “Connect a Data Source” option. On clicking the “Connect Data Source” button in there, a “New Data Source” modal opens up.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FeMkTi6iT9n6RPq6Rw5wz%2F3.png?alt=media" alt="" width="375">

To find the “Connection String”, we need to collect MongoDB connection details from the Atlas UI. To do this, start by logging in to Atlas.

Next, go to the Overview page for your project. If your desired project is not active in the UI, choose the appropriate project from the Projects menu in the top-left navigation panel. Select "Databases" from the options in the left navigation panel.

On the "Database Deployments" page, locate the database deployment (cluster) you wish to connect to, then click on the "Connect" button associated with that deployment.

![](https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FppPfe4evCIf5iiO2YAR3%2F4.png?alt=media)

Now, from the Connect page, select "Compass". Copy the connection string from the Compass view as shown:

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2Fm0w9cKdZy6yFkj3HV7r9%2F5.png?alt=media" alt="" width="375">

{% hint style="success" %}
The connection string is needed in the following format -

*mongodb+srv://\<username>:\<password>@\<cluster-num>.\<cluster-name>.mongodb.net/\<database-name>*

You must replace the username, password, cluster-num, cluster-name and add the database-name in the above string
{% endhint %}

Once done, copy the connection string over to the “New Data Source” modal. If your password has special characters, you can open up "Advanced Settings" and input the password there. Neurelo will encode the password and update the connection string it will use.&#x20;

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FC67Fp15NyIS0osyEY2g1%2F6.png?alt=media" alt="" width="375">

Please select the Neurelo Gateway that is nearest to your MongoDB Atlas instance.&#x20;

{% hint style="danger" %}
You may need to allow Neurelo IPs to connect to your Atlas instance. In which case, please select "Yes" for the "Is your database behind a firewall or a security group?" option and then copy the IPs displayed for your project. Once you have the IPs, please go into MongoDB Atlas’ Network permissions and add them there to allow Neurelo to connect to your instance.&#x20;
{% endhint %}

Make sure to test your connection details with Neurelo’s "Test Connection" button. If all’s good, click on Submit to connect this data source with Neurelo. This will create a new data source for your project. You can always come back to the Data Sources view to verify database details including the health check history.

### Introspection and Schema

Once the data source is added, Neurelo will introspect your schema in the database. To visualize the introspected schema, go back to the quick start guide (navigate back to the Quick Start guide by clicking on "Dashboard" in the left sidebar of your project view) and in the “Build Definitions” section click on your schema name.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FkJ1Fr4Oo6L6w8hzXZPbm%2F7.png?alt=media" alt="" width="480">

This should open up Neurelo’s Visual Schema Builder view, where you can visualize and iterate on the introspected schema. You can refer to this further by reading our documentation on [Neurelo Schema Editor](https://docs.neurelo.com/definitions/neurelo-schema-editor).

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F8OHSstIbItY8JoB2oyKN%2F8.png?alt=media" alt="" width="558">

### Creating an Environment <a href="#hzg3i1t0pnl2" id="hzg3i1t0pnl2"></a>

Now, let us create a Neurelo environment, followed by starting the runners. Think of environments in Neurelo as runtime workspaces that allow you to run your Neurelo GraphQL APIs using a specific version (commit) of your schema definition against a specific data source (in this case, our "Atlas" one).

Neurelo environments are designed to naturally align with typical Software Development Life Cycles (SDLC) as applications are developed, tested, deployed, and operated. Simply put, they help manage different stages of your project, whether it's development, testing, or production. In our scenario, we will create a testing environment.

To do so, navigate back to the Quick Start guide by clicking on "Dashboard" in the left sidebar of your project view and click on the "Create Environment" button. Next, fill in the environment details, which include the commit you’d like your environment to run against, and your gateway preferences. For now, we will select the introspected commit and use the gateway we used when adding our Atlas data source in the earlier step. We have also enabled observability, which will allow us to monitor and analyze the environment's GraphQL API performance.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FIS3ZeeRGTEdgG6tezDww%2F9.png?alt=media" alt="" width="563">

Upon creating an environment, you will see an environment view similar to the following:

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FSvtVZWwlGhQma8puNFDN%2F10.png?alt=media" alt="" width="563">

The APIs tab is generated and automatically updated in sync with your schema. It shows two things: a comprehensive documentation of your auto-generated API endpoints and an API reference for all the API endpoints that Neurelo has created for your schema.

Neurelo supports both REST and GraphQL APIs for your schema. To switch to the GraphQL mode of the APIs tab, click on the GraphQL option on the top.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FQS7sOYPV4PfkKZrzURuU%2F11.png?alt=media" alt="" width="563">

Here is an example of an API reference created for a sample Posts object:

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FwzrObLnSHqO4vDDMimEN%2F12.png?alt=media" alt="" width="563">

Furthermore, Neurelo also creates a GraphQL specification using your schema, which you can download by clicking on the "Specs" option.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FQx8HpdFBkN9WnAGRO3F3%2FGraphQL%20Specs.png?alt=media&amp;token=249fa145-17b5-48e6-a91b-b41af725b0df" alt="" width="252"><figcaption></figcaption></figure>

The APIs tab is also a hub where you can test and explore the provisioned GraphQL APIs using the “API playground”. However, before we explore it further, it is important to start the environment runners and create an API key.

### API Keys and Runners (API Server)

A runner (API server) in Neurelo is the main component that executes and manages all API calls. In Neurelo's Cloud Data API Platform, a runner is a part of every environment inside a project. Runners need to be started for the application to be able to handle GraphQL API requests and process them against the configured data source within an environment.

To do so, click on the "Start Runners" button on the top right of your environment’s view.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FsdyRO3njC09QaErts5Dm%2F14.png?alt=media" alt="" width="563">

Next, to create an authentication token to use with the APIs, navigate to the “API keys” tab. You will be prompted to create a new API key. Make sure to copy and save this key somewhere safely, as we will be using this quite a bit in the following sections.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F2eRMJyZAhvTzxbGgmo18%2F15.png?alt=media" alt="" width="563">

Neurelo also supports fine-grained access control mechanisms. To learn more about it, refer to our documentation on [Access Policies](https://docs.neurelo.com/guides/access-policies).

Well done! Your GraphQL APIs are now ready to be used.&#x20;

## API Playground - Try Neurelo Data APIs

It's time now to experiment with Neurelo's API endpoints. Navigate back to the “APIs” tab and click on the “API playground” button, which should open Neurelo's API playground. Once open, click on the "GraphQL” view on the top-right side of the playground to toggle into the GraphQL mode.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FRAdYTLH4qd4VzgudUnFT%2F16.png?alt=media" alt="" width="563">

To learn more about how to build and test your provisioned GraphQL APIs, check out our comprehensive [Neurelo API Reference docs for GraphQL](https://docs.neurelo.com/neurelo-api-reference-graphql).

Once you have built and tested your GraphQL API, you can then use Neurelo’s “Code Examples” located in the playground itself to easily integrate the API over to the language of your choice.

<img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FnlpBSmZvU8J6Kbom2UpV%2F17.png?alt=media" alt="" width="563">

## Custom API endpoints & SDKs

If you would like to define a rather complex query for some operations on your database, you can leverage Neurelo’s “Custom Queries” feature. These essentially allow you to create Custom GraphQL API endpoints. You can learn more about them in our guide on [Writing and Committing Custom Queries](https://docs.neurelo.com/definitions/custom-apis-for-complex-queries/write-and-commit-custom-queries).

Neurelo also provides a range of SDKs designed to work seamlessly with the APIs generated from your schema. Currently, we offer SDKs for Python, Typescript/Javascript, and Golang. To learn more about their integrations check out our [step-by-step installation guide](https://docs.neurelo.com/sdks) and our [tutorial on its usage](https://docs.neurelo.com/tutorials/building-a-real-time-chat-application-with-neurelo-and-mongodb-using-python#working-with-neurelos-python-sdks-and-building-our-chat-app).

To learn more about how you can get up and running with Neurelo’s GraphQL APIs, check out our sample tutorial on [Building a Restaurant Management System with Neurelo and MongoDB using GraphQL in just a few minutes](https://docs.neurelo.com/tutorials/building-a-restaurant-management-system-with-neurelo-and-mongodb-using-graphql-in-just-a-few-minutes).

## Conclusion

Neurelo lets you build your applications (working with a MongoDB Atlas database) very quickly and easily, all the way from building and extending a schema for your intent, mock data generation, multiple environments with observability, and instant GraphQL APIs with an API Server ready for consumption.

Feel free to try other [examples](https://docs.neurelo.com/tutorials), and check out the many other features of Neurelo which makes it way easier to build your applications with databases.

{% hint style="success" %}
Once you have confirmed that your GraphQL API endpoints are fully migrated and operational with Neurelo, you may proceed to delete your MongoDB Atlas App Services app to prevent incurring unnecessary costs. Please remember that Atlas GraphQL endpoints will no longer be supported starting March 12, 2025.
{% endhint %}

If you need help onboarding with Neurelo, or have questions about Neurelo's GraphQL APIs or any other capabilities, please send an email to <support@neurelo.com> or join Neurelo's Discord server using this [invite link](https://discord.gg/5VRK8vyFmG).&#x20;


# Neurelo Schema Language (NSL)

## Introduction

The Neurelo Schema Language (NSL) is used to define entities, attributes, relationships, and constraints of a system. The language is based on the [json-schema](https://json-schema.org/) spec, with added capabilities to accurately describe the relationships and constraints within the schema.

## Concepts

* **Object** - An object represents an entity in your data source. Each object consists of a name, a collection of properties, and constraints. Each object maps to a *table* (e.g. in PostgreSQL or MySQL) or a *collection* (e.g. in MongoDB) in your data source.
* **Properties** - A property represents the fields of an object in your data source e.g. a column in a *table* (e.g. PostgreSQL or MySQL) or a *key* in a key:value pair (e.g. in MongoDB). The property definition indicates how a value should be formed and validated, how it maps to the data source object (table or collection) and, optionally, if it represents a relationship to another object.
* **Enum** - An enum is a list of named values that can be used to limit the values that can be assigned to a property.
* **Constraints** - A constraint represents additional definitions or rules that should be applied to an object, like a multi-property index.
* **Functions** - A function can be used when assigning default values to an object’s property e.g. instead of having a hard-coded value, you can rely on your data source capabilities to generate a value for each record.
* **Relationships** - A relationship defines how objects interact between them. They are defined on a per-property basis and specify information such as the cardinality of the relation.
* **Inner Object** - An inner object is used to define a custom property schema, and can be reused across multiple objects, or even to define properties of other inner objects. Inner objects are not mapped to a table or collection. Currently they are only supported when using MongoDB (embedded documents).

## Top Level

The top level of a Neurelo Schema has the following format:

```json
{
  "features": {...},
  "objects": {...},
  "innerObjects": {...},
  "enums": {...}
}
```

`objects` must be specified in the top level, however, `features`, `enums` and `innerObjects` are optional.

## <mark style="color:purple;">Objects</mark>

Each object is represented by a name and a set of properties:

```json
{
  "objects": {
    "movies": {
      "properties": {
        "id": {
          "type": "integer",
          "identifier": true
        },
        "name": {
          "type": "string"
        }
      }
    }
  }
}
```

Optionally, it can include a “sourceName” attribute, that indicates how an object is named in the data source:

```json
{
  "objects": {
    "movies": {
      "sourceName": "films",
      "properties": {...}
    }
  }
}
```

And also an optional attribute “constraints” to indicate any extra indexes this entity may have in the data source:

```json
{
  "objects": {
    "movies": {
      "sourceName": "films",
      "properties": {...},
      "constraints": [
        {
          "type": "identifier",
          "property": [
            "id",
            "name"
          ]
        }
      ]
    }
  }
}
```

The above example would create an index using multiple properties - `id` and `name`.

## <mark style="color:purple;">Enums</mark>

Each enum is represented by a name and a list of string values. Enums can be used to constrain the possible values for a property in a reusable way:

```json
{
  "enums": {
    "Rating": [
      "G",
      "PG",
      "PG-13",
      "R"
    ]
  }
}
```

## <mark style="color:purple;">Properties</mark>

Properties define the values contained in an object e.g. in a column in a *table* (e.g. PostgreSQL or MySQL) or a *key* in a key:value pair (e.g. in MongoDB). Each property is defined by multiple **attributes**. These attributes define how the values for the property should be formed and how they map to the underlying data source.

Most of the properties accept the following attributes:

* `description` - optional, string value to add any documentation about the property. Does not have an actual effect on how the property behaves. For example,

  ```json
  {
    "objects": {
      "movies": {
        "properties": {
          "id": {
            "description": "Unique ID for a movie",
            "type": "integer",
            "identifier": true
          },
          "name": {
            "description": "Name of the movie",
            "type": "string"
          }
        }
      }
    }
  }
  ```
* `default`- optional, object value that defines either a hardcoded value or a function that generates a default value for the property. For example,

  ```json
  {
    "objects": {
      "movies": {
        "properties": {
          "id": {
            "type": "integer",
            "identifier": true,
            "default": {
              "function": "autoincrement"
            }
          },
          "name": {
            "description": "Name of the movie",
            "type": "string",
            "default": {
              "value": "Untitled"
            }
          }
        }
      }
    }
  }
  ```
* `sourceType`- optional, string or array value to specify the underlying data source type for this property. For examples on `sourceType`, refer to the respective property’s documentation.
* `sourceName`- optional, string value to specify how this property is named in the underlying data source. This is particularly useful in MongoDB where `[_id` field describes a unique `objectId`]\(<https://www.mongodb.com/docs/v2.4/reference/object-id/>), which is the primary key for every document. For example,

  ```json
  {
    "objects": {
      "movies": {
        "properties": {
          "id": {
            "type": "string",
            "sourceType": "ObjectId",
            "sourceName": "_id",
            "identifier": true
          },
          "name": {
            "type": "string"
          }
        }
      }
    }
  }
  ```
* `nullable` - optional, boolean value to specify if the property is nullable or not. By default, nullable is set as false which means it’s a required property. Here is example for setting nullable to true -

  ```json
  {
    "objects": {
      "movies": {
        "properties": {
          "id": {
            "type": "integer",
            "identifier": true
          },
          "name": {
            "type": "string",
            "nullable": true
          }
        }
      }
    }
  }
  ```
* `identifier` - optional, boolean value to specify if the property should be treated as a primary key in the underlying data source. For example,

  ```json
  {
    "objects": {
      "movies": {
        "properties": {
          "id": {
            "type": "integer",
            "identifier": true
          },
          "name": {
            "type": "string"
          }
        }
      }
    }
  }
  ```
* `unique` - optional, boolean value to specify if the property should be treated as a unique key in the underlying data source. For example,

  ```json
  {
    "objects": {
      "movies": {
        "properties": {
          "id": {
            "type": "integer",
            "identifier": true
          },
          "name": {
            "type": "string",
            "unique": true
          }
        }
      }
    }
  }
  ```

### <mark style="color:green;">Boolean</mark>

Required attributes: `type`

Optional attributes: `default`, `sourceType`, `description`, `nullable`, `sourceName`, `identifier`, `unique`

#### `default`

Default value can be one of:

* Default `true`/`false` value. For instance, `"default": { "value": true }`.
* `dbgenerated` function. Refer to Function section for further details on this.

#### `sourceType`

```json
{
  "type": "boolean",
  "sourceType": "Boolean"
}
```

#### PostgreSQL

| Data Source Type | NSL sourceType | Examples                | Notes |
| ---------------- | -------------- | ----------------------- | ----- |
| boolean          | Boolean        | "sourceType": "Boolean" |       |

#### MySQL

| Data Source Type | NSL sourceType | Examples                | Notes |
| ---------------- | -------------- | ----------------------- | ----- |
| BIT(1)           | Bit            | "sourceType": "Bit"     |       |
| TINYINT(1)       | TinyInt        | "sourceType": "TinyInt" |       |

#### MongoDB

| Data Source Type | NSL sourceType | Examples             | Notes |
| ---------------- | -------------- | -------------------- | ----- |
| bool             | Bool           | "sourceType": "Bool" |       |

### <mark style="color:green;">String</mark>

Required attributes: `type`

Optional attributes: `format`, `default`, `sourceType`, `description`, `nullable`, `sourceName`, `identifier`, `unique`

#### `default`

String supports a wide range of defaults:

* Default string value. For instance, `"default": { "value": "SomeValue" }`.
* `dbgenerated`, `auto`, `cuid`, and `uuid` functions. Refer to Function section for further details on these.

#### `sourceType`

```json
{
  "type": "string",
  "sourceType": ["VarChar", 255]
}
```

#### PostgreSQL

| Data Source Type              | NSL sourceType                                                                   | Examples                | Notes   |
| ----------------------------- | -------------------------------------------------------------------------------- | ----------------------- | ------- |
| text                          | Text                                                                             | "sourceType": "Text"    | Default |
| varbit                        | VarBit                                                                           | "sourceType": "VarBit"  |         |
| uuid                          | Uuid                                                                             | "sourceType": "Uuid"    |         |
| xml                           | Xml                                                                              | "sourceType": "Xml"     |         |
| inet                          | Inet                                                                             | "sourceType": "Inet"    |         |
| citext                        | Citext                                                                           | "sourceType": "Citext"  |         |
| point                         | Point                                                                            | "sourceType": "Point"   |         |
| bit(n)                        | Bit                                                                              | "sourceType": "Bit"     |         |
| "sourceType": \["Bit", 5]     | String form defaults length to 1. Array form is used to specify specific length. |                         |         |
| char(n)                       | Char                                                                             | "sourceType": "Char"    |         |
| "sourceType": \["Char", 5]    | String form defaults length to 1. Array form is used to specify specific length. |                         |         |
| varchar(n)                    | VarChar                                                                          | "sourceType": "VarChar" |         |
| "sourceType": \["VarChar", 5] | String form allows any length. Array form is used to specify max length.         |                         |         |

#### MySQL

| Data Source Type              | NSL sourceType                                                                            | Examples                   | Notes |
| ----------------------------- | ----------------------------------------------------------------------------------------- | -------------------------- | ----- |
| TEXT                          | Text                                                                                      | "sourceType": "Text"       |       |
| TINYTEXT                      | TinyText                                                                                  | "sourceType": "TinyText"   |       |
| MEDIUMTEXT                    | MediumText                                                                                | "sourceType": "MediumText" |       |
| LONGTEXT                      | LongText                                                                                  | "sourceType": "LongText"   |       |
| CHAR(n)                       | Char                                                                                      | "sourceType": "Char"       |       |
| "sourceType": \["Char", 5]    | String form defaults length to 1. Array form is used to specify specific length.          |                            |       |
| VARCHAR(n)                    | VarChar                                                                                   | "sourceType": "VarChar"    |       |
| "sourceType": \["VarChar", 5] | Default. String form defaults to max length 80. Array form is used to specify max length. |                            |       |

#### MongoDB

| Data Source Type | NSL sourceType | Examples                 | Notes                        |
| ---------------- | -------------- | ------------------------ | ---------------------------- |
| String           | String         | "sourceType": "String"   | Default                      |
| ObjectId         | ObjectId       | "sourceType": "ObjectId" | Required for BSON id fields. |

### <mark style="color:green;">Integer</mark>

Required attributes: `type`

Optional attributes: `default`, `sourceType`, `description`, `nullable`, `sourceName`, `identifier`, `unique`

#### `default`

Default value can be one of:

* Default integer value. For instance, `"default": { "value": 0 }`.
* `dbgenerated` function. Refer to Function section for further details on this.

#### `sourceType`

```json
{
  "type": "integer",
  "sourceType": "SmallInt"
}
```

#### PostgreSQL

| Data Source Type | NSL sourceType | Examples                 | Notes   |
| ---------------- | -------------- | ------------------------ | ------- |
| integer          | Integer        | "sourceType": "Integer"  | Default |
| smallint         | SmallInt       | "sourceType": "SmallInt" |         |
| oid              | Oid            | "sourceType": "Oid"      |         |

#### MySQL

| Data Source Type   | NSL sourceType    | Examples                          | Notes   |
| ------------------ | ----------------- | --------------------------------- | ------- |
| TINYINT            | TinyInt           | "sourceType": "Boolean"           |         |
| TINYINT UNSIGNED   | UnsignedTinyInt   | "sourceType": "UnsignedTinyInt"   |         |
| SMALLINT           | SmallInt          | "sourceType": "SmallInt"          |         |
| SMALLINT UNSIGNED  | UnsignedSmallInt  | "sourceType": "UnsignedSmallInt"  |         |
| MEDIUMINT          | MediumInt         | "sourceType": "MediumInt"         |         |
| MEDIUMINT UNSIGNED | UnsignedMediumInt | "sourceType": "UnsignedMediumInt" |         |
| INT                | Int               | "sourceType": "Boolean"           | Default |
| INT UNSIGNED       | UnsignedInt       | "sourceType": "UnsignedInt"       |         |
| YEAR               | Year              | "sourceType": "Year"              |         |

#### MongoDB

| Data Source Type | NSL sourceType | Examples             | Notes                   |
| ---------------- | -------------- | -------------------- | ----------------------- |
| int              | Int            | "sourceType": "Int"  | Default. 32-bit integer |
| long             | Long           | "sourceType": "Long" | 64-bit integer          |

### <mark style="color:green;">Big Int</mark>

Required attributes: `type`, `format`

Optional attributes: `default`, `sourceType`, `description`, `nullable`, `sourceName`, `identifier`, `unique`

By default, Big Int maps to [`bigint` in PostgreSQL](https://www.postgresql.org/docs/current/datatype-numeric.html), [`BIGINT` in MySQL](https://dev.mysql.com/doc/refman/8.0/en/integer-types.html), and [`long` in MongoDB](https://www.mongodb.com/docs/mongodb-shell/reference/data-types/#long). See `sourceType` sub-section for further details.

As big int is a special kind of string, to specify the usage of big int, `"format": "bigInt"` is required.

#### `default`

Default value can be one of:

* Default big int value. For instance, `"default": { "value": 0 }`.
* `dbgenerated` function. Refer to Function section for further details on this.

#### `sourceType`

```json
{
  "type": "string",
  "format": "bigInt",
  "sourceType": "BigInt"
}
```

#### PostgreSQL

| Data Source Type | NSL sourceType | Examples               | Notes   |
| ---------------- | -------------- | ---------------------- | ------- |
| bigint           | BigInt         | "sourceType": "BigInt" | Default |

#### MySQL

| Data Source Type | NSL sourceType | Examples                       | Notes   |
| ---------------- | -------------- | ------------------------------ | ------- |
| BIGINT           | BigInt         | "sourceType": "BigInt"         | Default |
| BIGINT UNSIGNED  | UnsignedBigInt | "sourceType": "UnsignedBigInt" |         |

#### MongoDB

| Data Source Type | NSL sourceType | Examples               | Notes   |
| ---------------- | -------------- | ---------------------- | ------- |
| long             | BigInt         | "sourceType": "BigInt" | Default |

### <mark style="color:green;">Float</mark>

Required attributes: `type`, `format`

Optional attributes: `default`, `sourceType`, `description`, `nullable`, `sourceName`, `identifier`, `unique`

As float is a special kind of number, to specify the usage of float, `"format": "float"` is required.

#### `default`

Default value can be one of:

* Default number value. For instance, `"default": { "value": 0.0 }`.
* `dbgenerated` function. Refer to Function section for further details on this.

#### `sourceType`

```json
{
  "type": "number",
  "format": "float",
  "sourceType": "Real"
}
```

#### PostgreSQL

| Data Source Type | NSL sourceType  | Examples                        | Notes   |
| ---------------- | --------------- | ------------------------------- | ------- |
| double precision | DoublePrecision | "sourceType": "DoublePrecision" | Default |
| real             | Real            | "sourceType": "Real"            |         |

#### MySQL

| Data Source Type | NSL sourceType | Examples               | Notes   |
| ---------------- | -------------- | ---------------------- | ------- |
| FLOAT            | Float          | "sourceType": "Float"  |         |
| DOUBLE           | Double         | "sourceType": "Double" | Default |

#### MongoDB

| Data Source Type | NSL sourceType | Examples               | Notes   |
| ---------------- | -------------- | ---------------------- | ------- |
| double           | Double         | "sourceType": "Double" | Default |

### <mark style="color:green;">Decimal</mark>

Required attributes: `type`, `format`

Optional attributes: `default`, `sourceType`, `description`, `nullable`, `sourceName`, `identifier`, `unique`

As decimal is a special kind of string, to specify the usage of decimal, `"format": "decimal"` is required with `"type": "string"`.

#### `default`

Default value can be one of:

* Default decimal value. NSL matches decimal values with an optional minus sign, allowing for both integer and decimal parts. For instance, some strings that would match are: `123`, `-45`, `0.314`, `.56`, `-123.456`. A default value can be specified as `"default": { "value": 0 }`.
* `dbgenerated` function. Refer to Function section for further details on this.

#### `sourceType`

```json
{
  "type": "string",
  "format": "decimal",
  "sourceType": "Money"
}
```

#### PostgreSQL

| Data Source Type                 | NSL sourceType                                                                                                  | Examples                | Notes |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------- | ----------------------- | ----- |
| money                            | Money                                                                                                           | "sourceType": "Money"   |       |
| decimal(p, s)                    | Decimal                                                                                                         | "sourceType": "Decimal" |       |
| "sourceType": \["Decimal", 3, 1] | Default. String form allows for unconstrained precision. Array form is used to specify the precision and scale. |                         |       |

#### MySQL

| Data Source Type                 | NSL sourceType                                                                                                  | Examples                | Notes |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------- | ----------------------- | ----- |
| DECIMAL(p, s)                    | Decimal                                                                                                         | "sourceType": "Decimal" |       |
| "sourceType": \["Decimal", 3, 1] | Default. String form allows for unconstrained precision. Array form is used to specify the precision and scale. |                         |       |

#### MongoDB

| Data Source Type | NSL sourceType | Examples                   | Notes   |
| ---------------- | -------------- | -------------------------- | ------- |
| decimal          | Decimal128     | "sourceType": "Decimal128" | Default |

### <mark style="color:green;">Date Time</mark>

Required attributes: `type` and `format`

Optional attributes: `default`, `sourceType`, `description`, `nullable`, `sourceName`, `identifier`, `unique`

For date time, the format supported is `date-time`. This is derived from [RFC 3339, section 5.6](https://datatracker.ietf.org/doc/html/rfc3339#section-5.6), in accordance with the JSON schema standard.

* date: 4 digit full year “-” 2 digit month “-” 2 digit day
  * For example, 9th January 2023 is represented as `2023-01-09`
* time: partial-time time-offset
  * `partial-time` - hour ":" minute ":" second
  * `time-offset`: `"Z" / time-numoffset`, where `time-numoffset` is ("+" / "-") hour-offset ":" minute-offset.
  * For example, 4:30 pm with a time offset of 15 minutes is represented as `16:30:00+00:15`
* `date-time`: date "T" time
  * For example, 12:30 pm on 4th July 1990 can be represented as `1990-07-04T12:30:00Z`. Here, the `Z` suffix denotes a UTC offset of 00:00.

Note that the letters `T` and `Z` used in the date/time syntax must always be upper case.

{% hint style="warning" %}
Our APIs currently only accept complete timestamps. This means you must follow the `date-time` format (`yyyy-mm-ddTHH:MM:SSZ`) specified above, even if your underlying data source type is just a `date` or `time` type.
{% endhint %}

#### `default`

Date Time supports a wide range of defaults:

* Default date-time value. For instance, `"default": { "value": "2024-01-01T12:00:00Z", "format": "date-time" }`.
* `now` and `dbgenerated` functions. Refer to Function section for further details on these.

#### `sourceType`

```json
{
  "format": "date-time",
  "type": "string",
  "sourceType": "Timestamptz"
}

{
  "format": "date-time",
  "type": "string",
  "sourceType": "Date"
}

{
  "format": "date-time",
  "type": "string",
  "sourceType": "Timetz"
}
```

#### PostgreSQL

| Data Source Type                  | NSL sourceType                                                                                       | Examples                    | Notes |
| --------------------------------- | ---------------------------------------------------------------------------------------------------- | --------------------------- | ----- |
| date                              | Date                                                                                                 | "sourceType": "Date"        |       |
| timestamp(n)                      | Timestamp                                                                                            | "sourceType": "Timestamp"   |       |
| "sourceType": \["Timestamp", 3]   | Default. String form defaults to max 6 digits of precision. Array form is used to specify precision. |                             |       |
| timestamptz(n)                    | Timestamptz                                                                                          | "sourceType": "Timestamptz" |       |
| "sourceType": \["Timestamptz", 3] | String form defaults to max 6 digits of precision. Array form is used to specify precision.          |                             |       |
| time(n)                           | Time                                                                                                 | "sourceType": "Time"        |       |
| "sourceType": \["Time", 3]        | String form defaults to max 6 digits of precision. Array form is used to specify precision.          |                             |       |
| timetz(n)                         | Timetz                                                                                               | "sourceType": "Timetz"      |       |
| "sourceType": \["Timetz", 3]      | String form defaults to max 6 digits of precision. Array form is used to specify precision.          |                             |       |

#### MySQL

| Data Source Type                | NSL sourceType                                                                                       | Examples                  | Notes |
| ------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------- | ----- |
| date                            | Date                                                                                                 | "sourceType": "Date"      |       |
| DATETIME(n)                     | DateTime                                                                                             | "sourceType": "DateTime"  |       |
| "sourceType": \["DateTime", 3]  | Default. String form defaults to max 6 digits of precision. Array form is used to specify precision. |                           |       |
| TIME(n)                         | Time                                                                                                 | "sourceType": "Time"      |       |
| "sourceType": \["Time", 3]      | String form defaults to max 6 digits of precision. Array form is used to specify precision.          |                           |       |
| TIMESTAMP(n)                    | Timestamp                                                                                            | "sourceType": "Timestamp" |       |
| "sourceType": \["Timestamp", 3] | String form defaults to max 6 digits of precision. Array form is used to specify precision.          |                           |       |

#### MongoDB

| Data Source Type | NSL sourceType | Examples                  | Notes   |
| ---------------- | -------------- | ------------------------- | ------- |
| date             | Date           | "sourceType": "Date"      |         |
| timestamp        | Timestamp      | "sourceType": "Timestamp" | Default |

### <mark style="color:green;">Bytes</mark>

Required attributes: `type` and `format`

Optional attributes: `default`, `sourceType`, `description`, `nullable`, `sourceName`, `identifier`, `unique`

As bytes is a special kind of string, to specify the usage of bytes, `"format": "bytes"` is required.

#### `default`

Default value can be one of:

* Default byte value. For instance, `"default": { "value": "V2VsY29tZSB0byBOZXVyZWxv" }`.
* `dbgenerated` function. Refer to Function section for further details on this.

#### `sourceType`

```json
{
  "type": "string",
  "format": "bytes",
  "sourceType": "ByteA"
}
```

#### PostgreSQL

| Data Source Type | NSL sourceType | Examples              | Notes   |
| ---------------- | -------------- | --------------------- | ------- |
| bytea            | ByteA          | "sourceType": "ByteA" | Default |

#### MySQL

| Data Source Type | NSL sourceType | Examples                   | Notes   |
| ---------------- | -------------- | -------------------------- | ------- |
| BIT(1)           | Bit            | "sourceType": "Bit"        |         |
| BINARY           | Binary         | "sourceType": "Binary"     |         |
| VARBINARY        | VarBinary      | "sourceType": "VarBinary"  |         |
| TINYBLOB         | TinyBlob       | "sourceType": "TinyBlob"   |         |
| MEDIUMBLOB       | MediumBlob     | "sourceType": "MediumBlob" |         |
| BLOB             | Blob           | "sourceType": "Blob"       |         |
| LONGBLOB         | LongBlob       | "sourceType": "LongBlob"   | Default |

#### MongoDB

| Data Source Type | NSL sourceType | Examples                | Notes   |
| ---------------- | -------------- | ----------------------- | ------- |
| binData          | BinData        | "sourceType": "BinData" | Default |

### <mark style="color:green;">JSON</mark>

Required attributes: `type` and `format`

Optional attributes: `default`, `sourceType`, `description`, `nullable`, `sourceName`, `identifier`, `unique`

As a JSON type can itself support a number of basic types, its `type` is represented as `["array", "boolean", "integer", "number", "object", "string"]`. Furthermore, `format` is required to be of type `json`.

#### `default`

Default value can be one of:

* Default JSON value. For instance, `"default": { "value": ["apple gardens", "strawberry fields", "vineyards"] }`.
* `dbgenerated` function. Refer to Function section for further details on this.

#### `sourceType`

```json
{
  "type": [
    "array",
    "boolean",
    "integer",
    "number",
    "object",
    "string"
  ],
  "format": "json",
  "sourceType": "Jsonb"
}
```

#### PostgreSQL

| Data Source Type | NSL sourceType | Examples              | Notes   |
| ---------------- | -------------- | --------------------- | ------- |
| json             | Json           | "sourceType": "Json"  |         |
| jsonb            | JsonB          | "sourceType": "JsonB" | Default |

#### MySQL

| Data Source Type | NSL sourceType | Examples             | Notes   |
| ---------------- | -------------- | -------------------- | ------- |
| JSON             | Json           | "sourceType": "Json" | Default |

#### MongoDB

In MongoDB, `json` is used indicate the flexible property type and that multiple types are supported for that property&#x20;

### <mark style="color:green;">Enum</mark>

Properties referencing an enum can be used to constrain its possible values to the ones defined in the enum.

The `$ref` property is used to reference a specific part of the schema by assigning it a value containing the path to the referenced part:

```json
{
  "$ref": "#/enums/Rating",
  "default": {
    "value": "PG"
  }
}
```

The example above is referencing `Rating` enum defined in the `Enums` section.

Optionally, references to enums can define a default value for the property.

### <mark style="color:green;">Array</mark>

Required attributes: `type` and `items`

Optional attributes: `description` and `sourceName`

An array field can be represented by specifying a `"type": "array"`, followed by the shape of the individual items the array will contain:

```json
{
  "type": "array",
  "items": {
    "type": "string",
    "format": "decimal"
  }
}
```

Note that `sourceType` can be specified in the `items` if necessary.

### <mark style="color:green;">Relation</mark>

A reference in an object represents a relationship between the two of them. The `relation` property is used to indicate relationships between objects in the schema definition.

The `relation` property contains the following attributes:

* attrKey - string or array of strings with the name of the object properties that contain the references to the foreign object.
* foreignAttrKey - string or array of strings with the name of the foreign object properties that should match the ones defined in `attrKey`.
* name - optional, used to disambiguate when multiple relationships between the same models are present.
* sourceName - optional, the name that should be used in the datasource for the foreign key index
* onUpdate - optional, side effect to use when a parent model is updated. Defaults to `NoAction.`
* onDelete - optional, side effect to use when a parent model is deleted. Defaults to `NoAction`.
* The actions supported by `onUpdate` and `onDelete` are:
  * `Restrict`: Prevents updation/deletion if any child model’s records exist.
  * `NoAction`: Similar to `Restrict` however the functionality of `NoAction` depends on the database being used. For instance,
    * PostgreSQL: [As mentioned in PostgreSQL docs](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-FK), `NoAction` behaves similar to `Restrict` except `NoAction` allows the check to be deferred until later in the transaction, whereas `Restrict` does not.
    * MySQL: For MySQL, `[NoAction` is equivalent to `Restrict`]\(<https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html#foreign-key-referential-actions>).
    * MongoDB: When a parent model’s record is updated/deleted, the child model’s records remain as is.
  * `Cascade`: Updating/deleting records from the parent model automatically triggers updation/deletion of corresponding records referenced in the child model.
  * `SetNull`: After updating/deleting record from the parent model, the corresponding records referenced in the child model are set to `Null`.
  * `SetDefault`: After updating/deleting record from the parent model, the corresponding records referenced in the child model are set to their default values.

#### <mark style="color:blue;">One to One</mark>

In the following example we have two objects: authors and author\_details. The author\_details object contains the relationship definition, as it is the one that has the author\_id foreign key property. On the other hand, the authors object only contains a property with items referencing the author\_details object.

```json
{
  "objects": {
    "authors": {
      "properties": {
        "id": {
          "type": "integer",
          "identifier": true
        },
        "details": {
          "$ref": "#/objects/author_details",
          "nullable": true
        }
      }
    },
    "author_details": {
      "properties": {
        "id": {
          "type": "integer",
          "identifier": true
        },
        "author_id": {
          "type": "integer",
          "unique": true
        },
        "author": {
          "$ref": "#/objects/authors",
          "relation": {
            "attrKey": "author_id",
            "foreignAttrKey": "id"
          }
        }
      }
    }
  }
}
```

#### <mark style="color:blue;">One to Many</mark>

In the following example we have two objects: authors and books. The books object contains the relationship definition, as it is the one that has the author\_id foreign key property. On the other hand, the authors object only contains an array property with items referencing the books object.

```json
{
  "objects": {
    "authors": {
      "properties": {
        "id": {
          "type": "integer",
          "identifier": true
        },
        "books": {
          "type": "array",
          "items": {
            "$ref": "#/objects/books"
          }
        }
      }
    },
    "books": {
      "properties": {
        "id": {
          "type": "integer",
          "identifier": true
        },
        "author_id": {
          "type": "integer"
        },
        "author": {
          "$ref": "#/objects/authors",
          "relation": {
            "attrKey": "author_id",
            "foreignAttrKey": "id"
          }
        }
      }
    }
  }
}
```

#### <mark style="color:blue;">Many to Many - implicit</mark>

In the following example we have two objects: books and libraries. A book can be found in many libraries, and each library contains many books. To define this type of relationship, where we are only interested in whether or not the records are related, we can use an implicit many to many definition.

```json
{
  "objects": {
    "books": {
      "properties": {
        "id": {
          "type": "integer",
          "identifier": true
        },
        "libraries": {
          "type": "array",
          "items": {
            "$ref": "#/objects/libraries"
          }
        }
      }
    },
    "libraries": {
      "properties": {
        "id": {
          "type": "integer",
          "identifier": true
        },
        "books": {
          "type": "array",
          "items": {
            "$ref": "#/objects/books"
          }
        }
      }
    }
  }
}
```

#### <mark style="color:blue;">Many to Many - explicit</mark>

Same scenario as the implicit version, but this time we need to keep track of additional information in the many to many pivot table, like the amount of books each library has purchased.

```json
{
  "objects": {
    "books": {
      "properties": {
        "id": {
          "type": "integer",
          "identifier": true
        },
        "libraries": {
          "type": "array",
          "items": {
            "$ref": "#/objects/library_books"
          }
        }
      }
    },
    "libraries": {
      "properties": {
        "id": {
          "type": "integer",
          "identifier": true
        },
        "books": {
          "type": "array",
          "items": {
            "$ref": "#/objects/library_books"
          }
        }
      }
    },
    "library_books": {
      "properties": {
        "id": {
          "type": "integer",
          "identifier": true
        },
        "book_id": {
          "type": "integer"
        },
        "library_id": {
          "type": "integer"
        },
        "purchased_amount": {
          "type": "integer"
        },
        "book": {
          "$ref": "#/objects/books",
          "relation": {
            "attrKey": "book_id",
            "foreignAttrKey": "id"
          }
        },
        "library": {
          "$ref": "#/objects/libraries",
          "relation": {
            "attrKey": "library_id",
            "foreignAttrKey": "id"
          }
        }
      }
    }
  }
}
```

## <mark style="color:purple;">Functions</mark>

Functions can be used to generate the default value for a property. The supported functions are:

* auto - Only available for MongoDB. Generates an ObjectId.
* autoincrement - Generates an automatically incremented integer value.
* cuid - Generates a string value based on the CUID spec.
* uuid - Generates a string value based on the UUID spec.
* now - Generates a Date Time value with the current data source timestamp.
* dbgenerated - Generates a value by executing the provided “rawDbValue”.
  * `rawDbValue`’s value is a database function. For instance, in PostgreSQL, `gen_random_uuid()` returns a random UUID that can be used for primary key values.

Functions can be used as follows:

```json
{
  "objects": {
    "movies": {
      "properties": {
        "id": {
          "type": "integer",
          "identifier": true,
          "default": {
            "function": "autoincrement"
          }
        }
      }
    },
    "actors": {
      "properties": {
        "id": {
          "type": "string",
          "identifier": true,
          "default": {
            "function": "dbgenerated",
            "rawDbValue": "gen_random_uuid()"
          }
        }
      }
    }
  }
}
```

## <mark style="color:purple;">Constraints</mark>

### <mark style="color:green;">Identifier</mark>

An identifier constraint can be used to define a multi-property primary key index for an object:

```json
{
  "objects": {
    "movies": {
      "properties": {
        "name": {
          "type": "string"
        },
        "rating": {
          "$ref": "#/enums/Rating",
          "default": {
            "value": "G"
          }
        }
      },
      "constraints": [
        {
          "type": "identifier",
          "property": [
            "name",
            "rating"
          ],
          "alias": "name_rating_id",
          "sourceName": "name_rating_pk"
        }
      ]
    }
  },
  "enums": {
    "Rating": [
      "G"
    ]
  }
}
```

The optional “alias” property will be used in Neurelo’s APIs to allow filtering by all the properties of this constraint.

The optional “sourceName” property indicates how this index constraint is named in the data source.

### <mark style="color:green;">Unique</mark>

A unique constraint can be used to define a multi-property unique index for an object:

```json
{
  "objects": {
    "movies": {
      "properties": {
        "name": {
          "type": "string"
        },
        "rating": {
          "$ref": "#/enums/Rating",
          "default": {
            "value": "G"
          }
        }
      },
      "constraints": [
        {
          "type": "unique",
          "property": [
            "name",
            "rating"
          ],
          "alias": "name_rating_id",
          "sourceName": "name_rating_ux"
        }
      ]
    }
  },
  "enums": {
    "Rating": [
      "G"
    ]
  }
}
```

The optional “alias” property will be used in Neurelo’s APIs to allow filtering by all the properties of this constraint.

The optional “sourceName” property indicates how this index constraint is named in the data source.

NOTE: The “sort” property is not supported within a unique constraint.

### <mark style="color:green;">Index</mark>

An index constraint can be used to define a single or multi-property index for an object:

```json
{
  "objects": {
    "movies": {
      "properties": {
        "id": {
          "type": "string",
          "identifier": true
        },
        "name": {
          "type": "string"
        },
        "rating": {
          "$ref": "#/enums/Rating",
          "default": {
            "value": "G"
          }
        },
        "releaseDate": {
          "type": "string",
          "format": "date-time"
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "name",
            "releaseDate"
          ],
          "alias": "nameReleaseDate",
          "kind": "BTree"
        }
      ]
    }
  },
  "enums": {
    "Rating": [
      "G"
    ]
  }
}
```

The optional “alias” property will be used in Neurelo’s APIs to allow filtering by all the properties of this constraint.

The optional “sourceName” property indicates how this index constraint is named in the data source.

The optional “sort” property indicates the order in which the entries of this index will be stored in the data source.

The optional “length” property indicates the maximum length of the value to be indexed. Only available for MySQL.

The optional “kind” property indicates the type of index to be used in the data source. Defaults to “BTree”. Available options are: Hash, Gist, SpGist, Gin, Brin. Only available for PostgreSQL.

## <mark style="color:purple;">Inner Objects</mark>

Only available for MongoDB. Inner Objects are defined in an almost identical way as objects, with the difference that the cannot have identifier or unique properties, nor constraints.

Inner objects can be used to describe complex schemas that can be reused across multiple objects properties via references. These properties will be represented in the underlying database as embedded documents.

```json
{
  "objects": {
    "libraries": {
      "properties": {
        "id": {
          "type": "string",
          "sourceType": "ObjectId",
          "identifier": true,
          "sourceName": "_id",
          "default": {
            "function": "auto"
          }
        },
        "public_bookshelves": {
          "type": "array",
          "items": {
            "$ref": "#/innerObjects/bookshelf"
          }
        },
        "private_bookshelves": {
          "type": "array",
          "items": {
            "$ref": "#/innerObjects/bookshelf"
          }
        }
      }
    }
  },
  "innerObjects": {
    "bookshelf": {
      "properties": {
        "width": {
          "type": "number",
          "format": "float"
        },
        "height": {
          "type": "number",
          "format": "float"
        },
        "number_of_shelves": {
          "type": "integer"
        }
      }
    }
  }
}
```

## <mark style="color:purple;">Features</mark>

Features are extensions to the schema.

### <mark style="color:green;">User Auth</mark>

For a guide on using this feature, see[#user-auth](#user-auth "mention"). To enable the feature you just have to specify the version (currently `"1"`)

```json
{
  "features": {
    "auth": {
      "version": "1"
    }
  },
  ...
}
```


# Example 1 - DVD Rentals

This is a DVD Rentals example database schema from PostgreSQL Tutorial (https\://www\.postgresqltutorial.com/postgresql-getting-started/postgresql-sample-database)

### Overview

There are 15 tables in the DVD Rental database:

* **actor** – stores actors data including first name and last name.
* **film** – stores film data such as title, release year, length, rating, etc.
* **film\_actor** – stores the relationships between films and actors.
* **category** – stores film’s categories data.
* **film\_category**- stores the relationships between films and categories.
* **store** – contains the store data including manager staff and address.
* **inventory** – stores inventory data.
* **rental** – stores rental data.
* **payment** – stores customer’s payments.
* **staff** – stores staff data.
* **customer** – stores customer data.
* **address** – stores address data for staff and customers
* **city** – stores city names.
* **country** – stores country names.

### ERD

Here is the ERD of the sample DVD rentals database:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F4QKzqTMOoc5Hl2AxuAat%2Fdvd-rental-sample-database-diagram.png?alt=media&amp;token=ad11ec29-921b-4448-902c-7677c63bb868" alt=""><figcaption></figcaption></figure>

### Neurelo Schema

This is the schema in the Neurelo Schema Language JSON Specification format

```json
{
  "objects": {
    "actor": {
      "properties": {
        "actor_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "film_actor": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film_actor"
          }
        },
        "first_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "last_name"
          ],
          "sourceName": "idx_actor_last_name"
        }
      ]
    },
    "address": {
      "properties": {
        "address": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ]
        },
        "address2": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ],
          "nullable": true
        },
        "address_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "city": {
          "$ref": "#/objects/city",
          "relation": {
            "attrKey": [
              "city_id"
            ],
            "foreignAttrKey": [
              "city_id"
            ],
            "sourceName": "fk_address_city",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "city_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "customer": {
          "type": "array",
          "items": {
            "$ref": "#/objects/customer"
          }
        },
        "district": {
          "type": "string",
          "sourceType": [
            "VarChar",
            20
          ]
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "phone": {
          "type": "string",
          "sourceType": [
            "VarChar",
            20
          ]
        },
        "postal_code": {
          "type": "string",
          "sourceType": [
            "VarChar",
            10
          ],
          "nullable": true
        },
        "staff": {
          "type": "array",
          "items": {
            "$ref": "#/objects/staff"
          }
        },
        "store": {
          "type": "array",
          "items": {
            "$ref": "#/objects/store"
          }
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "city_id"
          ],
          "sourceName": "idx_fk_city_id"
        }
      ]
    },
    "category": {
      "properties": {
        "category_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "film_category": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film_category"
          }
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            25
          ]
        }
      }
    },
    "city": {
      "properties": {
        "address": {
          "type": "array",
          "items": {
            "$ref": "#/objects/address"
          }
        },
        "city": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ]
        },
        "city_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "country": {
          "$ref": "#/objects/country",
          "relation": {
            "attrKey": [
              "country_id"
            ],
            "foreignAttrKey": [
              "country_id"
            ],
            "sourceName": "fk_city",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "country_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "country_id"
          ],
          "sourceName": "idx_fk_country_id"
        }
      ]
    },
    "country": {
      "properties": {
        "city": {
          "type": "array",
          "items": {
            "$ref": "#/objects/city"
          }
        },
        "country": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ]
        },
        "country_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      }
    },
    "customer": {
      "properties": {
        "active": {
          "type": "integer",
          "nullable": true
        },
        "activebool": {
          "type": "boolean",
          "default": {
            "value": true
          }
        },
        "address": {
          "$ref": "#/objects/address",
          "relation": {
            "attrKey": [
              "address_id"
            ],
            "foreignAttrKey": [
              "address_id"
            ]
          }
        },
        "address_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "create_date": {
          "type": "string",
          "format": "date",
          "sourceType": "Date",
          "default": {
            "function": "dbgenerated",
            "rawDbValue": "('now'::text)::date"
          }
        },
        "customer_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "email": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ],
          "nullable": true
        },
        "first_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          },
          "nullable": true
        },
        "payment": {
          "type": "array",
          "items": {
            "$ref": "#/objects/payment"
          }
        },
        "rental": {
          "type": "array",
          "items": {
            "$ref": "#/objects/rental"
          }
        },
        "store_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "address_id"
          ],
          "sourceName": "idx_fk_address_id"
        },
        {
          "type": "index",
          "property": [
            "store_id"
          ],
          "sourceName": "idx_fk_store_id"
        },
        {
          "type": "index",
          "property": [
            "last_name"
          ],
          "sourceName": "idx_last_name"
        }
      ]
    },
    "film": {
      "properties": {
        "description": {
          "type": "string",
          "nullable": true
        },
        "film_actor": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film_actor"
          }
        },
        "film_category": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film_category"
          }
        },
        "film_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "inventory": {
          "type": "array",
          "items": {
            "$ref": "#/objects/inventory"
          }
        },
        "language": {
          "$ref": "#/objects/language",
          "relation": {
            "attrKey": [
              "language_id"
            ],
            "foreignAttrKey": [
              "language_id"
            ]
          }
        },
        "language_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "length": {
          "type": "integer",
          "sourceType": "SmallInt",
          "nullable": true
        },
        "rating": {
          "default": {
            "value": "G"
          },
          "nullable": true,
          "$ref": "#/enums/mpaa_rating"
        },
        "release_year": {
          "type": "integer",
          "nullable": true
        },
        "rental_duration": {
          "type": "integer",
          "sourceType": "SmallInt",
          "default": {
            "value": 3
          }
        },
        "rental_rate": {
          "type": "string",
          "format": "decimal",
          "sourceType": [
            "Decimal",
            4,
            2
          ],
          "default": {
            "value": "4.99"
          }
        },
        "replacement_cost": {
          "type": "string",
          "format": "decimal",
          "sourceType": [
            "Decimal",
            5,
            2
          ],
          "default": {
            "value": "19.99"
          }
        },
        "special_features": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "title": {
          "type": "string",
          "sourceType": [
            "VarChar",
            255
          ]
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "language_id"
          ],
          "sourceName": "idx_fk_language_id"
        },
        {
          "type": "index",
          "property": [
            "title"
          ],
          "sourceName": "idx_title"
        }
      ]
    },
    "film_actor": {
      "properties": {
        "actor": {
          "$ref": "#/objects/actor",
          "relation": {
            "attrKey": [
              "actor_id"
            ],
            "foreignAttrKey": [
              "actor_id"
            ]
          }
        },
        "actor_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "film": {
          "$ref": "#/objects/film",
          "relation": {
            "attrKey": [
              "film_id"
            ],
            "foreignAttrKey": [
              "film_id"
            ]
          }
        },
        "film_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      },
      "constraints": [
        {
          "type": "identifier",
          "property": [
            "actor_id",
            "film_id"
          ]
        },
        {
          "type": "index",
          "property": [
            "film_id"
          ],
          "sourceName": "idx_fk_film_id"
        }
      ]
    },
    "film_category": {
      "properties": {
        "category": {
          "$ref": "#/objects/category",
          "relation": {
            "attrKey": [
              "category_id"
            ],
            "foreignAttrKey": [
              "category_id"
            ]
          }
        },
        "category_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "film": {
          "$ref": "#/objects/film",
          "relation": {
            "attrKey": [
              "film_id"
            ],
            "foreignAttrKey": [
              "film_id"
            ]
          }
        },
        "film_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      },
      "constraints": [
        {
          "type": "identifier",
          "property": [
            "film_id",
            "category_id"
          ]
        }
      ]
    },
    "inventory": {
      "properties": {
        "film": {
          "$ref": "#/objects/film",
          "relation": {
            "attrKey": [
              "film_id"
            ],
            "foreignAttrKey": [
              "film_id"
            ]
          }
        },
        "film_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "inventory_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "rental": {
          "type": "array",
          "items": {
            "$ref": "#/objects/rental"
          }
        },
        "store_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "store_id",
            "film_id"
          ],
          "sourceName": "idx_store_id_film_id"
        }
      ]
    },
    "language": {
      "properties": {
        "film": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film"
          }
        },
        "language_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "name": {
          "type": "string",
          "sourceType": [
            "Char",
            20
          ]
        }
      }
    },
    "payment": {
      "properties": {
        "amount": {
          "type": "string",
          "format": "decimal",
          "sourceType": [
            "Decimal",
            5,
            2
          ]
        },
        "customer": {
          "$ref": "#/objects/customer",
          "relation": {
            "attrKey": [
              "customer_id"
            ],
            "foreignAttrKey": [
              "customer_id"
            ]
          }
        },
        "customer_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "payment_date": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ]
        },
        "payment_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "rental": {
          "$ref": "#/objects/rental",
          "relation": {
            "attrKey": [
              "rental_id"
            ],
            "foreignAttrKey": [
              "rental_id"
            ],
            "onDelete": "SetNull"
          }
        },
        "rental_id": {
          "type": "integer"
        },
        "staff": {
          "$ref": "#/objects/staff",
          "relation": {
            "attrKey": [
              "staff_id"
            ],
            "foreignAttrKey": [
              "staff_id"
            ]
          }
        },
        "staff_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "customer_id"
          ],
          "sourceName": "idx_fk_customer_id"
        },
        {
          "type": "index",
          "property": [
            "rental_id"
          ],
          "sourceName": "idx_fk_rental_id"
        },
        {
          "type": "index",
          "property": [
            "staff_id"
          ],
          "sourceName": "idx_fk_staff_id"
        }
      ]
    },
    "rental": {
      "properties": {
        "customer": {
          "$ref": "#/objects/customer",
          "relation": {
            "attrKey": [
              "customer_id"
            ],
            "foreignAttrKey": [
              "customer_id"
            ]
          }
        },
        "customer_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "inventory": {
          "$ref": "#/objects/inventory",
          "relation": {
            "attrKey": [
              "inventory_id"
            ],
            "foreignAttrKey": [
              "inventory_id"
            ]
          }
        },
        "inventory_id": {
          "type": "integer"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "payment": {
          "type": "array",
          "items": {
            "$ref": "#/objects/payment"
          }
        },
        "rental_date": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ]
        },
        "rental_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "return_date": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "nullable": true
        },
        "staff": {
          "$ref": "#/objects/staff",
          "relation": {
            "attrKey": [
              "staff_id"
            ],
            "foreignAttrKey": [
              "staff_id"
            ],
            "sourceName": "rental_staff_id_key",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "staff_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "inventory_id"
          ],
          "sourceName": "idx_fk_inventory_id"
        },
        {
          "type": "unique",
          "property": [
            "rental_date",
            "inventory_id",
            "customer_id"
          ],
          "sourceName": "idx_unq_rental_rental_date_inventory_id_customer_id"
        }
      ]
    },
    "staff": {
      "properties": {
        "active": {
          "type": "boolean",
          "default": {
            "value": true
          }
        },
        "address": {
          "$ref": "#/objects/address",
          "relation": {
            "attrKey": [
              "address_id"
            ],
            "foreignAttrKey": [
              "address_id"
            ]
          }
        },
        "address_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "email": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ],
          "nullable": true
        },
        "first_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "password": {
          "type": "string",
          "sourceType": [
            "VarChar",
            40
          ],
          "nullable": true
        },
        "payment": {
          "type": "array",
          "items": {
            "$ref": "#/objects/payment"
          }
        },
        "picture": {
          "type": "string",
          "format": "bytes",
          "nullable": true
        },
        "rental": {
          "type": "array",
          "items": {
            "$ref": "#/objects/rental"
          }
        },
        "staff_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "store": {
          "nullable": true,
          "$ref": "#/objects/store"
        },
        "store_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "username": {
          "type": "string",
          "sourceType": [
            "VarChar",
            16
          ]
        }
      }
    },
    "store": {
      "properties": {
        "address": {
          "$ref": "#/objects/address",
          "relation": {
            "attrKey": [
              "address_id"
            ],
            "foreignAttrKey": [
              "address_id"
            ]
          }
        },
        "address_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "manager_staff_id": {
          "type": "integer",
          "sourceType": "SmallInt",
          "unique": true
        },
        "staff": {
          "$ref": "#/objects/staff",
          "relation": {
            "attrKey": [
              "manager_staff_id"
            ],
            "foreignAttrKey": [
              "staff_id"
            ]
          }
        },
        "store_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        }
      }
    }
  },
  "enums": {
    "mpaa_rating": [
      "G",
      "PG",
      "PG_13",
      "R",
      "NC_17"
    ]
  }
}
```


# Example 2 - Simple "Posts" App

This is a simple representative schema for a PostgreSQL datasource, which has 4 objects (tables) - links, posts, topics, users - with relationships between these objects.

### Neurelo Schema

{% code fullWidth="false" %}

```json
{
  "objects": {
    "links": {
      "properties": {
        "id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "link": {
          "type": "string",
          "sourceType": [
            "VarChar",
            500
          ],
          "nullable": true
        },
        "title": {
          "type": "string",
          "sourceType": [
            "VarChar",
            500
          ],
          "nullable": true
        },
        "topic_id": {
          "type": "integer",
          "nullable": true
        },
        "topics": {
          "nullable": true,
          "$ref": "#/objects/topics",
          "relation": {
            "attrKey": [
              "topic_id"
            ],
            "foreignAttrKey": [
              "id"
            ],
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        }
      }
    },
    "posts": {
      "properties": {
        "content": {
          "type": "string",
          "nullable": true
        },
        "id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "title": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        },
        "user_id": {
          "type": "integer",
          "nullable": true
        },
        "users": {
          "nullable": true,
          "$ref": "#/objects/users",
          "relation": {
            "attrKey": [
              "user_id"
            ],
            "foreignAttrKey": [
              "id"
            ],
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        }
      }
    },
    "topics": {
      "properties": {
        "description": {
          "type": "string",
          "nullable": true
        },
        "id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "links": {
          "type": "array",
          "items": {
            "$ref": "#/objects/links"
          }
        },
        "title": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        }
      }
    },
    "users": {
      "properties": {
        "email": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        },
        "first_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            100
          ],
          "nullable": true
        },
        "id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "last_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            100
          ],
          "nullable": true
        },
        "password": {
          "type": "string",
          "sourceType": [
            "VarChar",
            500
          ],
          "nullable": true
        },
        "posts": {
          "type": "array",
          "items": {
            "$ref": "#/objects/posts"
          }
        }
      }
    }
  }
}
```

{% endcode %}


# Example 3 - Bookstore

This is the Gravity Bookstore sample database from DatabaseStar (https\://www\.databasestar.com/sample-bookstore-database)

### Overview

This schema contains the following tables:

* **book**: a list of all books available in the store.
* **book\_author**: stores the authors for each book, which is a many-to-many relationship.
* **author**: a list of all authors.
* **book\_language**: a list of possible languages of books.
* **publisher**: a list of publishers for books.
* **customer**: a list of the customers of the Gravity Bookstore.
* **customer\_address**: a list of addresses for customers, as a customer can have more than one address, and an address has more than one customer.
* **address\_status**: a list of statuses for an address, because addresses can be current or old.
* **address**: a list of addresses in the system.
* **country**: a list of countries that addresses are in.
* **cust\_order**: a list of orders placed by customers.
* **order\_line**: a list of books that are a part of each order.
* **shipping\_method**: the possible shipping methods for an order.
* **order\_history**: the history of an order, such as ordered, cancelled, delivered.
* **order\_status**: the possible statuses of an order.

### ERD

Here is the ERD of this sample bookstore database:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FMIaXfeqGWnwT8QOlVWgm%2Ferd_gravity.png?alt=media&amp;token=01ce06d7-bf09-4317-954a-b642c3064cd9" alt=""><figcaption></figcaption></figure>

### Neurelo Schema

This is the schema in the Neurelo Schema Language JSON Specification format

```json
{
  "objects": {
    "address": {
      "properties": {
        "address_id": {
          "type": "integer",
          "identifier": true
        },
        "city": {
          "type": "string",
          "sourceType": [
            "VarChar",
            100
          ],
          "nullable": true
        },
        "country": {
          "nullable": true,
          "$ref": "#/objects/country",
          "relation": {
            "attrKey": [
              "country_id"
            ],
            "foreignAttrKey": [
              "country_id"
            ],
            "sourceName": "fk_addr_ctry",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "country_id": {
          "type": "integer",
          "nullable": true
        },
        "cust_order": {
          "type": "array",
          "items": {
            "$ref": "#/objects/cust_order"
          }
        },
        "customer_address": {
          "type": "array",
          "items": {
            "$ref": "#/objects/customer_address"
          }
        },
        "street_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        },
        "street_number": {
          "type": "string",
          "sourceType": [
            "VarChar",
            10
          ],
          "nullable": true
        }
      }
    },
    "address_status": {
      "properties": {
        "address_status": {
          "type": "string",
          "sourceType": [
            "VarChar",
            30
          ],
          "nullable": true
        },
        "status_id": {
          "type": "integer",
          "identifier": true
        }
      }
    },
    "author": {
      "properties": {
        "author_id": {
          "type": "integer",
          "identifier": true
        },
        "author_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            400
          ],
          "nullable": true
        },
        "book_author": {
          "type": "array",
          "items": {
            "$ref": "#/objects/book_author"
          }
        }
      }
    },
    "book": {
      "properties": {
        "book_author": {
          "type": "array",
          "items": {
            "$ref": "#/objects/book_author"
          }
        },
        "book_id": {
          "type": "integer",
          "identifier": true
        },
        "book_language": {
          "nullable": true,
          "$ref": "#/objects/book_language",
          "relation": {
            "attrKey": [
              "language_id"
            ],
            "foreignAttrKey": [
              "language_id"
            ],
            "sourceName": "fk_book_lang",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "isbn13": {
          "type": "string",
          "sourceType": [
            "VarChar",
            13
          ],
          "nullable": true
        },
        "language_id": {
          "type": "integer",
          "nullable": true
        },
        "num_pages": {
          "type": "integer",
          "nullable": true
        },
        "order_line": {
          "type": "array",
          "items": {
            "$ref": "#/objects/order_line"
          }
        },
        "publication_date": {
          "type": "string",
          "format": "date",
          "sourceType": "Date",
          "nullable": true
        },
        "publisher": {
          "nullable": true,
          "$ref": "#/objects/publisher",
          "relation": {
            "attrKey": [
              "publisher_id"
            ],
            "foreignAttrKey": [
              "publisher_id"
            ],
            "sourceName": "fk_book_pub",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "publisher_id": {
          "type": "integer",
          "nullable": true
        },
        "title": {
          "type": "string",
          "sourceType": [
            "VarChar",
            400
          ],
          "nullable": true
        }
      }
    },
    "book_author": {
      "properties": {
        "author": {
          "$ref": "#/objects/author",
          "relation": {
            "attrKey": [
              "author_id"
            ],
            "foreignAttrKey": [
              "author_id"
            ],
            "sourceName": "fk_ba_author",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "author_id": {
          "type": "integer"
        },
        "book": {
          "$ref": "#/objects/book",
          "relation": {
            "attrKey": [
              "book_id"
            ],
            "foreignAttrKey": [
              "book_id"
            ],
            "sourceName": "fk_ba_book",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "book_id": {
          "type": "integer"
        }
      },
      "constraints": [
        {
          "type": "identifier",
          "property": [
            "book_id",
            "author_id"
          ],
          "sourceName": "pk_bookauthor"
        }
      ]
    },
    "book_language": {
      "properties": {
        "book": {
          "type": "array",
          "items": {
            "$ref": "#/objects/book"
          }
        },
        "language_code": {
          "type": "string",
          "sourceType": [
            "VarChar",
            8
          ],
          "nullable": true
        },
        "language_id": {
          "type": "integer",
          "identifier": true
        },
        "language_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ],
          "nullable": true
        }
      }
    },
    "country": {
      "properties": {
        "address": {
          "type": "array",
          "items": {
            "$ref": "#/objects/address"
          }
        },
        "country_id": {
          "type": "integer",
          "identifier": true
        },
        "country_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        }
      }
    },
    "cust_order": {
      "properties": {
        "address": {
          "nullable": true,
          "$ref": "#/objects/address",
          "relation": {
            "attrKey": [
              "dest_address_id"
            ],
            "foreignAttrKey": [
              "address_id"
            ],
            "sourceName": "fk_order_addr",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "customer": {
          "nullable": true,
          "$ref": "#/objects/customer",
          "relation": {
            "attrKey": [
              "customer_id"
            ],
            "foreignAttrKey": [
              "customer_id"
            ],
            "sourceName": "fk_order_cust",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "customer_id": {
          "type": "integer",
          "nullable": true
        },
        "dest_address_id": {
          "type": "integer",
          "nullable": true
        },
        "order_date": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "nullable": true
        },
        "order_history": {
          "type": "array",
          "items": {
            "$ref": "#/objects/order_history"
          }
        },
        "order_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "order_line": {
          "type": "array",
          "items": {
            "$ref": "#/objects/order_line"
          }
        },
        "shipping_method": {
          "nullable": true,
          "$ref": "#/objects/shipping_method",
          "relation": {
            "attrKey": [
              "shipping_method_id"
            ],
            "foreignAttrKey": [
              "method_id"
            ],
            "sourceName": "fk_order_ship",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "shipping_method_id": {
          "type": "integer",
          "nullable": true
        }
      }
    },
    "customer": {
      "properties": {
        "cust_order": {
          "type": "array",
          "items": {
            "$ref": "#/objects/cust_order"
          }
        },
        "customer_address": {
          "type": "array",
          "items": {
            "$ref": "#/objects/customer_address"
          }
        },
        "customer_id": {
          "type": "integer",
          "identifier": true
        },
        "email": {
          "type": "string",
          "sourceType": [
            "VarChar",
            350
          ],
          "nullable": true
        },
        "first_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        },
        "last_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        }
      }
    },
    "customer_address": {
      "properties": {
        "address": {
          "$ref": "#/objects/address",
          "relation": {
            "attrKey": [
              "address_id"
            ],
            "foreignAttrKey": [
              "address_id"
            ],
            "sourceName": "fk_ca_addr",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "address_id": {
          "type": "integer"
        },
        "customer": {
          "$ref": "#/objects/customer",
          "relation": {
            "attrKey": [
              "customer_id"
            ],
            "foreignAttrKey": [
              "customer_id"
            ],
            "sourceName": "fk_ca_cust",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "customer_id": {
          "type": "integer"
        },
        "status_id": {
          "type": "integer",
          "nullable": true
        }
      },
      "constraints": [
        {
          "type": "identifier",
          "property": [
            "customer_id",
            "address_id"
          ],
          "sourceName": "pk_custaddr"
        }
      ]
    },
    "order_history": {
      "properties": {
        "cust_order": {
          "nullable": true,
          "$ref": "#/objects/cust_order",
          "relation": {
            "attrKey": [
              "order_id"
            ],
            "foreignAttrKey": [
              "order_id"
            ],
            "sourceName": "fk_oh_order",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "history_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "order_id": {
          "type": "integer",
          "nullable": true
        },
        "order_status": {
          "nullable": true,
          "$ref": "#/objects/order_status",
          "relation": {
            "attrKey": [
              "status_id"
            ],
            "foreignAttrKey": [
              "status_id"
            ],
            "sourceName": "fk_oh_status",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "status_date": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "nullable": true
        },
        "status_id": {
          "type": "integer",
          "nullable": true
        }
      }
    },
    "order_line": {
      "properties": {
        "book": {
          "nullable": true,
          "$ref": "#/objects/book",
          "relation": {
            "attrKey": [
              "book_id"
            ],
            "foreignAttrKey": [
              "book_id"
            ],
            "sourceName": "fk_ol_book",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "book_id": {
          "type": "integer",
          "nullable": true
        },
        "cust_order": {
          "nullable": true,
          "$ref": "#/objects/cust_order",
          "relation": {
            "attrKey": [
              "order_id"
            ],
            "foreignAttrKey": [
              "order_id"
            ],
            "sourceName": "fk_ol_order",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "line_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "order_id": {
          "type": "integer",
          "nullable": true
        },
        "price": {
          "type": "string",
          "format": "decimal",
          "sourceType": [
            "Decimal",
            5,
            2
          ],
          "nullable": true
        }
      }
    },
    "order_status": {
      "properties": {
        "order_history": {
          "type": "array",
          "items": {
            "$ref": "#/objects/order_history"
          }
        },
        "status_id": {
          "type": "integer",
          "identifier": true
        },
        "status_value": {
          "type": "string",
          "sourceType": [
            "VarChar",
            20
          ],
          "nullable": true
        }
      }
    },
    "publisher": {
      "properties": {
        "book": {
          "type": "array",
          "items": {
            "$ref": "#/objects/book"
          }
        },
        "publisher_id": {
          "type": "integer",
          "identifier": true
        },
        "publisher_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            400
          ],
          "nullable": true
        }
      }
    },
    "shipping_method": {
      "properties": {
        "cost": {
          "type": "string",
          "format": "decimal",
          "sourceType": [
            "Decimal",
            6,
            2
          ],
          "nullable": true
        },
        "cust_order": {
          "type": "array",
          "items": {
            "$ref": "#/objects/cust_order"
          }
        },
        "method_id": {
          "type": "integer",
          "identifier": true
        },
        "method_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            100
          ],
          "nullable": true
        }
      }
    }
  }
}
```


# Neurelo API Reference (REST)

## Introduction

This API documentation is intended to provide an overview of how Neurelo generates APIs based on your data definition. It will go into detail on how to perform operations using a sample schema definition. You can then apply these concepts and patterns to your own schema. Reference documentation generated specifically for your data definition is included in your specific project on Neurelo's Data Access Platform.

Neurelo provides two types of APIs that are automatically generated and available for use.&#x20;

* The REST API has predictable resource-oriented URLs, accepts JSON-encoded request bodies, returns JSON-encoded responses, and uses standard HTTP response codes, authentication, and verbs.&#x20;
* The GraphQL API exposes a single endpoint where clients can send GraphQL queries or mutations and a strictly-typed schema that be be shared across consumers.&#x20;

You can toggle between the GraphQL and REST API documentation when reviewing the documentation in the platform.

{% hint style="info" %}
Reference - [Neurelo Supported Databases and Versions](/references/supported-databases)
{% endhint %}

## API Headers

### <mark style="color:green;">Authentication</mark>

API calls to Neurelo are authenticated using an API Key for all API requests. This api key defines which environment the API request is interacting with. You can create an api key under the settings of the specific environment that you are trying to access. API Keys cannot be used across environments.

To utilize an api key, include it as a header with your API Request, using `X-API-KEY` as the key.

### <mark style="color:green;">Query Strategy</mark>

Neurelo generated APIs can be configured to fetch data using either the `selects` or `joins` strategy. The main difference is that `selects` executes multiple queries behind the scenes to gather the desired data, whereas `joins` uses a single query when possible using database-level joins, to fetch the results. By default, `joins` strategy is enabled. This can be changed using an HTTP header.

For example, to fetch all the users and their corresponding posts using `selects` strategy:

```
curl https://$ENV_API_URL/rest/user
    --url-query select='{"$related":true}'
    --header 'X-READ-STRATEGY: selects'
```

Similarly, `'X-READ-STRATEGY: joins'` can be used.

`joins` strategy is suitable for scenarios where you want to minimize the number of queries made to the database, especially when the relation expressions are relatively simpler, and there's less risk of data duplication.

`selects` can be faster in scenarios with multiple many-to-many or one-to-many relations. This is because the database's flat record list from joins can sometimes contain a significant amount of repeated information. Despite joins' quick execution in the database, the process of moving and parsing this redundant data into JSON can incur high costs.

{% hint style="info" %}
Only `GET`calls support this feature.
{% endhint %}

### <mark style="color:green;">Query Viz</mark>

To review the database queries that Neurelo will be sending to your data source, you can use the `X-QUERY-VIZ` HTTP header. For example, to enable query viz while fetching all the users and their corresponding posts:

```
curl https://$ENV_API_URL/rest/user
    --url-query select='{"$related":true}'
    --header 'X-QUERY-VIZ: true'
```

This header will return both the query string and its corresponding query parameters.

Similarly, `'X-QUERY-VIZ: false'` can be used to disable the viz. By default, this header is disabled.

{% hint style="danger" %}
IMPORTANT: When query viz is enabled, the queries will still run against your selected environment, and they may modify data in that environment depending on your queries.
{% endhint %}

## Operations

### <mark style="color:green;">Creating Objects</mark>

You can create objects by making a `POST` request to the `/rest/object`, where object is your object’s name. The request body should be a JSON array of objects representing the objects that you are looking to insert.

In this example, we will use a sample schema with a User object and a BlogPost object. A user has many posts, and a post has one user.

#### <mark style="color:purple;">Creating one object</mark> (`CreateInput`)

To create a single user, assuming that we have the sample schema running in an environment, we can issue a POST request to `/rest/user/__one` with the body set to a User object. For example

```
curl -X POST https://$ENV_API_URL/rest/user/__one
    --url-query select='{"$scalars":true}'
    --json '{name: "Admin User", country: "United States"}'
```

The response from this insert request will look like this, which is the object that was inserted:

```
{
  "data": {
    "id": 1,
    "name": "Admin User",
    "country": "United States"
  }
}
```

#### <mark style="color:purple;">Creating multiple objects</mark> (`CreateManyInput`)

To create multiple users, assuming that we have the sample schema running in an environment, we can issue a POST request to `/rest/user` with the body set to an array of User objects. For example:

```
curl -X POST https://$ENV_API_URL/rest/user
    --json '[{name: "User 1", country: "Canada"}, {name: "User 2", country: "United States"}]'
```

The response (`AffectedRowsOutput`) from this insert request will look like this, which is the count of the inserted rows:

```
{
  "data": {
    "count": 2
  }
}
```

{% hint style="info" %}
Currently, related objects cannot be created or associated with the 'root' object using `CreateManyInput`. To achieve this, it is necessary to use `CreateInput`.
{% endhint %}

#### <mark style="color:purple;">Creating objects with relations</mark>

{% hint style="info" %}
Currently, Neurelo for MongoDB does not directly support the creation of objects with relations. However, you can create inner objects (which are equivalent to embedded documents, meaning documents nested within another document) or use references to accommodate your data modeling needs. Refer to the [Modeling Relationships for MongoDB with Inner Objects and References section](#modeling-relationships-for-mongodb-with-inner-objects-and-references) for more information.
{% endhint %}

When creating a single object, you can create or connect related object in the same transaction.

On an object with a has one relationship to another object, you can use the `create` input to create a new related object automatically associated with the 'root' object. Alternatively, you can use the `connect` input to link an existing related object to the 'root' object. When using `connect`, an error will be thrown if the linked object is not found. To address this, use `connectOrCreate`, which links an existing related object to the 'root' object or creates a new related object if it doesn't exist.

On an object with a has many relationship to another object, you can also utilize `create`, `connect`, and `connectOrCreate`. Additionally, you can use `createMany` to create many related objects.

#### `create`

To demonstrate creating a root object and its related object, we will use a sample schema with a User object and a BlogPost object. A user has many posts, and a post has one user.

```
curl -X POST https://$ENV_API_URL/rest/user/__one
    --url-query select='{ "$scalars": true, "posts": { "$scalars": true }}'
    --json '{name: "Admin User", country: "United States", posts: { create: [{ title: "Post Title" }] }}'
```

The response from this insert request will look like this, which is the inserted object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User",
    "posts": [
      {
        "id": 1,
        "title": "Post Title"
      }
    ]
  }
}
```

#### `connect`

To create a root object and link it with an existing related object in a has many relationship, assuming that we have the sample schema running in an environment, we can use the `connect` input.

```
curl -X POST https://$ENV_API_URL/rest/user/__one
    --url-query select='{ "$scalars": true, "posts": { "$scalars": true }}'
    --json '{name: "User 1", country: "Canada", posts: { connect: [{ id: 2 }] }}'
```

The response from this insert request will look like this, which is the inserted object(s):

```
{
  "data": {
    "id": 1,
    "name": "User 1",
    "country": "Canada",
    "posts": [
      {
        "id": 2,
        "title": "My Trip to Hawaii"
      }
    ]
  }
}
```

In the above example, the Post with an ID of 2 previously existed and is now being associated with a relationship with the new root object.

#### `connectOrCreate`

To create a root object and link it with an existing related object or create a new related object if it doesn't exist (when the root and related object are in a has many relationship), assuming that we have the sample schema running in an environment, we can use the `connectOrCreate` input. For example,

```
curl -X POST https://$ENV_API_URL/rest/user/__one
    --url-query select='{ "$scalars": true, "posts": { "$scalars": true }}'
    --json '{name: "User 1", country: "Canada", posts: { connectOrCreate: [{ create: {"title": "My thoughts on Wonderwall by Oasis"}, where: {"id": 30} }] }}'
```

The response from this insert request will look like this, which is the inserted object(s):

```
{
  "data": {
    "id": 1,
    "name": "User 1",
    "country": "Canada",
    "posts": [
      {
        "id": 3,
        "title": "My thoughts on Oasis' Wonderwall"
      }
    ]
  }
}
```

In the above example, by observing the Post's ID, we can conclude that the ID 30 was not found in the Post object. As a result, a new object was created.

#### `createMany`

To create a root object and link it with many related objects in a has many relationship, assuming that we have the sample schema running in an environment, we can use the `createMany` input.

```
curl -X POST https://$ENV_API_URL/rest/user/__one
    --url-query select='{ "$scalars": true, "posts": { "$scalars": true }}'
    --json '{name: "User 1", country: "United States", posts: { createMany: [{"title": "Watching a rooftop concert"}, {"title": "How to buy concert tickets?"}] }}'
```

The response from this insert request will look like this, which is the inserted object(s):

```
{
  "data": {
    "id": 1,
    "name": "User 1",
    "country": "United States",
    "posts": [
      {
        "id": 1,
        "title": "Watching a rooftop concert"
      },
      {
        "id": 2,
        "title": "How to buy concert tickets?"
      }
    ]
  }
}
```

Moreover, to prevent the insertion of nested records with unique fields or identifiers that already exist, we can use `skipDuplicates`. For example:

```
curl -X POST https://$ENV_API_URL/rest/user/__one
    --url-query select='{ "$scalars": true, "posts": { "$scalars": true }}'
    --json '{name: "Admin User", country: "Canada", posts: {createMany: {data: [{id: 3, name: "Post 1"}, {id: 3, name: "Post 2"}], skipDuplicates: true}}}'
```

The response from this insert request will look like this, which is the inserted object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User",
    "country": "Canada",
    "posts": [
      {
        "id": 3,
        "title": "Post 1"
      }
    ]
  }
}
```

In the above example, as Post IDs were same, the second nested record was prevented from being inserted.

{% hint style="info" %}
Currently, `skipDuplicates` is not supported for MongoDB.
{% endhint %}

### <mark style="color:green;">Retrieving Objects</mark>

You can retrieve objects by making a `GET` request to the `/rest/object`, where object is your object’s name. By default, this endpoint will return all objects, you can utilize the parameters described above to filter and limit your results.

In this example, we will use a sample schema with a User object and a BlogPost object. A user has many posts, and a BlogPost has one user. A user has a relationship property to posts called `posts` and the post has a relationship property to users called `author`.

#### <mark style="color:purple;">Retrieving unique object</mark>

To retrieve a unique user, assuming that we have the sample schema running in an environment, we can issue a GET request to `/rest/user/{{userId}}`. For example:

```
curl https://$ENV_API_URL/rest/user/1
```

The response from this request will look like this, which is the retrieved object:

```
{
  "data": {
    "id": 1,
    "name": "User 1",
    "country": "Canada"
  }
}
```

#### <mark style="color:purple;">Retrieving all objects</mark>

To retrieve all users, assuming that we have the sample schema running in an environment, we can issue a GET request to `/rest/user`. For example:

```
curl https://$ENV_API_URL/rest/user
```

The response from this request will look like this, which is an array of the retrieved objects:

```
{
  "data": [
    {
      "id": 1,
      "name": "User 1",
      "country": "Canada"
    },
    {
      "id": 2,
      "name": "User 2",
      "country": "United States"
    }
  ]
}
```

#### <mark style="color:purple;">Filtering for specific objects</mark>

To filter specific objects, we can utilize the `filter` query parameter. For complete documentation of all the options available to you with the query parameter, take a look at the `filter` parameter documentation below.

To filter all specific objects, assuming that we have the sample schema running in an environment, we can issue a GET request to `/rest/user` with the filter parameter specified. For example:

```
curl https://$ENV_API_URL/rest/user
    --url-query filter='{"country":{"contains":"United"}}'
```

The response from this request will look like this, which is an array of the retrieved objects:

```
{
  "data": [
    {
      "name": "User 2",
      "country": "United States"
    }
  ]
}
```

#### <mark style="color:purple;">Retrieving all related objects</mark>

To retrieve all related objects, we can utilize the `select` query parameter along with the `$related` parameter. Furthermore, to retrieve all objects, `$scalars` parameter can be used. When `$scalars` and `$related` is used in conjunction, all the retrieved objects and their related objects can be queried. For a complete documentation of all the options available to you with the query parameter, take a look at the `select` parameter documentation below.

To retrieve all users with their posts, assuming that we have the sample schema running in an environment, we can issue a GET request to `rest/user` with the select parameter specified. For example:

```
curl https://$ENV_API_URL/rest/user
    --url-query select='{"$scalars":true, "$related":true}'
```

The response from this request will look like this, which is an array of the retrieved objects and their related objects:

```
{
  "data": [
    {
      "name": "Admin User",
      "country": "United States",
      "posts": [
        {
          "name": "My Trip to Egypt",
          "words": 1200
        },
        {
          "name": "My Trip to Canada",
          "words": 800
        }
      ]
    }
  ]
}
```

#### <mark style="color:purple;">Retrieving specific related objects</mark>

To retrieve specific related objects, we can utilize the `select` query parameter and manually specify the objects. For a complete documentation of all the options available to you with the query parameter, take a look at the `select` parameter documentation below.

To retrieve all the users and their post names, assuming that we have the sample schema running in an environment, we can issue a GET request to `rest/user` with the select parameter specified. For example:

```
curl https://$ENV_API_URL/rest/user
    --url-query select='{"$scalars":true, "posts": {"name": true}}'
```

The response from this request will look like this, which is an array of the retrieved objects and their specific related object:

```
{
  "data": [
    {
      "name": "Admin User",
      "country": "United States",
      "posts": [
        {
          "name": "My Trip to Egypt"
        },
        {
          "name": "My Trip to Canada"
        }
      ]
    }
  ]
}
```

#### <mark style="color:purple;">Retrieving n-levels of related objects</mark>

To retrieve n-levels of related objects, we can utilize the `select` query parameter and manually specify the deeply-nested related objects. For a complete documentation of all the options available to you with the query parameter, take a look at the `select` parameter documentation below.

Assume that in our sample schema, there is a new object Activity, such that each post has many activities. A post has a relationship property to activities called `activity`.

To retrieve all the users, their post names, and activities on each post, assuming that we have the sample schema running in an environment, we can issue a GET request to `rest/user` with the select parameter specified. For example:

```
curl https://$ENV_API_URL/rest/user
    --url-query select='{"$scalars":true, "posts": {"name": true, "activity": true}}'
```

The response from this request will look like this, which is an array of the retrieved objects and their specific related object:

```
{
  "data": [
    {
      "name": "Admin User",
      "country": "United States",
      "posts": [
        {
          "name": "My Trip to Egypt",
          "activity": [
            {
              "name": "User 123",
              "action": "Like"
            },
            {
              "name": "User 234",
              "action": "Bookmark"
            }
          ]
        },
        {
          "name": "My Trip to Canada",
          "activity": [
            {
              "name": "User 345",
              "action": "Like"
            }
          ]
        }
      ]
    }
  ]
}
```

### <mark style="color:green;">Updating Objects</mark>

You can update objects by making a `PATCH` request to the `/rest/object`, where object is your object’s name. The request body should be a JSON object with the properties that you are looking to update, and you can use the `filter` parameter to apply your desired condition to the operation.

#### <mark style="color:purple;">Updating unique object</mark> (`UpdateInput`)

To update a unique user, assuming that we have the sample schema running in an environment, we can issue a PATCH request to `/rest/user/{{userId}}`. For example:

```
curl -X PATCH https://$ENV_API_URL/rest/user/1
      --json '{name: "Admin User 1"}'
```

The response from this request will look like this, which is the updated object:

```
{
  "data": {
    "id": 3,
    "name": "Admin User 1",
    "country": "Canada"
  }
}
```

#### <mark style="color:purple;">Updating multiple objects</mark> (`UpdateManyInput`)

To update multiple users, assuming that we have the sample schema running in an environment, we can issue a PATCH request to `/rest/user`. For example:

```
curl -X PATCH https://$ENV_API_URL/rest/user
    --url-query filter='{"country":{"contains":"United"}}'
    --json '{name: "Admin User 1"}'
```

The response (`AffectedRowsOutput`) from this update request will look like this, which is the count of the updated rows:

```
{
  "data": {
    "count": 1
  }
}
```

#### <mark style="color:purple;">Updating scalars using special operations</mark>

#### `increment`, `decrement`, `multiply`, `divide`

When using the `integer` type for a property, the `UpdateInput` and `UpdateManyInput` provides basic arithmetic capabilities through `increment`, `decrement`, `multiply`, and `divide`. The `increment` operation increases the specific property by a given number, while `decrement` decreases it. Similarly, `multiply` and `divide` multiply or divide the property value by a specified number. This functionality proves useful by eliminating the need for an application-level read before a write call. An example of this is as follows:

```
curl -X PATCH https://$ENV_API_URL/rest/post/1
      --json '{name: "My updated .bashrc file", words: {increment: 30}}'
```

The response from this request will look like this, which is the updated object:

```
{
  "data": {
    "id": 1,
    "name": "My updated .bashrc file",
    "words": 350
  }
}
```

#### `push`

When using the `array` type for a property, the `UpdateInput` and `UpdateManyInput` provides a `push` operation. This inserts a value or array of values at the end of the array. If the value is null, it would initialize the array with the value(s) provided. For example,

```
curl -X PATCH https://$ENV_API_URL/rest/post/1
      --json '{name: "My updated .bashrc file", tags: {push: ["alias"]}}'
```

The response from this request will look like this, which is the updated object:

```
{
  "data": {
    "id": 1,
    "name": "My updated .bashrc file",
    "tags": ["termcolor", "alias"]
  }
}
```

#### <mark style="color:purple;">Updating with relations</mark>

{% hint style="info" %}
Currently, Neurelo for MongoDB does not directly support the updation of objects with relations. However, you can update inner objects (which are equivalent to embedded documents, meaning documents nested within another document) or use references to accommodate your data modeling needs. Refer to the [Modeling Relationships for MongoDB with Inner Objects and References section](#modeling-relationships-for-mongodb-with-inner-objects-and-references) for more information.
{% endhint %}

When updating a single object, you can create, update, disconnect or delete related object in the same transaction.

On an object with a has one relationship to another object, you can use the `update` input to update a related object automatically associated with the 'root' object. Alternatively, you can use the `disconnect` input to unlink an existing related object with the 'root' object. When using `update`, an error will be thrown if the linked object is not found. To address this, use `upsert`, which updates an existing related object to the 'root' object or creates a new related object if it doesn't exist. You can also use `delete` input to delete an existing related object.

The `connect`, `connectOrCreate`, and `create` inputs (as explained in the Creating objects with relations section) are also supported here.

On an object with a has many relationship to another object, you can also utilize `create`, `connect`, `connectOrCreate`, `update`, `upsert`, `delete`, and `disconnect` inputs. Additionally, you can use `createMany`, `updateMany`, and `deleteMany` to create, update, and delete many related objects, respectively.

`createMany` is explained in the Creating objects with relations section.

#### `update`

To demonstrate updating a root object and its related object, we will use a sample schema with a User object and a BlogPost object. A user has many posts, and a post has one user.

```
curl -X PATCH https://$ENV_API_URL/rest/user/1
    --url-query select='{ "$scalars": true, "posts": { "$scalars": true }}'
    --json '{name: "Admin User 1", posts: { update: [{ where: {id: 2}, data: {name: "My system configuration" } }] } }'
```

The response from this update request will look like this, which shows the updated object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User 1",
    "posts": [
      {
        "id": 1,
        "name": "Test"
      },
      {
        "id": 2,
        "name": "My system configuration"
      }
    ]
  }
}
```

In the above example, the Post with an ID of 2 previously existed and is now being updated along with the name of the user.

#### `upsert`

To update a root object and update its corresponding related object or create a new related object if it doesn't exist (when the root and related object are in a has many relationship), assuming that we have the sample schema running in an environment, we can use the `upsert` input. For example,

```
curl -X PATCH https://$ENV_API_URL/rest/user/1
    --url-query select='{ "$scalars": true, "posts": { "$scalars": true }}'
    --json '{name: "Admin User 1", posts: { upsert: { where: {"id": 2}, update: {name: "Hardware Info" }, create: {name: "Hardware Info"} } } }'
```

The response from this upsert request will look like this, which is the upsert object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User 1",
    "posts": [
      {
        "id": 1,
        "name": "Test"
      },
      {
        "id": 2,
        "name": "Hardware Info"
      }
    ]
  }
}
```

#### `disconnect`

To unlink an existing related object with the 'root' object (when the root and related object are in a has many relationship), assuming that we have the sample schema running in an environment, we can use the `disconnect` input. For example,

```
curl -X PATCH https://$ENV_API_URL/rest/user/
    --url-query select='{ "$scalars": true, "posts": { "$scalars": true }}'
    --json '{name: "Admin User 1", posts: { disconnect: { id: 2 } } }'
```

The response from this request will look like this, which is the updated object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User 1",
    "posts": [
      {
        "id": 1,
        "name": "Test"
      }
    ]
  }
}
```

In the above example, the Post with an ID of 2 previously existed and still exists, but it is now being unlinked with respect to the 'root' object. Furthermore, the name of the user also gets updated.

#### `delete`

To delete an existing related object asccociated with a 'root' object (when the root and related object are in a has many relationship), assuming that we have the sample schema running in an environment, we can use the `delete` input. For example,

```
curl -X PATCH https://$ENV_API_URL/rest/user/
    --url-query select='{ "$scalars": true, "posts": { "$scalars": true }}'
    --json '{name: "Admin User 1", posts: { delete: { id: 2 } } }'
```

The response from this request will look like this, which is the updated object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User 1",
    "posts": [
      {
        "id": 1,
        "name": "Test"
      }
    ]
  }
}
```

In the above example, the Post with an ID of 2 is now deleted. Furthermore, the name of the user also gets updated.

#### `updateMany`

To update a root object and its many related objects in a has many relationship, assuming that we have the sample schema running in an environment, we can use the `updateMany` input.

```
curl -X PATCH https://$ENV_API_URL/rest/user/
    --url-query select='{ "$scalars": true, "posts": { "$scalars": true }}'
    --json '{name: "Admin User 1", posts: {updateMany: [{where: {id: 1}, data: {name: "Test Blog"}}, {where: {id: 2}, data: {name: "Hardware Info Blog"}}]}}'
```

The response from this updateMany request will look like this, which is the updated object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User 1",
    "posts": [
      {
        "id": 1,
        "name": "Test Blog"
      },
      {
        "id": 2,
        "name": "Hardware Info Blog"
      }
    ]
  }
}
```

#### `deleteMany`

To update a root object and delete its many related objects in a has many relationship, assuming that we have the sample schema running in an environment, we can use the `deleteMany` input.

```
curl -X PATCH https://$ENV_API_URL/rest/user/
    --url-query select='{ "$scalars": true, "posts": { "$scalars": true }}'
    --json '{name: "Admin User Empty", posts: {deleteMany: [{id: 1}, {id: 2}]}}'
```

The response from this deleteMany request will look like this, which is the deleted object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User Empty",
    "posts": []
  }
}
```

### <mark style="color:green;">Deleting Objects</mark>

You can delete objects by making a `DELETE` request to the `/rest/object`, where object is your object’s name. You can use the `filter` parameter to apply your desired condition to the operation.

In this example, we will use a sample schema with a User object.

#### <mark style="color:purple;">Delete unique object</mark>

To delete a unique user, assuming that we have the sample schema running in an environment, we can issue a DELETE request to `/rest/user/{{userId}}`. For example:

```
curl -X DELETE https://$ENV_API_URL/rest/user/1
```

The response from this request will look like this, which is the deleted object:

```
{
  "data": {
    "id": 1,
    "name": "User 1",
    "country": "Canada"
  }
}
```

#### <mark style="color:purple;">Delete all objects</mark>

To delete all users, assuming that we have the sample schema running in an environment, we can issue a DELETE request to `/rest/user`. For example:

```
curl -X DELETE https://$ENV_API_URL/rest/user
```

The response from this request will look like this, which is the count of the deleted object(s):

```
{
  "data": {
    "count": 1
  }
}
```

#### <mark style="color:purple;">Delete specific objects</mark>

To delete specific objects, we can utilize the `filter` query parameter. For complete documentation of all the options available to you with the query parameter, take a look at the `filter` parameter documentation below.

To delete all specific Users, assuming that we have the sample schema running in an environment, we can issue a DELETE request to `/rest/user` with the filter parameter specified. For example:

```
curl -X DELETE https://$ENV_API_URL/rest/user
      --url-query filter="{\"name\":{\"contains\":\"Admin\"}}"
```

The response from this request will look like this, which is the count of the deleted object(s):

```
{
  "data": {
    "count": 1
  }
}
```

### <mark style="color:green;">Aggregating Objects</mark>

You can aggregate objects by making a `GET` request to the `/rest/object/__aggregate`, where object is your object’s name. The `select` query parameter is required to specify the fields to be aggregated. The following aggregate functions are supported: `_count`, `_sum`, `_avg`, `_min`, and `_max`.

In this example, we will use a sample schema with a Post object.

#### <mark style="color:purple;">Aggregating specific objects</mark>

To aggregate specific objects, we can utilize the `select` query parameter. For a complete documentation of all the options available to you with the query parameter, take a look at the `select` parameter documentation below.

To average specific objects, assuming that we have the sample schema running in an environment, we can issue a GET request to `/rest/post/__aggregate` with the `_avg` query option specified for the `select` query parameter. This query option takes an array of fields to be aggregated. For example:

```
curl https://$ENV_API_URL/rest/post/__aggregate
    --url-query select='{"_avg": ["words"]}'
```

The response (`AggregateOutput`) from this request will look like this, which contains the aggregated value:

```
{
  "data": {
    "_avg": {
      "words": 1000.0
    }
  }
}
```

#### <mark style="color:purple;">Aggregating all objects</mark>

Presently, only `_count` option supports aggregating all objects.

To count all objects, assuming that we have the sample schema running in an environment, we can issue a GET request to `/rest/post/__aggregate` with the `_count` query option and `_all` value specified for the `select` query parameter. For example:

```
curl https://$ENV_API_URL/rest/post/__aggregate
    --url-query select='{"_count": ["_all"]}'
```

The response (`AggregateOutput`) from this request will look like this, which contains the aggregated value:

```
{
  "data": {
    "_count": {
      "_all": 2
    }
  }
}
```

### <mark style="color:green;">Grouping Objects</mark>

In this example, we will use a sample schema with a User object.

To group by specific fields, we can utilize the `select` and `group_by` query parameters. For a complete documentation of all the options available to you with the query parameter, take a look at the `select` and `group_by` parameter documentation below.

For an object, you can group records by one or more fields, by making a `GET` request to the `/rest/object/__groupBy` with the `select` and `group_by` parameters specified. For example, to count the number of users by country:

```
curl https://$ENV_API_URL/rest/post/__groupBy
    --url-query group_by='["country"]'
    --url-query select='{"country": true, "_count": ["id"]}'
```

The response from this request will look like this, which is the grouped and aggregated object(s):

```
{
  "data": [
    {
      "country": "United States",
      "_count": {
        "id": 1
      }
    },
    {
      "country": "Canada",
      "_count": {
        "id": 1
      }
    }
  ]
}
```

#### <mark style="color:purple;">Group By with Filtering</mark>

To filter the fields before grouping, we can utilize the `filter` query parameter. For a complete documentation of all the options available to you with the query parameter, take a look at the `filter` parameter documentation below.

For example,

```
curl https://$ENV_API_URL/rest/post/__groupBy
    --url-query group_by='["country"]'
    --url-query select='{"country": true, "_count": ["id"]}'
    --url-query filter='{"country": {"startsWith": "C"}}'
```

The response from this request will look like this, which is the grouped and aggregated object:

```
{
  "data": [
    {
      "country": "Canada",
      "_count": {
        "id": 1
      }
    }
  ]
}
```

To filter the groups by aggregate functions, we can utilize the `having` query parameter. For a complete documentation of all the options available to you with the query parameter, take a look at the `having` parameter documentation below.

For example,

```
curl https://$ENV_API_URL/rest/post/__groupBy
    --url-query group_by='["country"]'
    --url-query select='{"country": true, "_count": ["id"]}'
    --url-query having='{"id": {"_count": {"lte": 2}}}'
```

The response from this request will look like this, which is the grouped and aggregated object(s):

```
{
  "data": [
    {
      "country": "United States",
      "_count": {
        "id": 1
      }
    },
    {
      "country": "Canada",
      "_count": {
        "id": 1
      }
    }
  ]
}
```

## Parameters

In this section, we’ll take a look at some parameters that apply to many different operations. Availability of each parameter is dependent on the operation being performed, for example, the `filter` parameter is not available on Insert operations.

Once you are familiar with these parameters, we hope that utilizing individual operations on your objects comes naturally and will not require continous referral to the generated reference documentation.

### <mark style="color:green;">`filter`</mark> <mark style="color:green;"></mark><mark style="color:green;">(</mark><mark style="color:green;">`WhereInput`</mark><mark style="color:green;">)</mark>

The filter parameter allows you to add conditions to your query. This parameter can be used when retrieving objects, as well as when updating objects where it will act as the condition on which objects are updated.

#### <mark style="color:purple;">Filtering with Scalars</mark>

Each scalar has it’s own set of operations that can be performed to assert a condition, for example, an integer has the following operators available to it: `equals`, `not`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`. With the exception of `in` and `notIn`, all of these operators will accept the matching scalar, `in` and `notIn` will take an array of the matching scalar.

Here is a list of all available operators: `equals`, `not`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `contains`, `startsWith`, `endsWith`, and `search`. The availiblity of these is dependant on the scalar type, for example, you cannot utilize the `gt` operator on a string. However, `search` is specific to strings.

A filter condition for a given object includes all of the scalars present on the object with their respective scalar filter type. To construct a filter condition utilizing only an object’s scalar properties, you can use the name of the property as the key, and then a filter object for that specific scalar type.

Here is a more comprehensive overview of these operators:

| Operator            | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Example                                                                                                                                                                                                                                                                                         |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| equals              | Filter for field values equal to a specific value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                | To filter when `age` equals 21, `{ "age": { "equals": 21 } }`                                                                                                                                                                                                                                   |
| lt/lte              | Filter for field values "less than / less than or equal to" a specific value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | To filter when `age` is less than 21, `{ "age": { "lt": 21 } }`                                                                                                                                                                                                                                 |
| gt/gte              | Filter for field values "greater than / greater than or equal to" a specific value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               | To filter when `age` is greater than or equal to 30, `{ "age": { "gte": 30 } }`                                                                                                                                                                                                                 |
| not                 | Filters when field value does not equal a specific value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         | To filter records that have all ids except `100`, `{"id": {"not": 100}}`                                                                                                                                                                                                                        |
| in/notIn            | Checks if a field value exists / does not exist in a list, and filters accordingly.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              | To filter records having ids as either `1`, `3` or `6`, `{ "id": { "in": [1, 3, 6] } }`                                                                                                                                                                                                         |
| startsWith/endsWith | Filter when a specific value is at the start or end of a field value. Case-sensitive by default. `_` wildcard can be used to match one or more characters. `$` wildcard can be used to match zero or more characters.                                                                                                                                                                                                                                                                                                                                                                                                            | To filter names that start with "Ron" (case-insensitive), `{"name": {"startsWith": "Ron", "mode": "insensitive"} }`. To filter names that start with "R", followed by one or more characters, and then "d", `{"name": {"startsWith": "R_d"} }`. This matches names such as "Roland" and "Rudd". |
| contains            | Filters when a specific value is contained in a field value. Case-sensitive by default. `_` wildcard can be used to match one or more characters. `$` wildcard can be used to match zero or more characters.                                                                                                                                                                                                                                                                                                                                                                                                                     | To filter country names that contain the word "United", `{"country": {"contains": "United" } }`                                                                                                                                                                                                 |
| search              | Filters using full-text search capabilities. This operator is specific to strings and currently, it is not supported with MongoDB. For querying, PostgreSQL and MySQL's native full-text search capabilities are leveraged. For example, in Postgres, `&` can be used to perform a boolean AND on two strings. Similarly, `\|` and `!` can be used to perform boolean OR and boolean NOT, respectively. For MySQL, `+` and `-` are used as boolean AND and boolean NOT, respectively. Boolean OR in MySQL is represented using no operators; for example, `Tomato Orange` would check if the text contains `Tomato` or `Orange`. | In PostgreSQL, to filter records with the engine as Firefox or Chrome, use `{"engine": {"search": "Firefox \| Chrome"}}`. In MySQL, to filter records with Firefox but not Chrome in the report, use `{"report": {"search": "+Firefox -Chrome"}}`.                                              |

#### <mark style="color:purple;">Combining conditions</mark>

When you add conditions to a filter object, you are asserting that all of the listed conditions must evaluate to true for an object to be returned, but you are also able to further customize your query’s condition by utilizing the `AND`, `OR`, and `NOT` properties. All of these properties accept an array of the object’s filter type, allowing you to nest and compose different filtering conditions to construct your query.

Here is a more comprehensive overview of these operators:

| Operator | Description                                                  | Example                                                                                                                                                                                                                                                                                                                                                                                 |
| -------- | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| OR       | Filters for field values when one or more conditions is true | To filter names starting with either "A" or "B", `{"OR": [{"name": {"startsWith": "A"}}, {"name": {"startsWith": "B"}}]}`. Furthermore, to filter names starting with "A" or ending with "n", `{OR: [{"name": {"startsWith": "A"}}, {"name": "endsWith": "n"}]}`.                                                                                                                       |
| AND      | Filters for field values when all conditions are true        | To filter for first names starting with "A" and last names ending with "n", `{"AND": [{"firstName": {"startsWith": "A"}}, {"lastName": {"endsWith": "n"}}]}`. Furthermore, to filter names starting with "B" and ending with "n", we can use operators such as `startsWith` and `endsWith` in a single object itself, like `{"AND": [{"name": {"startsWith": "B", "endsWith": "n"}}]}`. |
| NOT      | Filters for field values when all the conditions are false   | To filter for names that are not "Alan" and not "George", `{"NOT": [{"name": {"equals": "Alan"}}, {"name": {"equals": "George"}}]}`. Furthermore, to filter names not starting with "C" and not ending with "n", we can use operators such as `startsWith` and `endsWith` in a single object itself, like `{"NOT": [{"name": {"startsWith": "C", "endsWith": "n"}}]}`.                  |

Note on Scope of Logical operators:

* Implicit AND: Combining conditions within one object, `{"name": {"startsWith": "A", "endsWith": "n"}}`, uses an implicit `AND` logic, meaning all conditions must be met.
* Explicit Logical Operators: Using `OR`, `AND`, or `NOT` to combine multiple conditions, such as `{"OR": [ {...}, {...} ]}`, processes each condition in its own scope before applying the logical operator. This structure allows for complex filtering, evaluating from the inner-most conditions outwards.

Furthermore, you can combine these operators to do more powerful filtering. For example,

* `NOT` and `AND`: To filter for names that do no start with "A" and end with "n", `{"NOT": {"AND": [{"name": {"startsWith": "A"}}, {"name": {"endsWith": "n"}}]}}`.
* `OR` and `AND`: To filter for ids that are between 0 to 10 or 30 to 40, `{"OR": [{"AND": [{"id": {"gte": 0}}, {"id": {"lte": 10}}]}, {"AND": [{"id": {"gte": 30}}, {"id": {"lte": 40}}]}]}`.

#### <mark style="color:purple;">Filtering with List</mark>

You can use the following operators to perform filtering with lists: `has`, `hasSome`, `hasEvery`, and `isEmpty`.

Additionally, you can employ the `equals` operator introduced earlier.

Here is a more comprehensive overview of these operators:

| Operator | Description                                                             | Example                                                                                                                                              |
| -------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| has      | Filters for lists where a given value exists.                           | To filter when `Canada` is in a `locations` list, `{"locations": {"has": "Canada"}}`                                                                 |
| hasSome  | Filters for lists where at least one value from the search list exists. | To filter when `Canada` or `United States` are in a `locations` list, `{"locations": {"hasSome": ["Canada", "United States"]}}`                      |
| hasEvery | Filters for lists where all values from the search list exists.         | To filter when `Canada`, `United States`, and `Spain` are in a `locations` list, `{"locations": {"hasEvery": ["Canada", "United States", "Spain"]}}` |
| isEmpty  | Filters for empty lists.                                                | To filter for empty `locations` list, `{"locations": {"isEmpty": true}}`. Similarly, to filter for non-empty lists, use `{"isEmpty": false}`.        |

#### <mark style="color:purple;">Filtering with JSON</mark>

You can use the following operators to perform JSON filtering: `array_starts_with`, `array_ends_with`, `array_contains`, `string_starts_with`, `string_ends_with`, and `string_contains`.

Additionally, you can employ operators introduced earlier, such as `equals`, `gt`, `gte`, `lt`, `lte`, and `not`.

To filter a specific part of the JSON object, each of these operators requires a specified `path`. For example, consider a JSON object like `{"Crops": {"Fruits": {"Organic": ["Orange", "Mango", "Banana"], "Non-organic": ["Apple", "Melon"]}}}`. In Postgres, the path `Crops -> Fruits -> Organic` can be represented as `["Crops", "Fruits", "Organic"]`. Similarly, for MySQL, it can be represented as `'$.Crops.Fruits.Organic'`.

Here is a more comprehensive overview of these operators (all the paths are specific to Postgres):

| Operator             | Description                                                                                     | Example                                                                                                                                                                                               |
| -------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| array\_starts\_with  | Filters for JSON objects where a specified path has a list that begins with a specific value.   | To filter when the list at `["Fruits", "Organic"]` path starts with `Orange`, `{"Crops": {"path": ["Fruits", "Organic"], "array_starts_with": "Orange"}}`                                             |
| array\_ends\_with    | Filters for JSON objects where a specified path has a list that ends with a specific value.     | To filter when the list at `["Fruits", "Organic"]` path ends with `Apple` , `{"Crops": {"path": ["Fruits", "Organic"], "array_starts_with": "Apple"}}`                                                |
| array\_contains      | Filters for JSON objects where a specified path has a list that contains a specific value.      | To filter when the list at `["Schedule", "Heathrow"]` path contains 9 , `{"Misc": {"path": ["Schedule", "Heathrow"], "array_contains": 9}}`                                                           |
| string\_starts\_with | Filters for JSON objects where a specified path has a string that begins with a specific value. | To filter when the string at `["Premium Customers", "NYC", "George"]` path starts with `Q2F0cw==` , `{"IDs": {"path": ["Premium Customers", "NYC", "George"], "string_starts_with": "Q2F0cw=="}}`     |
| string\_ends\_with   | Filters for JSON objects where a specified path has a string that ends with a specific value.   | To filter when the string at `["Premium Customers", "NYC", "George"]` path ends with `TmV1cmVsbw==` , `{"IDs": {"path": ["Premium Customers", "NYC", "George"], "string_ends_with": "TmV1cmVsbw=="}}` |
| string\_contains     | Filters for JSON objects where a specified path has a string that contains a specific value.    | To filter when the string at `["FullReport", "Browser"]` path contains `Firefox` , `{"Details": {"path": ["FullReport", "Browser"], "string_contains": "Firefox"}}`                                   |

#### <mark style="color:purple;">Filtering with Relations</mark>

You are able to utilize related objects in a condition too, though the manner in which you do so will depend on the type of relationship that this object has with it’s related object.

When a relationship has one of another object, you can utilize the `is` and `isNot` filters to construct conditions on a related object. For example, if we have a Post object, which has one User object, we can create a condition utilizing the User’s objects properties like so: `{ "user": { "is": { "name": { "equals": "George" } } } }`. This filter would return all Post objects where the related User’s name is equal to George.

When a relationship has many of another object, you can utilize the `some`, `every`, and `none` conditions to construct conditions on a set of related objects. For example, if we have a User object that has many Posts, we can create a condition utilizing the Post’s objects properties like so:`{ "posts": "some": [ { "title": { "equal": "Cats" } } ] }`. This will return a list of users where at least one of their posts has the title of “Cats”.

Here is a more comprehensive overview of these operators:

| Operator | Description                                                                                                                                        | Example                                                                                                                                                                 |
| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| is       | Filters a record when related record "is" equal to the filter condition. Can only be used when a relationship has one of another object.           | If every user has one post, to filter when name equals Alan, `{ "user": { "is": { "name": { "equal": "Alan" } } } }`                                                    |
| isNot    | Filters a record when related record "is not" equal to the filter condition. Can only be used when a relationship has one of another object.       | If every user has one post, to filter when name does not start with "A", `{ "user": { "isNot": { "name": { "startsWith": "A" } } } }`                                   |
| some     | Filters a record when related record has "some" filter conditions as true. Can only be used when a relationship has many of another object.        | If a brand has many sauces, to find out brands that have "Paprika" in some of their sauces, `{ "sauces": { "some": [ { "ingr": { "contains": "paprika" } } ] } }`       |
| every    | Filters a record when related record has "every" filter conditions as true. Can only be used when a relationship has many of another object.       | If a brand has many sauces, to find out brands that have "Paprika" in all of their sauces, `{ "sauces": { "every": [ { "ingr": { "contains": "paprika" } } ] } }`       |
| none     | Filters a record when related record has "none" of its filter conditions as true. Can only be used when a relationship has many of another object. | If a brand has many sauces, to find out brands that do not have "Paprika" in any of their sauces, `{ "sauces": { "none": [ { "ingr": { "contains": "paprika" } } ] } }` |

{% hint style="info" %}
You can combine the sections above to construct complex queries.
{% endhint %}

### <mark style="color:green;">`select`</mark> <mark style="color:green;"></mark><mark style="color:green;">(</mark><mark style="color:green;">`SelectInput`</mark><mark style="color:green;">)</mark>

You can use the select parameter to limit the scalars that you request for a specific object, as well as to eagerly retrieve related objects for that object.

If no select parameter is specified in MongoDB, by default all scalars and all inner objects are selected automatically. In Postgres and MySQL, only scalars are selected by default.

To select specific scalars on an object, pass an object with the property key name as the key, and `true` as the value.

To select all scalars on an object, you can utilize the `$scalars` parameter in the select object.

To select all related objects, you can utilize the `$related` parameter in the select object. This will retrieve all direct relationships from the parent object.

To select specific related objects, you can pass in the related objects property name as a key, and `true` as the value.

To further specify which properties of a related object that you want to select, you can pass in an object, with the key being the related property name on the root object, and the value being another `select` type object, allowing you to select the relations scalars, as well as it’s own relations. There is no limit to how far you can nest Select objects to explore relationships.

You can also use `select` to specify the fields to be aggregated (`AggregateInput`). The following aggregate functions are supported: `_count`, `_sum`, `_avg`, `_min`, and `_max`. For example, if we have a User object that has many posts, to find the maximum number of words amongst those posts, we can use `{"_max": ["words"]}`.

Similarly, you can use `select` (`GroupByInput`) in conjunction with `group_by` option to group records by one or more fields. For a more comprehensive overview, refer to the `group_by` parameter documentation.

### <mark style="color:green;">`order_by`</mark> <mark style="color:green;"></mark><mark style="color:green;">(</mark><mark style="color:green;">`OrderByWithRelationInput`</mark><mark style="color:green;">)</mark>

The `order_by` parameter takes an array of objects, with the following definition:

`{ [key: ScalarName]: "asc" | "desc" }`

You can use any scalar on the object being queried as a key, along with the direction of the sort as the value in the object. We do not support ordering nested fields at this time.

For example, given a sample schema with a User object:

```
curl https://$ENV_API_URL/rest/user?order_by=[{"name": "desc"}]
```

The response from this request will look like this:

```
{
  "data": [
    {
      "id": 2,
      "name": "User 2",
      "country": "United States"
    },
    {
      "id": 1,
      "name": "User 1",
      "country": "Canada"
    }
  ]
}
```

### <mark style="color:green;">`skip`</mark> <mark style="color:green;"></mark><mark style="color:green;">&</mark> <mark style="color:green;"></mark><mark style="color:green;">`take`</mark>

Pagination with Neurelo’s APIs works using the `skip` and `take` options as an implementation of offset based paginaition. You can pass an integer to each option to limit or skip the resulting objects.

For example, given a sample schema with a User object, to skip one record and take the next record:

```
curl https://$ENV_API_URL/rest/user?skip=1&take=1
```

The response from this request will look like this:

```
{
  "data": [
    {
      "id": 1,
      "name": "User 1",
      "country": "Canada"
    }
  ]
}
```

### <mark style="color:green;">`group_by`</mark>

The `group_by` parameter takes an array of field names (`Array`), to specify the fields to group by with.

Note: A `select` parameter needs to be specified alongside `group_by`, such that, every selected scalar field that is not part of an aggregation (`_count`, `_sum`, `_avg`, `_min`, and `_max`) must be included in `group_by` parameter's array of field names.

For example, let us use a sample schema with a Post object,

```
# If the selected scalar fields in select are country and name, then group_by needs to equal ["country", "name"].
curl https://$ENV_API_URL/rest/post/__groupBy
    --url-query select='{"country": true, "name": true, "_count": ["id"]}'
    --url-query group_by='["country", "name"]'
```

The response from this request will look like this:

```
{
  "data": [
    {
      "name": "User 2",
      "country": "United States",
      "_count": {
        "id": 1
      }
    },
    {
      "name": "User 1",
      "country": "Canada",
      "_count": {
        "id": 1
      }
    }
  ]
}
```

#### `having` (`HavingInput`)

`having` parameter is used in conjuction with `group_by` parameter to filter the groups by aggregate functions. It is a special kind of `filter` which accepts all the `filter` options, together with the ability to filter aggregate functions.

To filter by aggregate function, the following definition can be used:

`{ [field: ScalarName]: { [key: aggregateFunction]: filterCondition } }`

Supported aggregate functions are: `_count`, `_sum`, `_avg`, `_min`, and `_max`. filterCondition is the same as a `filter` body and accepts all the `filter` options.

For example, let us use a sample schema with a Post object,

```
curl https://$ENV_API_URL/rest/post/__groupBy
    --url-query group_by='["location"]'
    --url-query select='{"location": true, "_sum": ["num_words"]}'
    --url-query having='{"num_words": {"_sum": {"gte": 1000000}}}'
```

The response from this request will look like this, which is the grouped and aggregated object(s):

```
{
  "data": [
    {
      "location": "United States",
      "_sum": {
        "id": 5179839
      }
    },
    {
      "location": "India",
      "_sum": {
        "id": 3044357
      }
    }
  ]
}
```

Moreover, similar to `filter`, you can use `AND`, `OR`, and `NOT` operators to do more powerful filtering. For example, to filter when the number of words is in the range of 1000 to 10000, you can use `{"OR": [{"id": {"_sum": {"gte": 1000}}}, {"id": {"_sum": {"lte": 10000}}}]}`.

### Modeling Relationships for MongoDB with Inner Objects and References

Currently, Neurelo for MongoDB doesn't support direct manipulation of objects with relations. However, you can work with inner objects (equivalent to embedded documents, i.e., documents nested within another document) or use references to model such relationships.

To decide which data modeling approach suits your needs best, refer to our guide on [how to work with embedded documents and references in MongoDB](/guides/how-to-work-with-embedded-documents-and-references-in-mongodb).

In summary, inner objects enhance read performance by reducing database queries and ensuring atomic updates within a single document. They are optimal for closely related data that is frequently accessed together, remains relatively static, and adheres to the 16MB document size limit. However, they might lead to data redundancy and scalability challenges as your database grows.

On the other hand, references are more suitable for large or frequently changing data. They excel in many-to-many relationships by offering the flexibility to link documents across different collections, preventing data duplication and maintaining database normalization. The trade-off, however, is the need for additional queries to get related data, which could affect your performance.

**Inner Objects**

Neurelo supports the management of inner objects at the schema level. To learn how to create inner objects for your schema, please refer to [the Neurelo Schema Language reference](/neurelo-schema-language-nsl#inner-objects).

Now, assume that will have a sample schema with a User object and an Address inner object. A user **has one** address. For example,

```json
{
  "objects": {
    "user": {
      "properties": {
        "id": {
          "type": "string",
          "sourceName": "_id",
          "sourceType": "ObjectId",
          "default": {
            "function": "auto"
          },
          "identifier": true
        },
        "name": {
          "type": "string"
        },
        "address": {
          "$ref": "#/innerObjects/Address",
          "nullable": true
        }
      }
    }
  },
  "innerObjects": {
    "Address": {
      "properties": {
        "id": {
          "type": "string",
          "sourceType": "ObjectId"
        },
        "street": {
          "type": "string"
        },
        "city": {
          "type": "string"
        },
        "zipcode": {
          "type": "string"
        }
      }
    }
  }
}
```

**Create**

To create a single user with an address, assuming that we have this sample schema running in an environment, we can issue a `POST` request to `/rest/user/__one` with the body set to a User object. For example,

```bash
curl -X POST https://$ENV_API_URL/rest/user/__one
    --url-query select='{ "$scalars": true, "$innerObjects": true}'
    --data '{"name": "Admin User", "address": { "set": { "id": "5ca4bbc7a2dd94ee5816238d", "street": "Diagon Alley", "city": "Nowhere Land", "zipcode": "27000" } }}'
```

Note that, at present, our APIs **do not allow** the user to autogenerate inner object ids, hence we had to manually specify it in the above example. Also notice that we can use `$innerObjects` to `select` all the inner objects without the need to manually specify them.

The response from this insert request will look like this, which is the object that was inserted:

```json
{
  "data": {
    "id": "65eb623e591811da1638040a",
    "name": "Admin User",
    "address": {
      "id": "5ca4bbc7a2dd94ee5816238d",
      "street": "Diagon Alley",
      "city": "Nowhere Land",
      "zipcode": "27000"
    }
  }
}
```

To create multiple users, we can issue a `POST` request to `/rest/user` with the body set to an array of User objects. For example:

```bash
curl -X POST https://$ENV_API_URL/rest/user
    --url-query select='{ "$scalars": true, "$innerObjects": true}'
    --data '[{"name": "Roger Smith", "address": { "set": { "id": "5ca4bbc7a2dd94ee5816238e", "street": "King's Court", "city": "Nashville", "zipcode": "27100" } }}, {"name": "Alan Walkman", "address": { "set": { "id": "5ca4bbc7a2dd94ee5816238f", "street": "King's Court", "city": "Nashville", "zipcode": "27100" } }}]'
```

The response (`AffectedRowsOutput`) from this insert request will look like this, which is the count of the inserted rows:

```json
{
  "data": {
    "count": 2
  }
}
```

**Retrieve**

To retrieve a unique user with its address, assuming that we have the sample schema running in an environment, we can issue a `GET` request to `/rest/user/{{userId}}`. For example:

```bash
curl https://$ENV_API_URL/rest/user/65eb623e591811da1638040a
```

The response from this request will look like this, which is the retrieved object:

```json
{
  "data": {
    "id": "65eb623e591811da1638040a",
    "name": "Admin User",
    "address": {
      "id": "5ca4bbc7a2dd94ee5816238d",
      "street": "Diagon Alley",
      "city": "Nowhere Land",
      "zipcode": "27000"
    }
  }
}
```

Similarly, to retrieve all users along with their addresses, assuming that we have the sample schema running in an environment, we can issue a `GET` request to `/rest/user`. For example:

```bash
curl https://$ENV_API_URL/rest/user
```

The response from this request will look like this, which is an array of the retrieved objects (with their inner objects):

```json
{
  "data": [
    {
      "data": {
        "id": "65eb623e591811da1638040a",
        "name": "Admin User",
        "address": {
          "id": "5ca4bbc7a2dd94ee5816238d",
          "street": "Diagon Alley",
          "city": "Nowhere Land",
          "zipcode": "27000"
        }
      }
    }
  ]
}
```

Note that a `select` with `"$innerObjects": true` is not necessary for retrieving all of the corresponding inner objects.

**Update**

To update users with its address, assuming that we have the sample schema running in an environment, we can issue an `UPDATE` request to `/rest/user/`. For example:

```bash
curl -X PATCH 'https://$ENV_API_URL/rest/user'
--url-query filter='{ "id": { "equals": "65eb623e591811da1638040a" }}'
--data '{
  "address": {
    "update": {
      "city": "Valencia",
      "id": "5ca4bbc7a2dd94ee5816238d",
      "street": "Eixample",
      "zipcode": "960"
    }
  }
}'
```

The response (`AffectedRowsOutput`) from this update request will look like this, which is the count of the updated rows:

```json
{
  "data": {
    "count": 1
  }
}
```

**Delete**

To delete users with its address, assuming that we have the sample schema running in an environment, we can issue an `DELETE` request to `/rest/user/`. For example:

```bash
curl -X DELETE 'https://$ENV_API_URL/rest/user'
--url-query filter='{ "address": { "is": {"id": "5ca4bbc7a2dd94ee5816238d"} }}'
```

The response (`AffectedRowsOutput`) from this delete request will look like this, which is the count of the deleted rows:

```json
{
  "data": {
    "count": 1
  }
}
```

Note that **this will delete both the object and its inner object**. To remove the contents of just the inner object, you can use the `UPDATE` request with an `unset`:

```bash
curl -X UPDATE 'https://$ENV_API_URL/rest/user'
--url-query filter='{ "id": { "equals": "65eb623e591811da1638040a" }}'
--data '{
  "address": {
    "unset": true
  }
}'
```

This approach requires setting the inner object of your schema, specifically the unique ID, to have `nullable` set to `true`.

## API Errors

Errors for the API calls will be presented in a list format so that multiple issues can be communicated at once. Each error object will contain an `error` property that contains the error message and, optionally, a `details` object with more information about the error.

Two types of errors can be returned as a response:

* Validation errors - request is invalid or contains invalid data
* Execution errors - request execution failed

For example, a sample schema and a sample request like:

```json
Schema: 

{
  "objects": {
    "actor": {
      "properties": {
        "actor_id": {
          "type": "integer",
          "identifier": true
        },
        "first_name": {
          "type": "string"
        },
        "last_name": {
          "type": "string"
        },
        "movie_count": {
          "type": "integer"
        }
      }
    }
  }
}
```

```bash
Request: 

curl https://$ENV_API_URL/rest/actor
    --url-query select='{"first_name": true}'
    --url-query filter='{"movie_count": {"gt": "3"}}'
    --url-query aggregate='{"_count": ["first_name", "alias"]}'
    --url-query group_by='["first_name"]'
```

Will generate the following response:

```json
Response: 

{
  "errors": [
    {
      "error": "\"3\" is not of type \"integer\"",
      "details": {
        "in": "params",
        "location": "filter/movie_count/gt"
      }
    },
    {
      "error": "\"alias\" is not one of [\"actor_id\", \"first_name\", \"last_name\", \"movie_count\"]",
      "details": {
        "in": "params",
        "location": "aggregate/_count/1"
      }
    }
  ]
}
```

The above example contains two errors, each with an error message and the specific location of the invalid attribute in the details section. The location parameter contains a JSON path to the attribute that failed the validation and uses “/” as a separator for each part of the path. In the case of the second error, the location contains the number “1”, indicating that the invalid attribute is contained within an array and that the element with index 1 is invalid.


# Examples of Neurelo Auto-Generated REST API endpoints

### Overview

Neurelo auto-generates a rich set of REST API endpoints from your schema for the project.

The API endpoints comprise of -

1. <mark style="color:green;">**GET**</mark> method endpoints to retrieve data
2. <mark style="color:blue;">**POST**</mark> method endpoints to add new data
3. <mark style="color:purple;">**PATCH**</mark> method endpoints to update data
4. <mark style="color:red;">**DELETE**</mark> method endpoints to delete data

{% hint style="info" %}
These endpoints support a rich set of filters, aggregation, sorting, pagination and other operations.
{% endhint %}

{% hint style="info" %}
These endpoints allow you to take action on a single object or across multiple objects in a single call, using any specified references between them (e.g. relationships, embedded documents).
{% endhint %}

The endpoints are reachable at **https\://$ENV\_API\_URL/rest/**

* **$ENV\_API\_URL** can be retrieved from the Neurelo environment in the project you want to use. This path will be different depending on the region where the runners for your environment have been instantiated.
* You will need an api key to use these endpoints.
  * API Keys can be generated within the settings of your Neurelo Environment.
  * An api key needs to be provided in the **X-API-KEY** header for your HTTPs calls and will look something like this

    ```json
    —header 'X-API-KEY: neurelo_9wAFBp854Z5xFw....q3S4++ktfGmelrcQI='
    ```
* You can download the **OpenAPI spec** for your auto-generated endpoints and a **Postman collection** to get you started from the API documentation page.

## Examples

The following pages cover examples for using the auto-generated REST APIs for 3 different sample schemas -&#x20;

1. [Example 1 - Simple "Posts" application](/neurelo-api-reference-rest/examples-of-neurelo-auto-generated-rest-api-endpoints/example-1-simple-posts-application)
2. [Example 2 - "DVD Rentals" application](/neurelo-api-reference-rest/examples-of-neurelo-auto-generated-rest-api-endpoints/example-2-dvd-rentals-application)
3. [Example 3 - "Bookstore" application](/neurelo-api-reference-rest/examples-of-neurelo-auto-generated-rest-api-endpoints/example-3-bookstore-application)
4. [cURL examples for using the APIs](/neurelo-api-reference-rest/examples-of-neurelo-auto-generated-rest-api-endpoints/curl-api-examples)


# Example 1 - Simple “Posts” application

### Schema

This is a simple representative schema for a PostgreSQL datasource, which has 4 objects (tables) - links, posts, topics, users - with relationships between these objects.

* This schema is in the Neurelo Schema Language JSON specification

<details>

<summary>JSON Schema</summary>

```json
{
  "objects": {
    "links": {
      "properties": {
        "id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "link": {
          "type": "string",
          "sourceType": [
            "VarChar",
            500
          ],
          "nullable": true
        },
        "title": {
          "type": "string",
          "sourceType": [
            "VarChar",
            500
          ],
          "nullable": true
        },
        "topic_id": {
          "type": "integer",
          "nullable": true
        },
        "topics": {
          "nullable": true,
          "$ref": "#/objects/topics",
          "relation": {
            "attrKey": [
              "topic_id"
            ],
            "foreignAttrKey": [
              "id"
            ],
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        }
      }
    },
    "posts": {
      "properties": {
        "content": {
          "type": "string",
          "nullable": true
        },
        "id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "title": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        },
        "user_id": {
          "type": "integer",
          "nullable": true
        },
        "users": {
          "nullable": true,
          "$ref": "#/objects/users",
          "relation": {
            "attrKey": [
              "user_id"
            ],
            "foreignAttrKey": [
              "id"
            ],
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        }
      }
    },
    "topics": {
      "properties": {
        "description": {
          "type": "string",
          "nullable": true
        },
        "id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "links": {
          "type": "array",
          "items": {
            "$ref": "#/objects/links"
          }
        },
        "title": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        }
      }
    },
    "users": {
      "properties": {
        "email": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        },
        "first_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            100
          ],
          "nullable": true
        },
        "id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "last_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            100
          ],
          "nullable": true
        },
        "password": {
          "type": "string",
          "sourceType": [
            "VarChar",
            500
          ],
          "nullable": true
        },
        "posts": {
          "type": "array",
          "items": {
            "$ref": "#/objects/posts"
          }
        }
      }
    }
  }
}
```

</details>

### <mark style="color:green;">GET</mark> endpoint examples

* Retrieve all posts

  ```json
  GET https://$ENV_API_URL/rest/posts
  ```
* Retrieve a specific post by id

  ```json
  GET https://$ENV_API_URL/rest/posts/3
  ```

  or

  ```json
  GET https://$ENV_API_URL/rest/posts?filter={"id":3}
  ```
* Retrieve a specific user

  ```json
  GET https://$ENV_API_URL/rest/users?filter={"first_name":"Jane", "last_name":"Doe"}
  ```
* Retrieve the first 5 posts

  ```json
  GET https://$ENV_API_URL/rest/posts?take=5
  ```
* Retrieve all users and their posts

  ```json
  GET https://$ENV_API_URL/rest/users?select={"$scalars": true, "posts": true}
  ```
* Retrieve user with id 3 and all their posts

  ```json
  GET https://$ENV_API_URL/rest/users/3?select={"$scalars": true, "posts": true}
  ```
* Retrieve specific user and all their posts

  ```json
  GET https://$ENV_API_URL/rest/users?select={"$scalars": true, "posts": true}&filter={"first_name":"Jane", "last_name":"Doe"}
  ```

### <mark style="color:blue;">POST</mark> endpoint examples

* Create a new post

  ```json
  POST https://$ENV_API_URL/rest/posts

  {
          "content": "This is my first blog post",
          "title": "My first blog post"
  }
  ```
* Create a new post, a new user, and link them to each other

  ```json
  POST https://$ENV_API_URL/rest/posts

  {
    "content": "New POST",
    "title": "The new post",
    "users": {
      "create": {
        "email": "new-user@example.com",
        "first_name": "new",
        "last_name": "user",
        "password": "password"
      }
    }
  }
  ```
* Create a new user, 3 posts, link the posts to the user AND return the user scalars + related data (the 3 posts we just created)

  ```json
  POST https://$ENV_API_URL/rest/users?select={"$scalars": true, "$related": true}

  {
    "email": "multi-post@example.com",
    "first_name": "multi",
    "last_name": "post",
    "password": "manymanyposts",
    "posts": {
      "createMany": {
        "data": [
          {
              "content": "this is the first one",
              "title": "first one"
          },
          {
              "content": "this is the second one",
              "title": "second one"
          },
          {
              "content": "this is the third one",
              "title": "third one"
          }
        ]
      }
    }
  }
  ```

### <mark style="color:purple;">PATCH</mark> endpoint examples

* Update a post

  ```json
  PATCH https://$ENV_API_URL/rest/posts/7

  {
          "content": "This is my seventh blog post",
          "title": "My seventh blog post"
  }
  ```
* Update a post and its linked user

  ```json
  PATCH https://$ENV_API_URL/rest/posts/1

  {
    "content": "Newest post",
    "title": "The new post (revised)",
    "users": {
      "update": {
        "first_name": "updated",
        "last_name": "name"
      }
    }
  }
  ```

### <mark style="color:red;">DELETE</mark> endpoint examples

* Delete a post

  ```json
  DELETE https://$ENV_API_URL/rest/posts/4
  ```


# Example 2 - "DVD Rentals" application

### Schema

This is a DVD Rentals example database schema from [PostgreSQL Tutorial](https://www.postgresqltutorial.com/postgresql-getting-started/postgresql-sample-database/).

There are 15 tables in the DVD Rental database:

* **actor** – stores actors data including first name and last name.
* **film** – stores film data such as title, release year, length, rating, etc.
* **film\_actor** – stores the relationships between films and actors.
* **category** – stores film’s categories data.
* **film\_category**- stores the relationships between films and categories.
* **store** – contains the store data including manager staff and address.
* **inventory** – stores inventory data.
* **rental** – stores rental data.
* **payment** – stores customer’s payments.
* **staff** – stores staff data.
* **customer** – stores customer data.
* **address** – stores address data for staff and customers
* **city** – stores city names.
* **country** – stores country names.

Here is the ERD of the sample DVD rentals database:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FR6WjaAECIirZFs3Jzmiq%2Fdvd-rental-sample-database-diagram.png?alt=media&amp;token=907bb134-36c9-4377-9eb4-85944dc488b5" alt=""><figcaption></figcaption></figure>

* This is the schema in the Neurelo Schema Language JSON Specification format

<details>

<summary>JSON Schema</summary>

```json
{
  "objects": {
    "actor": {
      "properties": {
        "actor_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "film_actor": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film_actor"
          }
        },
        "first_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "last_name"
          ],
          "sourceName": "idx_actor_last_name"
        }
      ]
    },
    "address": {
      "properties": {
        "address": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ]
        },
        "address2": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ],
          "nullable": true
        },
        "address_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "city": {
          "$ref": "#/objects/city",
          "relation": {
            "attrKey": [
              "city_id"
            ],
            "foreignAttrKey": [
              "city_id"
            ],
            "sourceName": "fk_address_city",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "city_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "customer": {
          "type": "array",
          "items": {
            "$ref": "#/objects/customer"
          }
        },
        "district": {
          "type": "string",
          "sourceType": [
            "VarChar",
            20
          ]
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "phone": {
          "type": "string",
          "sourceType": [
            "VarChar",
            20
          ]
        },
        "postal_code": {
          "type": "string",
          "sourceType": [
            "VarChar",
            10
          ],
          "nullable": true
        },
        "staff": {
          "type": "array",
          "items": {
            "$ref": "#/objects/staff"
          }
        },
        "store": {
          "type": "array",
          "items": {
            "$ref": "#/objects/store"
          }
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "city_id"
          ],
          "sourceName": "idx_fk_city_id"
        }
      ]
    },
    "category": {
      "properties": {
        "category_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "film_category": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film_category"
          }
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            25
          ]
        }
      }
    },
    "city": {
      "properties": {
        "address": {
          "type": "array",
          "items": {
            "$ref": "#/objects/address"
          }
        },
        "city": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ]
        },
        "city_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "country": {
          "$ref": "#/objects/country",
          "relation": {
            "attrKey": [
              "country_id"
            ],
            "foreignAttrKey": [
              "country_id"
            ],
            "sourceName": "fk_city",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "country_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "country_id"
          ],
          "sourceName": "idx_fk_country_id"
        }
      ]
    },
    "country": {
      "properties": {
        "city": {
          "type": "array",
          "items": {
            "$ref": "#/objects/city"
          }
        },
        "country": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ]
        },
        "country_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      }
    },
    "customer": {
      "properties": {
        "active": {
          "type": "integer",
          "nullable": true
        },
        "activebool": {
          "type": "boolean",
          "default": {
            "value": true
          }
        },
        "address": {
          "$ref": "#/objects/address",
          "relation": {
            "attrKey": [
              "address_id"
            ],
            "foreignAttrKey": [
              "address_id"
            ]
          }
        },
        "address_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "create_date": {
          "type": "string",
          "format": "date",
          "sourceType": "Date",
          "default": {
            "function": "dbgenerated",
            "rawDbValue": "('now'::text)::date"
          }
        },
        "customer_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "email": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ],
          "nullable": true
        },
        "first_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          },
          "nullable": true
        },
        "payment": {
          "type": "array",
          "items": {
            "$ref": "#/objects/payment"
          }
        },
        "rental": {
          "type": "array",
          "items": {
            "$ref": "#/objects/rental"
          }
        },
        "store_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "address_id"
          ],
          "sourceName": "idx_fk_address_id"
        },
        {
          "type": "index",
          "property": [
            "store_id"
          ],
          "sourceName": "idx_fk_store_id"
        },
        {
          "type": "index",
          "property": [
            "last_name"
          ],
          "sourceName": "idx_last_name"
        }
      ]
    },
    "film": {
      "properties": {
        "description": {
          "type": "string",
          "nullable": true
        },
        "film_actor": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film_actor"
          }
        },
        "film_category": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film_category"
          }
        },
        "film_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "inventory": {
          "type": "array",
          "items": {
            "$ref": "#/objects/inventory"
          }
        },
        "language": {
          "$ref": "#/objects/language",
          "relation": {
            "attrKey": [
              "language_id"
            ],
            "foreignAttrKey": [
              "language_id"
            ]
          }
        },
        "language_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "length": {
          "type": "integer",
          "sourceType": "SmallInt",
          "nullable": true
        },
        "rating": {
          "default": {
            "value": "G"
          },
          "nullable": true,
          "$ref": "#/enums/mpaa_rating"
        },
        "release_year": {
          "type": "integer",
          "nullable": true
        },
        "rental_duration": {
          "type": "integer",
          "sourceType": "SmallInt",
          "default": {
            "value": 3
          }
        },
        "rental_rate": {
          "type": "string",
          "format": "decimal",
          "sourceType": [
            "Decimal",
            4,
            2
          ],
          "default": {
            "value": "4.99"
          }
        },
        "replacement_cost": {
          "type": "string",
          "format": "decimal",
          "sourceType": [
            "Decimal",
            5,
            2
          ],
          "default": {
            "value": "19.99"
          }
        },
        "special_features": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "title": {
          "type": "string",
          "sourceType": [
            "VarChar",
            255
          ]
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "language_id"
          ],
          "sourceName": "idx_fk_language_id"
        },
        {
          "type": "index",
          "property": [
            "title"
          ],
          "sourceName": "idx_title"
        }
      ]
    },
    "film_actor": {
      "properties": {
        "actor": {
          "$ref": "#/objects/actor",
          "relation": {
            "attrKey": [
              "actor_id"
            ],
            "foreignAttrKey": [
              "actor_id"
            ]
          }
        },
        "actor_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "film": {
          "$ref": "#/objects/film",
          "relation": {
            "attrKey": [
              "film_id"
            ],
            "foreignAttrKey": [
              "film_id"
            ]
          }
        },
        "film_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      },
      "constraints": [
        {
          "type": "identifier",
          "property": [
            "actor_id",
            "film_id"
          ]
        },
        {
          "type": "index",
          "property": [
            "film_id"
          ],
          "sourceName": "idx_fk_film_id"
        }
      ]
    },
    "film_category": {
      "properties": {
        "category": {
          "$ref": "#/objects/category",
          "relation": {
            "attrKey": [
              "category_id"
            ],
            "foreignAttrKey": [
              "category_id"
            ]
          }
        },
        "category_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "film": {
          "$ref": "#/objects/film",
          "relation": {
            "attrKey": [
              "film_id"
            ],
            "foreignAttrKey": [
              "film_id"
            ]
          }
        },
        "film_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      },
      "constraints": [
        {
          "type": "identifier",
          "property": [
            "film_id",
            "category_id"
          ]
        }
      ]
    },
    "inventory": {
      "properties": {
        "film": {
          "$ref": "#/objects/film",
          "relation": {
            "attrKey": [
              "film_id"
            ],
            "foreignAttrKey": [
              "film_id"
            ]
          }
        },
        "film_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "inventory_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "rental": {
          "type": "array",
          "items": {
            "$ref": "#/objects/rental"
          }
        },
        "store_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "store_id",
            "film_id"
          ],
          "sourceName": "idx_store_id_film_id"
        }
      ]
    },
    "language": {
      "properties": {
        "film": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film"
          }
        },
        "language_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "name": {
          "type": "string",
          "sourceType": [
            "Char",
            20
          ]
        }
      }
    },
    "payment": {
      "properties": {
        "amount": {
          "type": "string",
          "format": "decimal",
          "sourceType": [
            "Decimal",
            5,
            2
          ]
        },
        "customer": {
          "$ref": "#/objects/customer",
          "relation": {
            "attrKey": [
              "customer_id"
            ],
            "foreignAttrKey": [
              "customer_id"
            ]
          }
        },
        "customer_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "payment_date": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ]
        },
        "payment_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "rental": {
          "$ref": "#/objects/rental",
          "relation": {
            "attrKey": [
              "rental_id"
            ],
            "foreignAttrKey": [
              "rental_id"
            ],
            "onDelete": "SetNull"
          }
        },
        "rental_id": {
          "type": "integer"
        },
        "staff": {
          "$ref": "#/objects/staff",
          "relation": {
            "attrKey": [
              "staff_id"
            ],
            "foreignAttrKey": [
              "staff_id"
            ]
          }
        },
        "staff_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "customer_id"
          ],
          "sourceName": "idx_fk_customer_id"
        },
        {
          "type": "index",
          "property": [
            "rental_id"
          ],
          "sourceName": "idx_fk_rental_id"
        },
        {
          "type": "index",
          "property": [
            "staff_id"
          ],
          "sourceName": "idx_fk_staff_id"
        }
      ]
    },
    "rental": {
      "properties": {
        "customer": {
          "$ref": "#/objects/customer",
          "relation": {
            "attrKey": [
              "customer_id"
            ],
            "foreignAttrKey": [
              "customer_id"
            ]
          }
        },
        "customer_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "inventory": {
          "$ref": "#/objects/inventory",
          "relation": {
            "attrKey": [
              "inventory_id"
            ],
            "foreignAttrKey": [
              "inventory_id"
            ]
          }
        },
        "inventory_id": {
          "type": "integer"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "payment": {
          "type": "array",
          "items": {
            "$ref": "#/objects/payment"
          }
        },
        "rental_date": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ]
        },
        "rental_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "return_date": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "nullable": true
        },
        "staff": {
          "$ref": "#/objects/staff",
          "relation": {
            "attrKey": [
              "staff_id"
            ],
            "foreignAttrKey": [
              "staff_id"
            ],
            "sourceName": "rental_staff_id_key",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "staff_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "inventory_id"
          ],
          "sourceName": "idx_fk_inventory_id"
        },
        {
          "type": "unique",
          "property": [
            "rental_date",
            "inventory_id",
            "customer_id"
          ],
          "sourceName": "idx_unq_rental_rental_date_inventory_id_customer_id"
        }
      ]
    },
    "staff": {
      "properties": {
        "active": {
          "type": "boolean",
          "default": {
            "value": true
          }
        },
        "address": {
          "$ref": "#/objects/address",
          "relation": {
            "attrKey": [
              "address_id"
            ],
            "foreignAttrKey": [
              "address_id"
            ]
          }
        },
        "address_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "email": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ],
          "nullable": true
        },
        "first_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "password": {
          "type": "string",
          "sourceType": [
            "VarChar",
            40
          ],
          "nullable": true
        },
        "payment": {
          "type": "array",
          "items": {
            "$ref": "#/objects/payment"
          }
        },
        "picture": {
          "type": "string",
          "format": "bytes",
          "nullable": true
        },
        "rental": {
          "type": "array",
          "items": {
            "$ref": "#/objects/rental"
          }
        },
        "staff_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "store": {
          "nullable": true,
          "$ref": "#/objects/store"
        },
        "store_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "username": {
          "type": "string",
          "sourceType": [
            "VarChar",
            16
          ]
        }
      }
    },
    "store": {
      "properties": {
        "address": {
          "$ref": "#/objects/address",
          "relation": {
            "attrKey": [
              "address_id"
            ],
            "foreignAttrKey": [
              "address_id"
            ]
          }
        },
        "address_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "manager_staff_id": {
          "type": "integer",
          "sourceType": "SmallInt",
          "unique": true
        },
        "staff": {
          "$ref": "#/objects/staff",
          "relation": {
            "attrKey": [
              "manager_staff_id"
            ],
            "foreignAttrKey": [
              "staff_id"
            ]
          }
        },
        "store_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        }
      }
    }
  },
  "enums": {
    "mpaa_rating": [
      "G",
      "PG",
      "PG_13",
      "R",
      "NC_17"
    ]
  }
}
```

</details>

### <mark style="color:green;">GET</mark> endpoint examples

* Retrieve all actors

  ```json
  GET https://$ENV_API_URL/rest/actors
  ```
* Retrieve a specific actor by id

  ```json
  GET https://$ENV_API_URL/rest/actor/159
  ```

  or

  ```json
  GET https://$ENV_API_URL/rest/actor?filter={"actor_id":159}
  ```
* Retrieve a specific actor

  ```json
  GET https://$ENV_API_URL/rest/actor?filter={"first_name":"John", "last_name":"Wayne"}
  ```
* Retrieve 5 customers

  ```json
  GET https://$ENV_API_URL/rest/customer?take=5
  ```
* Retrieve all films and their actors

  ```json
  GET https://$ENV_API_URL/rest/film?select={"film_actor": {"actor":{"$scalars": true}}, "$scalars": true}
  ```
* Retrieve stores and their employees

  ```json
  GET https://$ENV_API_URL/rest/store?select={"staff":{"$scalars": true}, "$scalars": true}
  ```
* Retrieve rentals and films

  ```json
  GET https://$ENV_API_URL/rest/rental?select={"inventory":{"film": {"$scalars": true}}, "$scalars": true}&take=5
  ```
* Retrieve films by category

  ```json
  GET https://$ENV_API_URL/rest/category?select={"film_category":{"film": {"$scalars": true}}, "$scalars": true}&take=5
  ```
* Retrieve customers that have rented a movie after 2006-01-01

  ```json
  GET https://$ENV_API_URL/rest/category?select={"$scalars": true}&filter={"rental": {"some": {"rental_date": {"gte": "2006-01-01T00:00:00.000Z"}}}}
  ```
* Retrieve customers that have more than 35 rentals

  ```json
  GET https://$ENV_API_URL/rest/category?select={"customer_id": true}&aggregate={"_count": ["rental_id"]}&group_by=["customer_id"]&having={"rental_id": {"_count": {"gt": 35}}}
  ```
* Retrieve count of films in english by category

  ```json
  GET https://$ENV_API_URL/rest/category?select={"category_id": true}&filter={"film": {"language": {"name": {"contains": "English"}}}}&aggregate={"_count": ["film_id"]}&group_by=["category_id"]
  ```
* Get all films where (special features contains "Commentaries" OR length > 160) AND replacement cost > 29

  ```json
  GET https://$ENV_API_URL/rest/category?select={"$scalars": true}&filter={"OR": [{"special_features": {"has": "Commentaries"}}, {"length": {"gt": 160}}], "replacement_cost": {"gte": 29}}
  ```

### <mark style="color:blue;">POST</mark> endpoint examples

* Create a new actor

  ```json
  POST https://$ENV_API_URL/rest/actor

  {
          "content": "This is my first blog post",
          "title": "My first blog post"
  }
  ```
* Create multiple rentals

  ```json
  POST https://$ENV_API_URL/rest/rental

  [
      {
          "customer_id": 2,
          "inventory_id": 1,
          "rental_date": "2023-07-11T14:50:58.951Z",
          "staff_id": 1
      },
      {
          "customer_id": 524,
          "inventory_id": 2,
          "rental_date": "2023-07-11T14:50:58.951Z",
          "staff_id": 1
      }
  ]
  ```
* Create a film and related data

  ```json
  POST https://$ENV_API_URL/rest/film?select={"$scalars": true, "language": {"$scalars": true}, "film_category": {"category": {"$scalars": true}}, "film_actor": {"actor": {"$scalars": true}}}

  {
      "title": "Shrek 3",
      "language": {
          "connect": {
              "language_id": 2
          }
      },
      "film_category": {
          "create": {
              "category": {
                  "create": {
                      "name": "Swamp"
                  }
              }
          }
      },
      "film_actor": {
          "create": {
              "actor": {
                  "create": {
                      "first_name": "Prince",
                      "last_name": "Arthur"
                  }
              }
          }
      }
  }
  ```

### <mark style="color:purple;">PATCH</mark> endpoint examples

* Update a film

  ```json
  PATCH https://$ENV_API_URL/rest/film/1001?select={"film_actor": {"actor":{"$scalars": true}}, "$scalars": true}

  {
      "description": "Book of Life"
  }
  ```

### <mark style="color:red;">DELETE</mark> endpoint examples

* Delete an actor

  ```json
  DELETE https://$ENV_API_URL/rest/actor/201?select={"$scalars": true, "$related": true}
  ```
* Delete films by name

  <pre class="language-json"><code class="lang-json"><strong>DELETE https://$ENV_API_URL/rest/film?filter={"title": {"contains": "Shark"}}
  </strong></code></pre>


# Example 3 - "Bookstore” application

### Schema

We are going to use this schema as the sample schema for the examples that follow - This is the Gravity Bookstore sample database from [DatabaseStar](https://www.databasestar.com/sample-bookstore-database/).

This schema contains the following tables:

* **book**: a list of all books available in the store.
* **book\_author**: stores the authors for each book, which is a many-to-many relationship.
* **author**: a list of all authors.
* **book\_language**: a list of possible languages of books.
* **publisher**: a list of publishers for books.
* **customer**: a list of the customers of the Gravity Bookstore.
* **customer\_address**: a list of addresses for customers, as a customer can have more than one address, and an address has more than one customer.
* **address\_status**: a list of statuses for an address, because addresses can be current or old.
* **address**: a list of addresses in the system.
* **country**: a list of countries that addresses are in.
* **cust\_order**: a list of orders placed by customers.
* **order\_line**: a list of books that are a part of each order.
* **shipping\_method**: the possible shipping methods for an order.
* **order\_history**: the history of an order, such as ordered, cancelled, delivered.
* **order\_status**: the possible statuses of an order.

Here is the ERD of this sample bookstore database:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FjuFhOsFie9jDWvysGAcs%2Ferd_gravity.png?alt=media&amp;token=3c61a2d4-7847-49f7-b9e1-162379ea2464" alt=""><figcaption></figcaption></figure>

* This is the schema in the Neurelo Schema Language JSON Specification format

<details>

<summary>JSON Schema</summary>

```json
{
  "objects": {
    "address": {
      "properties": {
        "address_id": {
          "type": "integer",
          "identifier": true
        },
        "city": {
          "type": "string",
          "sourceType": [
            "VarChar",
            100
          ],
          "nullable": true
        },
        "country": {
          "nullable": true,
          "$ref": "#/objects/country",
          "relation": {
            "attrKey": [
              "country_id"
            ],
            "foreignAttrKey": [
              "country_id"
            ],
            "sourceName": "fk_addr_ctry",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "country_id": {
          "type": "integer",
          "nullable": true
        },
        "cust_order": {
          "type": "array",
          "items": {
            "$ref": "#/objects/cust_order"
          }
        },
        "customer_address": {
          "type": "array",
          "items": {
            "$ref": "#/objects/customer_address"
          }
        },
        "street_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        },
        "street_number": {
          "type": "string",
          "sourceType": [
            "VarChar",
            10
          ],
          "nullable": true
        }
      }
    },
    "address_status": {
      "properties": {
        "address_status": {
          "type": "string",
          "sourceType": [
            "VarChar",
            30
          ],
          "nullable": true
        },
        "status_id": {
          "type": "integer",
          "identifier": true
        }
      }
    },
    "author": {
      "properties": {
        "author_id": {
          "type": "integer",
          "identifier": true
        },
        "author_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            400
          ],
          "nullable": true
        },
        "book_author": {
          "type": "array",
          "items": {
            "$ref": "#/objects/book_author"
          }
        }
      }
    },
    "book": {
      "properties": {
        "book_author": {
          "type": "array",
          "items": {
            "$ref": "#/objects/book_author"
          }
        },
        "book_id": {
          "type": "integer",
          "identifier": true
        },
        "book_language": {
          "nullable": true,
          "$ref": "#/objects/book_language",
          "relation": {
            "attrKey": [
              "language_id"
            ],
            "foreignAttrKey": [
              "language_id"
            ],
            "sourceName": "fk_book_lang",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "isbn13": {
          "type": "string",
          "sourceType": [
            "VarChar",
            13
          ],
          "nullable": true
        },
        "language_id": {
          "type": "integer",
          "nullable": true
        },
        "num_pages": {
          "type": "integer",
          "nullable": true
        },
        "order_line": {
          "type": "array",
          "items": {
            "$ref": "#/objects/order_line"
          }
        },
        "publication_date": {
          "type": "string",
          "format": "date",
          "sourceType": "Date",
          "nullable": true
        },
        "publisher": {
          "nullable": true,
          "$ref": "#/objects/publisher",
          "relation": {
            "attrKey": [
              "publisher_id"
            ],
            "foreignAttrKey": [
              "publisher_id"
            ],
            "sourceName": "fk_book_pub",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "publisher_id": {
          "type": "integer",
          "nullable": true
        },
        "title": {
          "type": "string",
          "sourceType": [
            "VarChar",
            400
          ],
          "nullable": true
        }
      }
    },
    "book_author": {
      "properties": {
        "author": {
          "$ref": "#/objects/author",
          "relation": {
            "attrKey": [
              "author_id"
            ],
            "foreignAttrKey": [
              "author_id"
            ],
            "sourceName": "fk_ba_author",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "author_id": {
          "type": "integer"
        },
        "book": {
          "$ref": "#/objects/book",
          "relation": {
            "attrKey": [
              "book_id"
            ],
            "foreignAttrKey": [
              "book_id"
            ],
            "sourceName": "fk_ba_book",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "book_id": {
          "type": "integer"
        }
      },
      "constraints": [
        {
          "type": "identifier",
          "property": [
            "book_id",
            "author_id"
          ],
          "sourceName": "pk_bookauthor"
        }
      ]
    },
    "book_language": {
      "properties": {
        "book": {
          "type": "array",
          "items": {
            "$ref": "#/objects/book"
          }
        },
        "language_code": {
          "type": "string",
          "sourceType": [
            "VarChar",
            8
          ],
          "nullable": true
        },
        "language_id": {
          "type": "integer",
          "identifier": true
        },
        "language_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ],
          "nullable": true
        }
      }
    },
    "country": {
      "properties": {
        "address": {
          "type": "array",
          "items": {
            "$ref": "#/objects/address"
          }
        },
        "country_id": {
          "type": "integer",
          "identifier": true
        },
        "country_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        }
      }
    },
    "cust_order": {
      "properties": {
        "address": {
          "nullable": true,
          "$ref": "#/objects/address",
          "relation": {
            "attrKey": [
              "dest_address_id"
            ],
            "foreignAttrKey": [
              "address_id"
            ],
            "sourceName": "fk_order_addr",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "customer": {
          "nullable": true,
          "$ref": "#/objects/customer",
          "relation": {
            "attrKey": [
              "customer_id"
            ],
            "foreignAttrKey": [
              "customer_id"
            ],
            "sourceName": "fk_order_cust",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "customer_id": {
          "type": "integer",
          "nullable": true
        },
        "dest_address_id": {
          "type": "integer",
          "nullable": true
        },
        "order_date": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "nullable": true
        },
        "order_history": {
          "type": "array",
          "items": {
            "$ref": "#/objects/order_history"
          }
        },
        "order_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "order_line": {
          "type": "array",
          "items": {
            "$ref": "#/objects/order_line"
          }
        },
        "shipping_method": {
          "nullable": true,
          "$ref": "#/objects/shipping_method",
          "relation": {
            "attrKey": [
              "shipping_method_id"
            ],
            "foreignAttrKey": [
              "method_id"
            ],
            "sourceName": "fk_order_ship",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "shipping_method_id": {
          "type": "integer",
          "nullable": true
        }
      }
    },
    "customer": {
      "properties": {
        "cust_order": {
          "type": "array",
          "items": {
            "$ref": "#/objects/cust_order"
          }
        },
        "customer_address": {
          "type": "array",
          "items": {
            "$ref": "#/objects/customer_address"
          }
        },
        "customer_id": {
          "type": "integer",
          "identifier": true
        },
        "email": {
          "type": "string",
          "sourceType": [
            "VarChar",
            350
          ],
          "nullable": true
        },
        "first_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        },
        "last_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            200
          ],
          "nullable": true
        }
      }
    },
    "customer_address": {
      "properties": {
        "address": {
          "$ref": "#/objects/address",
          "relation": {
            "attrKey": [
              "address_id"
            ],
            "foreignAttrKey": [
              "address_id"
            ],
            "sourceName": "fk_ca_addr",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "address_id": {
          "type": "integer"
        },
        "customer": {
          "$ref": "#/objects/customer",
          "relation": {
            "attrKey": [
              "customer_id"
            ],
            "foreignAttrKey": [
              "customer_id"
            ],
            "sourceName": "fk_ca_cust",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "customer_id": {
          "type": "integer"
        },
        "status_id": {
          "type": "integer",
          "nullable": true
        }
      },
      "constraints": [
        {
          "type": "identifier",
          "property": [
            "customer_id",
            "address_id"
          ],
          "sourceName": "pk_custaddr"
        }
      ]
    },
    "order_history": {
      "properties": {
        "cust_order": {
          "nullable": true,
          "$ref": "#/objects/cust_order",
          "relation": {
            "attrKey": [
              "order_id"
            ],
            "foreignAttrKey": [
              "order_id"
            ],
            "sourceName": "fk_oh_order",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "history_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "order_id": {
          "type": "integer",
          "nullable": true
        },
        "order_status": {
          "nullable": true,
          "$ref": "#/objects/order_status",
          "relation": {
            "attrKey": [
              "status_id"
            ],
            "foreignAttrKey": [
              "status_id"
            ],
            "sourceName": "fk_oh_status",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "status_date": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "nullable": true
        },
        "status_id": {
          "type": "integer",
          "nullable": true
        }
      }
    },
    "order_line": {
      "properties": {
        "book": {
          "nullable": true,
          "$ref": "#/objects/book",
          "relation": {
            "attrKey": [
              "book_id"
            ],
            "foreignAttrKey": [
              "book_id"
            ],
            "sourceName": "fk_ol_book",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "book_id": {
          "type": "integer",
          "nullable": true
        },
        "cust_order": {
          "nullable": true,
          "$ref": "#/objects/cust_order",
          "relation": {
            "attrKey": [
              "order_id"
            ],
            "foreignAttrKey": [
              "order_id"
            ],
            "sourceName": "fk_ol_order",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "line_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "order_id": {
          "type": "integer",
          "nullable": true
        },
        "price": {
          "type": "string",
          "format": "decimal",
          "sourceType": [
            "Decimal",
            5,
            2
          ],
          "nullable": true
        }
      }
    },
    "order_status": {
      "properties": {
        "order_history": {
          "type": "array",
          "items": {
            "$ref": "#/objects/order_history"
          }
        },
        "status_id": {
          "type": "integer",
          "identifier": true
        },
        "status_value": {
          "type": "string",
          "sourceType": [
            "VarChar",
            20
          ],
          "nullable": true
        }
      }
    },
    "publisher": {
      "properties": {
        "book": {
          "type": "array",
          "items": {
            "$ref": "#/objects/book"
          }
        },
        "publisher_id": {
          "type": "integer",
          "identifier": true
        },
        "publisher_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            400
          ],
          "nullable": true
        }
      }
    },
    "shipping_method": {
      "properties": {
        "cost": {
          "type": "string",
          "format": "decimal",
          "sourceType": [
            "Decimal",
            6,
            2
          ],
          "nullable": true
        },
        "cust_order": {
          "type": "array",
          "items": {
            "$ref": "#/objects/cust_order"
          }
        },
        "method_id": {
          "type": "integer",
          "identifier": true
        },
        "method_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            100
          ],
          "nullable": true
        }
      }
    }
  }
}
```

</details>

### <mark style="color:green;">GET</mark> endpoint examples

* Get one author by id 19283

  ```json
  GET https://$ENV_API_URL/rest/author/19283
  ?select={"$scalars": true, "$related": true}
  ```
* Select first 10 publisher and books ordered by publisher name

  ```json
  GET https://$ENV_API_URL/rest/publisher
  ?select={"$scalars": true, "book": {"$scalars": true}}
  &order_by=[{"publisher_name": "asc"}]
  &take=10
  ```
* Select customer scalars and their orders. Filter by email containing "[cdbaby.com](http://cdbaby.com/)"

  ```json
  GET https://$ENV_API_URL/rest/customer
  ?select={"$scalars": true, "cust_order": {"order_id": true, "order_line": {"$scalars": true}}}
  &filter={"email": {"contains": "@cdbaby.com"}}
  ```
* Select book\_id and the number of books sold where sales > 8

  ```json
  GET https://$ENV_API_URL/rest/order_line
  ?select={"book_id": true}
  &aggregate={"_count": ["line_id"]}
  &group_by=["book_id"]
  &having={"book_id": {"_count": {"gt": 8}}}
  ```
* Get list of customer order with order\_history and scalars. Filter by status is Order Received

  ```json
  GET https://$ENV_API_URL/rest/cust_order
  ?select={"order_history": {"order_status": {"$scalars": true}, "status_date": true}, "$scalars": true}
  &filter={"order_history": {"every": {"order_status": {"status_value": {"equals": "Order Received"}}}}}
  &take=3
  ```
* Get list of books not translated to "English” (.*English.* - includes “English”, “British English”, “United States English”), or “Spanish

  ```json
  GET https://$ENV_API_URL/rest/book
  ?select={"book_id": true, "title": true}
  &filter={"book_language": {"NOT": [{"language_name": {"contains": "English"}}, {"language_name": "Spanish"}]}}
  ```

### <mark style="color:blue;">POST</mark> endpoint examples

* Create a new book with author

  ```json
  POST https://$ENV_API_URL/rest/book
  ?select={"$scalars": true, "$related": true}

  {
      "book_id": 19283,
      "title": "DUNE: A new hope",
      "book_author": {
          "create": {
              "author": {
                  "create": {
                      "author_id": 19283,
                      "author_name": "Frank Lucas"
                  }
              }
          }
      }
  }
  ```
* Create many authors

  ```json
  POST https://$ENV_API_URL/rest/author

  [
      {
          "author_id": 19284,
          "author_name": "Francis Hube"
      },
      {
          "author_id": 19285,
          "author_name": "Brandon Stevens"
      },
      {
          "author_id": 19286,
          "author_name": "Red Roberts"
      }
  ]
  ```
* Create a new author with many books

  ```json
  POST https://$ENV_API_URL/rest/author
  ?select={"$scalars": true, "$related": true}

  {
      "author_id": 19288,
      "author_name": "Arthur Doyle",
      "book_author": {
          "create": [
              {
                  "book": {
                      "create": {
                          "book_id": 19286,
                          "title": "Sherlock Holmes: Mistery one"
                      }
                  }
              },
              {
                  "book": {
                      "create": {
                          "book_id": 19287,
                          "title": "Sherlock Holmes: Mistery two"
                      }
                  }
              }
          ]
      }
  }
  ```
* Create a customer with address and address status

  ```json
  POST https://$ENV_API_URL/rest/customer
  ?select={"$scalars": true, "customer_address": {"address": {"$scalars": true}}}

  {
      "customer_id": 19201,
      "first_name": "Watson",
      "email": "watson@solvesmysteries.com",
      "customer_address": {
          "create": {
              "status_id": 1,
              "address": {
                  "create": {
                      "address_id": 19201,
                      "city": "San Francisco",
                      "street_name": "Big Street",
                      "street_number": "1"
                  }
              }
          }
      }
  }
  ```

### <mark style="color:purple;">PATCH</mark> endpoint examples

* Update a single address

  ```json
  PATCH https://$ENV_API_URL/rest/address/19200
  ?select={"$scalars": true}

  {
      "city": "London",
      "street_name": "Baker Street",
      "street_number": "221B"
  }
  ```
* Update multiple addresses based on filter

  ```json
  PATCH https://$ENV_API_URL/rest/address
  ?filter={"city": "London"}

  {
      "city": "London",
      "street_name": "Baker Street",
      "street_number": "221B"
  }
  ```
* Update book title where title and language

  ```json
  PATCH https://$ENV_API_URL/rest/book
  ?filter={"AND": {"title": "Bed time stories", "book_language": {"language_name": "Russian"}}}

  {
      "isbn13": "the-new-isbn"
  }
  ```

### <mark style="color:red;">DELETE</mark> endpoint examples

* Delete publishers that have forbidden books published

  ```json
  DELETE https://$ENV_API_URL/rest/publisher
  ?filter={"book": {"some": {"title": "Forbidden text as of now"}}}
  ```


# cURL API Examples

### Schema

This is a DVD Rentals example database schema from [PostgreSQL Tutorial](https://www.postgresqltutorial.com/postgresql-getting-started/postgresql-sample-database/).

There are 15 tables in the DVD Rental database:

* **actor** – stores actors data including first name and last name.
* **film** – stores film data such as title, release year, length, rating, etc.
* **film\_actor** – stores the relationships between films and actors.
* **category** – stores film’s categories data.
* **film\_category**- stores the relationships between films and categories.
* **store** – contains the store data including manager staff and address.
* **inventory** – stores inventory data.
* **rental** – stores rental data.
* **payment** – stores customer’s payments.
* **staff** – stores staff data.
* **customer** – stores customer data.
* **address** – stores address data for staff and customers
* **city** – stores city names.
* **country** – stores country names.

Here is the ERD of the sample DVD rentals database:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FR6WjaAECIirZFs3Jzmiq%2Fdvd-rental-sample-database-diagram.png?alt=media&amp;token=907bb134-36c9-4377-9eb4-85944dc488b5" alt=""><figcaption></figcaption></figure>

* This is the schema in the Neurelo Schema Language JSON Specification format

<details>

<summary>JSON Schema</summary>

```json
{
  "objects": {
    "actor": {
      "properties": {
        "actor_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "film_actor": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film_actor"
          }
        },
        "first_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "last_name"
          ],
          "sourceName": "idx_actor_last_name"
        }
      ]
    },
    "address": {
      "properties": {
        "address": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ]
        },
        "address2": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ],
          "nullable": true
        },
        "address_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "city": {
          "$ref": "#/objects/city",
          "relation": {
            "attrKey": [
              "city_id"
            ],
            "foreignAttrKey": [
              "city_id"
            ],
            "sourceName": "fk_address_city",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "city_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "customer": {
          "type": "array",
          "items": {
            "$ref": "#/objects/customer"
          }
        },
        "district": {
          "type": "string",
          "sourceType": [
            "VarChar",
            20
          ]
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "phone": {
          "type": "string",
          "sourceType": [
            "VarChar",
            20
          ]
        },
        "postal_code": {
          "type": "string",
          "sourceType": [
            "VarChar",
            10
          ],
          "nullable": true
        },
        "staff": {
          "type": "array",
          "items": {
            "$ref": "#/objects/staff"
          }
        },
        "store": {
          "type": "array",
          "items": {
            "$ref": "#/objects/store"
          }
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "city_id"
          ],
          "sourceName": "idx_fk_city_id"
        }
      ]
    },
    "category": {
      "properties": {
        "category_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "film_category": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film_category"
          }
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            25
          ]
        }
      }
    },
    "city": {
      "properties": {
        "address": {
          "type": "array",
          "items": {
            "$ref": "#/objects/address"
          }
        },
        "city": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ]
        },
        "city_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "country": {
          "$ref": "#/objects/country",
          "relation": {
            "attrKey": [
              "country_id"
            ],
            "foreignAttrKey": [
              "country_id"
            ],
            "sourceName": "fk_city",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "country_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "country_id"
          ],
          "sourceName": "idx_fk_country_id"
        }
      ]
    },
    "country": {
      "properties": {
        "city": {
          "type": "array",
          "items": {
            "$ref": "#/objects/city"
          }
        },
        "country": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ]
        },
        "country_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      }
    },
    "customer": {
      "properties": {
        "active": {
          "type": "integer",
          "nullable": true
        },
        "activebool": {
          "type": "boolean",
          "default": {
            "value": true
          }
        },
        "address": {
          "$ref": "#/objects/address",
          "relation": {
            "attrKey": [
              "address_id"
            ],
            "foreignAttrKey": [
              "address_id"
            ]
          }
        },
        "address_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "create_date": {
          "type": "string",
          "format": "date",
          "sourceType": "Date",
          "default": {
            "function": "dbgenerated",
            "rawDbValue": "('now'::text)::date"
          }
        },
        "customer_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "email": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ],
          "nullable": true
        },
        "first_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          },
          "nullable": true
        },
        "payment": {
          "type": "array",
          "items": {
            "$ref": "#/objects/payment"
          }
        },
        "rental": {
          "type": "array",
          "items": {
            "$ref": "#/objects/rental"
          }
        },
        "store_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "address_id"
          ],
          "sourceName": "idx_fk_address_id"
        },
        {
          "type": "index",
          "property": [
            "store_id"
          ],
          "sourceName": "idx_fk_store_id"
        },
        {
          "type": "index",
          "property": [
            "last_name"
          ],
          "sourceName": "idx_last_name"
        }
      ]
    },
    "film": {
      "properties": {
        "description": {
          "type": "string",
          "nullable": true
        },
        "film_actor": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film_actor"
          }
        },
        "film_category": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film_category"
          }
        },
        "film_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "inventory": {
          "type": "array",
          "items": {
            "$ref": "#/objects/inventory"
          }
        },
        "language": {
          "$ref": "#/objects/language",
          "relation": {
            "attrKey": [
              "language_id"
            ],
            "foreignAttrKey": [
              "language_id"
            ]
          }
        },
        "language_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "length": {
          "type": "integer",
          "sourceType": "SmallInt",
          "nullable": true
        },
        "rating": {
          "default": {
            "value": "G"
          },
          "nullable": true,
          "$ref": "#/enums/mpaa_rating"
        },
        "release_year": {
          "type": "integer",
          "nullable": true
        },
        "rental_duration": {
          "type": "integer",
          "sourceType": "SmallInt",
          "default": {
            "value": 3
          }
        },
        "rental_rate": {
          "type": "string",
          "format": "decimal",
          "sourceType": [
            "Decimal",
            4,
            2
          ],
          "default": {
            "value": "4.99"
          }
        },
        "replacement_cost": {
          "type": "string",
          "format": "decimal",
          "sourceType": [
            "Decimal",
            5,
            2
          ],
          "default": {
            "value": "19.99"
          }
        },
        "special_features": {
          "type": "array",
          "items": {
            "type": "string"
          }
        },
        "title": {
          "type": "string",
          "sourceType": [
            "VarChar",
            255
          ]
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "language_id"
          ],
          "sourceName": "idx_fk_language_id"
        },
        {
          "type": "index",
          "property": [
            "title"
          ],
          "sourceName": "idx_title"
        }
      ]
    },
    "film_actor": {
      "properties": {
        "actor": {
          "$ref": "#/objects/actor",
          "relation": {
            "attrKey": [
              "actor_id"
            ],
            "foreignAttrKey": [
              "actor_id"
            ]
          }
        },
        "actor_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "film": {
          "$ref": "#/objects/film",
          "relation": {
            "attrKey": [
              "film_id"
            ],
            "foreignAttrKey": [
              "film_id"
            ]
          }
        },
        "film_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      },
      "constraints": [
        {
          "type": "identifier",
          "property": [
            "actor_id",
            "film_id"
          ]
        },
        {
          "type": "index",
          "property": [
            "film_id"
          ],
          "sourceName": "idx_fk_film_id"
        }
      ]
    },
    "film_category": {
      "properties": {
        "category": {
          "$ref": "#/objects/category",
          "relation": {
            "attrKey": [
              "category_id"
            ],
            "foreignAttrKey": [
              "category_id"
            ]
          }
        },
        "category_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "film": {
          "$ref": "#/objects/film",
          "relation": {
            "attrKey": [
              "film_id"
            ],
            "foreignAttrKey": [
              "film_id"
            ]
          }
        },
        "film_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        }
      },
      "constraints": [
        {
          "type": "identifier",
          "property": [
            "film_id",
            "category_id"
          ]
        }
      ]
    },
    "inventory": {
      "properties": {
        "film": {
          "$ref": "#/objects/film",
          "relation": {
            "attrKey": [
              "film_id"
            ],
            "foreignAttrKey": [
              "film_id"
            ]
          }
        },
        "film_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "inventory_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "rental": {
          "type": "array",
          "items": {
            "$ref": "#/objects/rental"
          }
        },
        "store_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "store_id",
            "film_id"
          ],
          "sourceName": "idx_store_id_film_id"
        }
      ]
    },
    "language": {
      "properties": {
        "film": {
          "type": "array",
          "items": {
            "$ref": "#/objects/film"
          }
        },
        "language_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "name": {
          "type": "string",
          "sourceType": [
            "Char",
            20
          ]
        }
      }
    },
    "payment": {
      "properties": {
        "amount": {
          "type": "string",
          "format": "decimal",
          "sourceType": [
            "Decimal",
            5,
            2
          ]
        },
        "customer": {
          "$ref": "#/objects/customer",
          "relation": {
            "attrKey": [
              "customer_id"
            ],
            "foreignAttrKey": [
              "customer_id"
            ]
          }
        },
        "customer_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "payment_date": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ]
        },
        "payment_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "rental": {
          "$ref": "#/objects/rental",
          "relation": {
            "attrKey": [
              "rental_id"
            ],
            "foreignAttrKey": [
              "rental_id"
            ],
            "onDelete": "SetNull"
          }
        },
        "rental_id": {
          "type": "integer"
        },
        "staff": {
          "$ref": "#/objects/staff",
          "relation": {
            "attrKey": [
              "staff_id"
            ],
            "foreignAttrKey": [
              "staff_id"
            ]
          }
        },
        "staff_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "customer_id"
          ],
          "sourceName": "idx_fk_customer_id"
        },
        {
          "type": "index",
          "property": [
            "rental_id"
          ],
          "sourceName": "idx_fk_rental_id"
        },
        {
          "type": "index",
          "property": [
            "staff_id"
          ],
          "sourceName": "idx_fk_staff_id"
        }
      ]
    },
    "rental": {
      "properties": {
        "customer": {
          "$ref": "#/objects/customer",
          "relation": {
            "attrKey": [
              "customer_id"
            ],
            "foreignAttrKey": [
              "customer_id"
            ]
          }
        },
        "customer_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "inventory": {
          "$ref": "#/objects/inventory",
          "relation": {
            "attrKey": [
              "inventory_id"
            ],
            "foreignAttrKey": [
              "inventory_id"
            ]
          }
        },
        "inventory_id": {
          "type": "integer"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "payment": {
          "type": "array",
          "items": {
            "$ref": "#/objects/payment"
          }
        },
        "rental_date": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ]
        },
        "rental_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "return_date": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "nullable": true
        },
        "staff": {
          "$ref": "#/objects/staff",
          "relation": {
            "attrKey": [
              "staff_id"
            ],
            "foreignAttrKey": [
              "staff_id"
            ],
            "sourceName": "rental_staff_id_key",
            "onUpdate": "NoAction",
            "onDelete": "NoAction"
          }
        },
        "staff_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        }
      },
      "constraints": [
        {
          "type": "index",
          "property": [
            "inventory_id"
          ],
          "sourceName": "idx_fk_inventory_id"
        },
        {
          "type": "unique",
          "property": [
            "rental_date",
            "inventory_id",
            "customer_id"
          ],
          "sourceName": "idx_unq_rental_rental_date_inventory_id_customer_id"
        }
      ]
    },
    "staff": {
      "properties": {
        "active": {
          "type": "boolean",
          "default": {
            "value": true
          }
        },
        "address": {
          "$ref": "#/objects/address",
          "relation": {
            "attrKey": [
              "address_id"
            ],
            "foreignAttrKey": [
              "address_id"
            ]
          }
        },
        "address_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "email": {
          "type": "string",
          "sourceType": [
            "VarChar",
            50
          ],
          "nullable": true
        },
        "first_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_name": {
          "type": "string",
          "sourceType": [
            "VarChar",
            45
          ]
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "password": {
          "type": "string",
          "sourceType": [
            "VarChar",
            40
          ],
          "nullable": true
        },
        "payment": {
          "type": "array",
          "items": {
            "$ref": "#/objects/payment"
          }
        },
        "picture": {
          "type": "string",
          "format": "bytes",
          "nullable": true
        },
        "rental": {
          "type": "array",
          "items": {
            "$ref": "#/objects/rental"
          }
        },
        "staff_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        },
        "store": {
          "nullable": true,
          "$ref": "#/objects/store"
        },
        "store_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "username": {
          "type": "string",
          "sourceType": [
            "VarChar",
            16
          ]
        }
      }
    },
    "store": {
      "properties": {
        "address": {
          "$ref": "#/objects/address",
          "relation": {
            "attrKey": [
              "address_id"
            ],
            "foreignAttrKey": [
              "address_id"
            ]
          }
        },
        "address_id": {
          "type": "integer",
          "sourceType": "SmallInt"
        },
        "last_update": {
          "type": "string",
          "format": "date-time",
          "sourceType": [
            "Timestamp",
            6
          ],
          "default": {
            "function": "now"
          }
        },
        "manager_staff_id": {
          "type": "integer",
          "sourceType": "SmallInt",
          "unique": true
        },
        "staff": {
          "$ref": "#/objects/staff",
          "relation": {
            "attrKey": [
              "manager_staff_id"
            ],
            "foreignAttrKey": [
              "staff_id"
            ]
          }
        },
        "store_id": {
          "type": "integer",
          "default": {
            "function": "autoincrement"
          },
          "identifier": true
        }
      }
    }
  },
  "enums": {
    "mpaa_rating": [
      "G",
      "PG",
      "PG_13",
      "R",
      "NC_17"
    ]
  }
}
```

</details>

### <mark style="color:green;">GET</mark> endpoint examples

* Get All Actors

```bash
curl https://us-east-2.aws.neurelo.app/rest/actor \
--header 'X-API-KEY: <api-key>'
```

* Get specific actor(s)

```bash
# Find actor with "actor_id" = 200
curl https://us-east-2.aws.neurelo.app/rest/actor \
--url-query filter='{"actor_id":200}' \
--header 'X-API-KEY: <api-key>'

# Find actor(s) with the First Name "Ed"
curl https://us-east-2.aws.neurelo.app/rest/actor \
--url-query filter='{"first_name":"Ed"}' \
--header 'X-API-KEY: <api-key>'

# Find actor(s) whose Last Name contains "berg"
curl https://us-east-2.aws.neurelo.app/rest/actor \
--url-query filter='{"last_name": {"contains": "berg"}}' \
--header 'X-API-KEY: <api-key>'

# Find actor(s) whose First Name does not contain "John"
curl https://us-east-2.aws.neurelo.app/rest/actor \ 
--url-query filter='{"NOT":{"first_name":{"contains":"John"}}}' \ 
--header 'X-API-KEY: <api-key>'

# Find actor(s) whose First Name is not "John"
curl https://us-east-2.aws.neurelo.app/rest/actor \ 
--url-query filter='{"NOT":{"first_name":"John"}}' \ 
--header 'X-API-KEY: <api-key>'

# Find actor(s) whose First Name is "John" or "Ed"
curl https://us-east-2.aws.neurelo.app/rest/actor \ 
--url-query filter='{"OR":[{"first_name":"John"},{"first_name":"Ed"}]}' \ 
--header 'X-API-KEY: <api-key>'

# Find actor(s) whose First Name is NOT ("John" or "Ed")
curl https://us-east-2.aws.neurelo.app/rest/actor \ 
--url-query filter='{"NOT":{"OR":[{"first_name":"John"},{"first_name":"Ed"}]}}' \ 
--header 'X-API-KEY: <api-key>'
```

* Get 10 Customers

```bash
curl https://us-east-2.aws.neurelo.app/rest/customer \
--url-query take='10' \
--header 'X-API-KEY: <api-key>'
```

* Get Films & Actors

```bash
curl https://us-east-2.aws.neurelo.app/rest/film \
--url-query select='{"film_actor": {"actor":{"$scalars": true}}, "$scalars": true}' \
--header 'X-API-KEY: <api-key>'
```

* Get Stores & Employees

```bash
curl https://us-east-2.aws.neurelo.app/rest/store \
--url-query select='{"staff":{"$scalars": true}, "$scalars": true}' \
--header 'X-API-KEY: <api-key>'
```

* Get 5 Rentals and Films

```bash
curl https://us-east-2.aws.neurelo.app/rest/rental \
--url-query select='{"inventory":{"film": {"$scalars": true}}, "$scalars": true}&take=5' \
--header 'X-API-KEY: <api-key>'
```

* Get 3 Films By Category

```bash
curl https://us-east-2.aws.neurelo.app/rest/category \
--url-query select='{"film_category":{"film": {"$scalars": true}}, "$scalars": true}&take=3' \
--header 'X-API-KEY: <api-key>'
```

### <mark style="color:blue;">POST</mark> endpoint examples

* Create New Actor

```bash
curl https://us-east-2.aws.neurelo.app/rest/actor \
--header 'X-API-KEY: <api-key>' \
--header 'Content-Type: application/json' \
--data '{
    "first_name": "John",
    "last_name": "Wayne"
}'
```

* Create many Rentals

```bash
curl https://us-east-2.aws.neurelo.app/rest/rental \
--header 'X-API-KEY: <api-key>' \
--header 'Content-Type: application/json' \
--data '[
    {
        "customer_id": 2,
        "inventory_id": 1,
        "rental_date": "2023-07-11T14:50:58.951Z",
        "staff_id": 1
    },
    {
        "customer_id": 524,
        "inventory_id": 2,
        "rental_date": "2023-07-11T14:50:58.951Z",
        "staff_id": 1
    }
]'
```

* Create One Film & Related

```bash
curl https://us-east-2.aws.neurelo.app/rest/film \
--url-query select='{"$scalars": true, "language": {"$scalars": true}, "film_category": {"category": {"$scalars": true}}, "film_actor": {"actor": {"$scalars": true}}}' \
--header 'X-API-KEY: <api-key>' \
--header 'Content-Type: application/json' \
--data '{
    "title": "Shrek 3",
    "language": {
        "connect": {
            "language_id": 2
        }
    },
    "film_category": {
        "create": {
            "category": {
                "create": {
                    "name": "Swamp"
                }
            }
        }
    },
    "film_actor": {
        "create": {
            "actor": {
                "create": {
                    "first_name": "Prince",
                    "last_name": "Arthur"
                }
            }
        }
    }
}'
```

### <mark style="color:purple;">PATCH</mark> endpoint examples

* Update a film

```bash
curl --request PATCH https://us-east-2.aws.neurelo.app/rest/film/133 \
--header 'X-API-KEY: <api-key>' \
--header 'Content-Type: application/json' \
--data '{
    "description": "Book of Life"
}'
```

### <mark style="color:red;">DELETE</mark> endpoint examples

* Delete an actor

```bash
curl --request DELETE [https://us-east-2.aws.neurelo.app/rest/actor/201 \](https://us-east-2.aws.neurelo.app/openapi/actor/201?select=%7B%22%24scalars%22%3A%20true%2C%20%22%24related%22%3A%20true%7D)
--header 'X-API-KEY: <api-key>'
```

* Delete films by name

```bash
curl --request DELETE [https://us-east-2.aws.neurelo.app/rest/film \
--url-quer](https://us-east-2.aws.neurelo.app/openapi/film?filter=%7B%22title%22%3A%20%7B%22contains%22%3A%20%22Shark%22%7D)y filter='{"title":{"contains":"Shark"}}' \
--header 'X-API-KEY: <api-key>'
```


# Neurelo API Reference (GraphQL)

## Introduction

This API documentation is intended to provide an overview of how Neurelo generates APIs based on your data definition. It will go into detail on how to perform operations using a sample schema definition. You can then apply these concepts and patterns to your own schema. Reference documentation generated specifically for your data definition is included in your specific project on Neurelo's Data Access Platform.

Neurelo provides two types of APIs that are automatically generated and available for use.&#x20;

* The REST API has predictable resource-oriented URLs, accepts JSON-encoded request bodies, returns JSON-encoded responses, and uses standard HTTP response codes, authentication, and verbs.&#x20;
* The GraphQL API exposes a single endpoint where clients can send GraphQL queries or mutations and a strictly-typed schema that be be shared across consumers.&#x20;

You can toggle between the GraphQL and REST API documentation when reviewing the documentation in the platform.

{% hint style="info" %}
Reference - [Neurelo Supported Databases and Versions](/references/supported-databases)
{% endhint %}

## API Headers

### <mark style="color:green;">Authentication</mark>

API calls to Neurelo are authenticated using an API Key for all API requests. This api key defines which environment the API request is interacting with. You can create an api key under the settings of the specific environment that you are trying to access. API Keys cannot be used across environments.

To utilize an api key, include it as a header with your API Request, using `X-API-KEY` as the key.

### <mark style="color:green;">Query Strategy</mark>

Neurelo generated APIs can be tuned to fetch data using either the `selects` or `joins` strategy. The main difference is that `selects` executes multiple queries behind the scenes to gather the desired data, whereas `joins` uses a single query when possible using database-level joins, to fetch the results.

By default, `joins` strategy is enabled. This can be changed using an HTTP header. For example if you are using cURL, then to fetch all the users and their corresponding posts using `selects` strategy:

```
curl -X POST https://$ENV_API_URL/graphql/
    --data '{"query": "query { findManyUser { name } }", "variables": {}}'
    --header 'X-READ-STRATEGY: selects'
```

Similarly, `'X-READ-STRATEGY: joins'` can be used.

`joins` strategy is suitable for scenarios where you want to minimize the number of queries made to the database, especially when the relation expressions are relatively simpler, and there's less risk of data duplication.

`selects` can be faster in scenarios with multiple many-to-many or one-to-many relations. This is because the database's flat record list from joins can sometimes contain a significant amount of repeated information. Despite joins' quick execution in the database, the process of moving and parsing this redundant data into JSON can incur high costs.

### <mark style="color:green;">Query Viz</mark>

To review the database queries that Neurelo will be sending to your data source, you can use the `X-QUERY-VIZ` HTTP header. For example, to enable query viz while fetching all the users and their corresponding posts:

```
curl https://$ENV_API_URL/graphql/
    --data '{"query": "query { findManyUser { name } }", "variables": {}}'
    --header 'X-QUERY-VIZ: true'
```

This header will return both the query string and its corresponding query parameters.

Similarly, `'X-QUERY-VIZ: false'` can be used to disable the viz. By default, this header is disabled.

{% hint style="danger" %}
IMPORTANT: When query viz is enabled, the queries will still run against your selected environment, and they may modify data in that environment depending on your queries.
{% endhint %}

## Operations

### <mark style="color:green;">Creating Objects</mark>

You can create objects by utilizing one of two mutations available for creating objects. These are `createOneObject` and `createManyObject`, where `Object` is the name of your object.

In this example, we will use a sample schema with a User object and a BlogPost object. A user has many posts, and a post has one user.

#### <mark style="color:purple;">Create one User</mark> (`CreateInput`)

To create a single user, assuming that we have the sample schema running in an environment, we can issue a `CreateOne` mutation, with the data argument set to the `UserCreateInput` input type. For example:

```
mutation {
  createOneUser(data: { name: "User 1", country: "Canada" }) {
    id
    name
    country
  }
}
```

The response from this insert request will look like this, which is the object that was inserted:

```
{
  "data": {
    "createOneUser": {
      "id": 1,
      "name": "Admin User",
      "country": "United States"
    }
  }
}
```

To prevent the insertion of records with unique fields or identifiers that already exist, we can use `skipDuplicates`. For example:

```
mutation {
  createOneUser(data: [{ id: 1, name: "User 1", country: "Canada" }, { id: 1, name: "User 2", country: "United States" }]) {
    id
    name
    country
  }
}
```

The response from this insert request will look like this, which is the inserted object(s):

```
{
  "data": {
    "createOneUser": {
      "id": 1,
      "name": "Admin User",
      "country": "United States"
    }
  }
}
```

In the above example, as User IDs were same, the second record was prevented from being inserted.

NOTE: Currently, `skipDuplicates` is not supported for MongoDB.

#### <mark style="color:purple;">Creating multiple objects</mark> (`CreateManyInput`)

To create multiple users, assuming that we have the sample schema running in an environment, we can issue a `CreateMany` mutation, with the data argument set to an array of `UserCreateInput` types.

```
mutation {
  createManyUser(data: [{ name: "User 1", country: "Canada" }, { name: "User 2", country: "United States" }]) {
    id
  }
}
```

The response (`AffectedRowsOutput`) from this insert request will look like this, which is the count of the inserted rows:

```
{
  "data": {
    "createManyUser": {
      "count": 2
    }
  }
}
```

NOTE: Currently, related objects cannot be created or associated with the 'root' object using `CreateManyInput`. To achieve this, it is necessary to use `CreateInput`.

#### <mark style="color:purple;">Creating with relations</mark>

{% hint style="info" %}
Currently, Neurelo for MongoDB does not directly support the creation of objects with relations. However, you can create inner objects (which are equivalent to embedded documents, meaning documents nested within another document) or use references to accommodate your data modeling needs. Refer to the [Modeling Relationships for MongoDB with Inner Objects and References section](#modeling-relationships-for-mongodb-with-inner-objects-and-references) for more information.
{% endhint %}

When creating a single user, you can create or connect related object in the same transaction.

On an object with a has one relationship to another object, you can use the `create` input to create a new related object automatically associated with the 'root' object. Alternatively, you can use the `connect` input to link an existing related object to the 'root' object. When using `connect`, an error will be thrown if the linked object is not found. To address this, use `connectOrCreate`, which links an existing related object to the 'root' object or creates a new related object if it doesn't exist.

On an object with a has many relationship to another object, you can also utilize `create`, `connect`, and `connectOrCreate`. Additionally, you can use `createMany` to create many related objects.

#### `create`

To demonstrate creating a root object and its related object, we will use a sample schema with a User object and a BlogPost object. A user has many posts, and a post has one user.

```
mutation {
  createOneUser(data: { name: "User 1", country: "Canada", posts: { create: [{ title: "Post Title" }] } }) {
    id
    name
    posts {
      id
      title
    }
  }
}
```

The response from this insert request will look like this, which is the inserted object(s):

```
{
  "data": {
    "createOneUser": {
      "id": 1,
      "name": "User 1",
      "posts": [
        {
          "id": 1,
          "title": "Post Title"
        }
      ]
    }
  }
}
```

#### `connect`

To create a root object and link it with an existing related object in a has many relationship, assuming that we have the sample schema running in an environment, we can use the `connect` input.

```
mutation {
  createOneUser(data: { name: "User 1", country: "Canada", posts: { connect: [{ id: 1 }] } }) {
    id
    name
    country
    posts {
      id
      title
    }
  }
}
```

The response from this insert request will look like this, which is the inserted object(s):

```
{
  "data": {
    "createOneUser": {
      "id": 1,
      "name": "User 1",
      "country": "Canada",
      "posts": [
        {
          "id": 1,
          "title": "Post Title"
        }
      ]
    }
  }
}
```

In the above example, the Post with an ID of 1 previously existed and is now being associated with a relationship with the new root object.

#### `connectOrCreate`

To create a root object and link it with an existing related object or create a new related object if it doesn't exist (when the root and related object are in a has many relationship), assuming that we have the sample schema running in an environment, we can use the `connectOrCreate` input. For example,

```
mutation {
  createOneUser(data: { name: "User 1", country: "Canada", posts: { connectOrCreate: [{ create: { title: "Post 1" }, where: { id: 3 } }] } }) {
    id
    name
    country
    posts {
      id
      title
    }
  }
}
```

The response from this insert request will look like this, which is the inserted object(s):

```
{
  "data": {
    "createOneUser": {
      "id": 1,
      "name": "User 1",
      "country": "Canada",
      "posts": [
        {
          "id": 2,
          "title": "Post 1"
        }
      ]
    }
  }
}
```

In the above example, by observing the Post's ID, we can conclude that the ID 3 was not found in the Post object. As a result, a new object was created.

#### `createMany`

To create a root object and link it with many related objects in a has many relationship, assuming that we have the sample schema running in an environment, we can use the `createMany` input.

```
mutation {
  createOneUser(data: { name: "User 1", country: "Canada", posts: { createMany: { data: [{ title: "Post Title 1" }, { title: "Post Title 2" }] } } }) {
    id
    name
    country
    posts {
      id
      title
    }
  }
}
```

The response from this insert request will look like this, which is the inserted object(s):

```
{
  "data": {
    "createOneUser": {
      "id": 1,
      "name": "User 1",
      "country": "Canada",
      "posts": [
        {
          "id": 1,
          "title": "Post Title 1"
        },
        {
          "id": 2,
          "title": "Post Title 2"
        }
      ]
    }
  }
}
```

Similar to `createInput`, you can use `skipDuplicates` in `createMany` to prevent the insertion of records with unique fields or identifiers that already exist.

### <mark style="color:green;">Retrieving Objects</mark>

You can retrieve objects by utilizing a few different queries that are generated for each object. There are three find queries available per object, they are `findFirstObject`, `findUniqueObject` and `findManyObject`.

In this example, we will use a sample schema with a User object and a BlogPost object. A user has many posts, and a BlogPost has one user. A user has a relationship property to posts called `posts` and the post has a relationship property to users called `author`.

#### <mark style="color:purple;">Retrieving unique object</mark>

To retrieve a unique user, assuming that we have the sample schema running in an environment, we can issue a query to `findUniqueUser` with a `where` argument that filters on unique properties. For example:

```
query {
  findUniqueUser(where: { id: 1 }) {
    name
  }
}
```

The response from this request will look like this, which is the retrieved object:

```
{
  "data": {
    "findUniqueUser": {
      "name": "User 1"
    }
  }
}
```

#### <mark style="color:purple;">Retrieving all objects</mark>

To retrieve all users, assuming that we have the sample schema running in an environment, we can issue a query with `findManyUser`. For example:

```
query {
  findManyUser {
    name
  }
}
```

The response from this request will look like this, which is an array of the retrieved objects:

```
{
  "data": {
    "findManyUser": [
      {
        "name": "User 1"
      },
      {
        "name": "User 2"
      }
    ]
  }
}
```

#### <mark style="color:purple;">Filtering for specific objects</mark>

To filter specific objects, we can utilize the `where` query argument. For complete documentation of all the options available to you with the query argument, take a look at the `WhereInput` input type documentation below.

To filter for specific User objects, assuming that we have the sample schema running in an environment, we can issue a query with the `where` argument set to the `UserWhereInput` input type.

```
query {
  findManyUser(where: { name: { contains: "Jane" } }) {
    name
  }
}
```

The response from this request will look like this, which is an array of the retrieved objects:

```
{
  "data": {
    "findManyUser": [
      {
        "name": "Jane"
      }
    ]
  }
}
```

#### <mark style="color:purple;">Retrieving related objects</mark>

To retrieve all users with their posts, assuming that we have the sample schema running in an environment, we can issue a query with `findManyUser`. For example:

```
query {
  findManyUser {
    name
    posts {
      name
      words
    }
  }
}
```

The response from this request will look like this, which is an array of the retrieved objects and their related objects:

```
{
  "data": {
    "findManyUser": [
      {
        "name": "User 1",
        "posts": [
          {
            "name": "My Trip to Egypt",
            "words": 1200
          },
          {
            "name": "My Trip to Canada",
            "words": 800
          }
        ]
      },
      {
        "name": "User 2",
        "posts": [
          {
            "name": "Greek mythology: Part 1",
            "words": 1000
          }
        ]
      }
    ]
  }
}
```

#### <mark style="color:purple;">Retrieving n-levels of related objects</mark>

Assume that in our sample schema, there is a new object Activity, such that each post has many activities. A post has a relationship property to activities called `activity`.

To retrieve all the users, their post names, and activities on each post, assuming that we have the sample schema running in an environment, we can issue a query with `findManyUser`. For example:

```
query {
  findManyUser {
    name
    posts {
      name
      activity {
        name
        action
      }
    }
  }
}
```

The response from this request will look like this, which is an array of the retrieved objects and their specific related objects:

```
{
  "data": {
    "findManyUser": [
      {
        "name": "User 1",
        "posts": [
          {
            "name": "My Trip to Egypt",
            "activity": [
              {
                "name": "User 123",
                "action": "Like"
              },
              {
                "name": "User 234",
                "action": "Share"
              }
            ]
          },
          {
            "name": "My Trip to Canada",
            "activity": [
              {
                "name": "User 345",
                "action": "Like"
              }
            ]
          }
        ]
      }
    ]
  }
}
```

### <mark style="color:green;">Updating Objects</mark>

You can update objects by using one of two update mutations, these are similar to the create mutations, but include a `where` argument to specify which objects should be updated. There are `updateOneObject` and a `updateManyObject` mutations available, `Object` being replaced by the object that you are performing the update on.

#### <mark style="color:purple;">Updating unique object</mark> (`UpdateInput`)

Updating a unique object is similar to updating many, except that the `where` argument is limited to filtering on unique properties. For example, the `id` property on User is a unique property and is guaranteed to be unique to a single User object.

```
mutation {
  updateOneUser(data: { name: "John" }, where: { id: 1 }) {
    name
  }
}
```

The response from this request will look like this, which is the updated object:

```
{
  "data": {
    "updateOneUser": {
      "id": 1,
      "name": "John"
    }
  }
}
```

#### <mark style="color:purple;">Updating multiple objects</mark> (`UpdateManyInput`)

To update multiple users, we can utilize the `updateManyObject` mutation with the `data` and `where` arguments to provide both our updated properties and a condition set to limit which objects are updated.

```
mutation {
  updateManyUser(data: { name: "John" }, where: { name: { contains: "Jane " } }) {
    count
  }
}
```

The response (`AffectedRowsOutput`) from this update request will look like this, which is the count of the updated rows:

```
{
  "data": {
    "updateManyUser": {
      "count": 1
    }
  }
}
```

#### <mark style="color:purple;">Updating scalars using special operations</mark>

#### `push`

When using the `array` type for a property, the `UpdateInput` provides a `push` operation. This inserts a value or array of values at the end of the array. If the value is null, it would initialize the array with the value(s) provided. For example,

```
mutation {
  updateOnePost(data: { name: "My updated .bashrc file", tags: { push: ["alias"] } }) {
    id
    name
    tags
  }
}
```

The response from this request will look like this, which is the updated object:

```
{
  "data": {
    "id": 1,
    "name": "My updated .bashrc file",
    "tags": ["termcolor", "alias"]
  }
}
```

#### <mark style="color:purple;">Updating with relations</mark>

{% hint style="info" %}
Currently, Neurelo for MongoDB does not directly support the updation of objects with relations. However, you can update inner objects (which are equivalent to embedded documents, meaning documents nested within another document) or use references to accommodate your data modeling needs. Refer to the [Modeling Relationships for MongoDB with Inner Objects and References section](#modeling-relationships-for-mongodb-with-inner-objects-and-references) for more information.
{% endhint %}

When updating a single object, you can create, update, disconnect or delete related object in the same transaction.

On an object with a has one relationship to another object, you can use the `update` input to update a related object automatically associated with the 'root' object. Alternatively, you can use the `disconnect` input to unlink an existing related object with the 'root' object. When using `update`, an error will be thrown if the linked object is not found. To address this, use `upsert`, which updates an existing related object to the 'root' object or creates a new related object if it doesn't exist. You can also use `delete` input to delete an existing related object.

The `connect`, `connectOrCreate`, and `create` inputs (as explained in the Creating objects with relations section) are also supported here.

On an object with a has many relationship to another object, you can also utilize `create`, `connect`, `connectOrCreate`, `update`, `upsert`, `delete`, and `disconnect` inputs. Additionally, you can use `createMany`, `updateMany`, and `deleteMany` to create, update, and delete many related objects, respectively.

`createMany` is explained in the Creating objects with relations section.

#### `update`

To demonstrate updating a root object and its related object, we will use a sample schema with a User object and a BlogPost object. A user has many posts, and a post has one user.

```
mutation {
  updateManyUser(where: { id: 1 }, data: { name: "Admin User 1", posts: { update: { where: { id: 2 }, data: { name: "My system configuration" } } } }) {
    id
    name
    posts {
      id
      name
    }
  }
}
```

The response from this update request will look like this, which shows the updated object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User 1",
    "posts": [
      {
        "id": 1,
        "name": "Test"
      },
      {
        "id": 2,
        "name": "My system configuration"
      }
    ]
  }
}
```

In the above example, the Post with an ID of 2 previously existed and is now being updated along with the name of the user.

#### `upsert`

To update a root object and update its corresponding related object or create a new related object if it doesn't exist (when the root and related object are in a has many relationship), assuming that we have the sample schema running in an environment, we can use the `upsert` input. For example,

```
mutation {
  updateManyUser(where: { id: 1 }, data: { name: "Admin User 1", posts: { upsert: { where: { id: 2 }, update: { name: "Hardware Info" }, create: { name: "Hardware Info" } } } }) {
    id
    name
    posts {
      id
      name
    }
  }
}
```

The response from this upsert request will look like this, which is the upsert object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User 1",
    "posts": [
      {
        "id": 1,
        "name": "Test"
      },
      {
        "id": 2,
        "name": "Hardware Info"
      }
    ]
  }
}
```

#### `disconnect`

To unlink an existing related object with the 'root' object (when the root and related object are in a has many relationship), assuming that we have the sample schema running in an environment, we can use the `disconnect` input. For example,

```
mutation {
  updateManyUser(where: { id: 1 }, data: { name: "Admin User 1", posts: { disconnect: { id: 2 } } }) {
    id
    name
    posts {
      id
      name
    }
  }
}
```

The response from this request will look like this, which is the updated object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User 1",
    "posts": [
      {
        "id": 1,
        "name": "Test"
      }
    ]
  }
}
```

In the above example, the Post with an ID of 2 previously existed and still exists, but it is now being unlinked with respect to the 'root' object. Furthermore, the name of the user also gets updated.

#### `delete`

To delete an existing related object asccociated with a 'root' object (when the root and related object are in a has many relationship), assuming that we have the sample schema running in an environment, we can use the `delete` input. For example,

```
mutation {
  updateManyUser(where: { id: 1 }, data: { name: "Admin User 1", posts: { delete: { id: 2 } } }) {
    id
    name
    posts {
      id
      name
    }
  }
}
```

The response from this request will look like this, which is the updated object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User 1",
    "posts": [
      {
        "id": 1,
        "name": "Test"
      }
    ]
  }
}
```

In the above example, the Post with an ID of 2 is now deleted. Furthermore, the name of the user also gets updated.

#### `updateMany`

To update a root object and its many related objects in a has many relationship, assuming that we have the sample schema running in an environment, we can use the `updateMany` input.

```
mutation {
  updateManyUser(where: { id: 1 }, data: { name: "Admin User 1", posts: { updateMany: [{ where: { id: 1 }, data: { name: "Test Blog" } }, { where: { id: 2 }, data: { name: "Hardware Info Blog" } }] } }) {
    id
    name
    posts {
      id
      name
    }
  }
}
```

The response from this updateMany request will look like this, which is the updated object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User 1",
    "posts": [
      {
        "id": 1,
        "name": "Test Blog"
      },
      {
        "id": 2,
        "name": "Hardware Info Blog"
      }
    ]
  }
}
```

#### `deleteMany`

To update a root object and delete its many related objects in a has many relationship, assuming that we have the sample schema running in an environment, we can use the `deleteMany` input.

```
mutation {
  updateManyUser(where: { id: 1 }, data: { name: "Admin User Empty", posts: { deleteMany: [{ id: 1 }, { id: 2 }] } }) {
    id
    name
    posts {
      id
      name
    }
  }
}
```

The response from this deleteMany request will look like this, which is the deleted object(s):

```
{
  "data": {
    "id": 1,
    "name": "Admin User Empty",
    "posts": []
  }
}
```

### <mark style="color:green;">Deleting Objects</mark>

You can delete objects by utilizing one of two mutations. These mutations are `deleteOneObject` and a `deleteManyObject` mutations available, where `Object` is the name of the object that you are deleting.

In this example, we will use a sample schema with a User object.

#### <mark style="color:purple;">Delete unique object</mark>

To delete a unique user, assuming that we have the sample schema running in an environment, we can issue a query to `deleteOneUser`. For example:

```
mutation {
  deleteOneUser(where: { id: 1 }) {
    id
    name
    country
  }
}
```

The response from this request will look like this, which is the deleted object:

```
{
  "data": {
    "id": 1,
    "name": "User 1",
    "country": "Canada"
  }
}
```

#### <mark style="color:purple;">Delete all objects</mark>

To delete all users, you can issue a `deleteManyUser` mutation with arguments present. For example:

```
mutation {
  deleteManyUser {
    count
  }
}
```

The response from this request will look like this, which is the count of the deleted object(s):

```
{
  "data": {
    "deleteManyUser": {
      "count": 1
    }
  }
}
```

#### <mark style="color:purple;">Delete specific objects</mark>

To delete specific objects, we can utilize the `where` argument. For complete documentation of all the options available to you with the query argument, take a look at the `WhereInput` input type documentation below.

To retrieve all specific, we can issue `deleteManyUser` with the where argument specified. For example:

```
mutation {
  deleteManyUser(where: { name: { contains: "John" } }) {
    count
  }
}
```

The response from this request will look like this, which is the count of the deleted object(s):

```
{
  "data": {
    "deleteManyUser": {
      "count": 1
    }
  }
}
```

### <mark style="color:green;">Aggregating Objects</mark>

You can aggregate objects by utilizing the `aggregateObject` query that is generated for each object. The following aggregate functions are supported: `_count`, `_sum`, `_avg`, `_min`, and `_max`.

In this example, we will use a sample schema with a Post object.

#### <mark style="color:purple;">Aggregating specific objects</mark>

To aggregate post objects, assuming that we have the sample schema running in an environment, we can issue a query with `aggregatePost`. For example, to average the number of words for post objects:

```
query {
  aggregatePost {
    _avg {
      words
    }
  }
}
```

The response (`AggregateOutput`) from this request will look like this, which contains the aggregated value:

```
{
  "data": {
    "aggregatePost": {
      "_avg": {
        "words": 1000.0
      }
    }
  }
}
```

#### <mark style="color:purple;">Aggregating all objects</mark>

Presently, only `_count` function supports aggregating all objects.

To count all objects, assuming that we have the sample schema running in an environment, we can issue a query with `aggregatePost` with the `_count` function and `_all` value specified for it. For example,

```
query {
  aggregatePost {
    _count {
      _all
    }
  }
}
```

The response (`AggregateOutput`) from this request will look like this, which contains the aggregated value:

```
{
  "data": {
    "aggregatePost": {
      "_count": {
        "_all": 2
      }
    }
  }
}
```

### <mark style="color:green;">Grouping Objects</mark>

In this example, we will use a sample schema with a User object.

You can group by objects by utilizing the `groupByObject` query that is generated for each object. It is mandatory to include a `by` option to group records by one or more fields. This option takes an array of field names (`Array`), to specify the fields to group by with.

For example, to count the number of users by country:

```
query {
  groupByUser(by: [country]) {
    country
    _count {
      id
    }
  }
}
```

The response from this request will look like this, which is the grouped and aggregated object(s):

```
{
  "data": {
    "groupByUser": [
      {
        "country": "United States",
        "_count": {
          "id": 1
        }
      },
      {
        "country": "Canada",
        "_count": {
          "id": 1
        }
      }
    ]
  }
}
```

#### <mark style="color:purple;">Group By with Filtering</mark>

To filter the fields before grouping, we can utilize the `where` option. For example,

```
query {
  groupByUser(where: { country: { startsWith: "C" } }, by: [country]) {
    country
    _count {
      id
    }
  }
}
```

The response from this request will look like this, which is the grouped and aggregated object:

```
{
  "data": {
    "groupByUser": [
      {
        "country": "Canada",
        "_count": {
          "id": 1
        }
      }
    ]
  }
}
```

To filter the groups by aggregate functions, we can utilize the `having` option.

```
query {
  groupByUser(having: { id: { _count: { lte: 2 } } }, by: [country]) {
    country
    _count {
      id
    }
  }
}
```

The response from this request will look like this, which is the grouped and aggregated object(s):

```
{
  "data": {
    "groupByUser": [
      {
        "country": "United States",
        "_count": {
          "id": 1
        }
      },
      {
        "country": "Canada",
        "_count": {
          "id": 1
        }
      }
    ]
  }
}
```

## Input Types

In this section, we’ll take a look at some arguments that apply to many different operations. The avaliability of each argument is dependent on the operation being performed, for example, the `WhereInput` argument is not available on Insert operations.

Once you are familiar with these arguments, we hope that utilizing individual operations on your objects comes naturally and will not require continous referral to the generated reference documentation.

### <mark style="color:green;">`where`</mark> <mark style="color:green;"></mark><mark style="color:green;">(</mark><mark style="color:green;">`WhereInput`</mark><mark style="color:green;">)</mark>

The `WhereInput` argument allows you to add conditions to your query. This argument can be used when retrieving objects, as well as when updating objects where it will act as the condition on which objects are updated.

#### <mark style="color:purple;">Filtering with Scalars</mark>

Each scalar has it’s own set of operations that can be performed to assert a condition, for example, an integer has the following operators available to it: `equals`, `not`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`. With the exception of `in` and `notIn`, all of these operators will accept the matching scalar, `in` and `notIn` will take an array of the matching scalar.

Here is a list of all available operators: `equals`, `not`, `in`, `notIn`, `lt`, `lte`, `gt`, `gte`, `contains`, `startsWith`, and `endsWith`. The availiblity of these is dependant on the scalar type, for example, you cannot utilize the `gt` operator on a string.

A where condition for a given object includes all of the scalars present on the object with their respective scalar filter type. To construct a where condition utilizing only an object’s scalar properties, you can use the name of the property as the key, and then a where object for that specific scalar type.

Here is a more comprehensive overview of these operators:

| Operator            | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              | Example                                                                                                                                                                                                                                                                               |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| equals              | Filter for field values equal to a specific value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | To filter when `age` equals 21, `{ age: { equals: 21 } }`                                                                                                                                                                                                                             |
| lt/lte              | Filter for field values "less than / less than or equal to" a specific value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | To filter when `age` is less than 21, `{ age: { lt: 21 } }`                                                                                                                                                                                                                           |
| gt/gte              | Filter for field values "greater than / greater than or equal to" a specific value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | To filter when `age` is greater than or equal to 30, `{ age: { gte: 30 } }`                                                                                                                                                                                                           |
| not                 | Filters when field value does not equal a specific value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | To filter records that have all ids except `100`, `{id: {not: 100}}`                                                                                                                                                                                                                  |
| in/notIn            | Checks if a field value exists / does not exist in a list, and filters accordingly.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | To filter records having ids as either `1`, `3` or `6`, `{ id: { in: [1, 3, 6] } }`                                                                                                                                                                                                   |
| startsWith/endsWith | Filter when a specific value is at the start or end of a field value. Case-sensitive by default. `_` wildcard can be used to match one or more characters. `$` wildcard can be used to match zero or more characters.                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | To filter names that start with "Ron" (case-insensitive), `{name: {startsWith: "Ron", mode: "insensitive"} }`. To filter names that start with "R", followed by one or more characters, and then "d", `{name: {startsWith: "R_d"} }`. This matches names such as "Roland" and "Rudd". |
| contains            | Filters when a specific value is contained in a field value. Case-sensitive by default. `_` wildcard can be used to match one or more characters. `$` wildcard can be used to match zero or more characters.                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | To filter country names that contain the word "United", `{country: {contains: "United" } }`                                                                                                                                                                                           |
| search              | Filters using full-text search capabilities. This operator is specific to strings and currently, it is not supported with MongoDB. Currently, this operator is not supported with MongoDB. For querying, PostgreSQL and MySQL's native full-text search capabilities are leveraged. For example, in Postgres, `&` can be used to perform a boolean AND on two strings. Similarly, `\|` and `!` can be used to perform boolean OR and boolean NOT, respectively. For MySQL, `+` and `-` are used as boolean AND and boolean NOT, respectively. Boolean OR in MySQL is represented using no operators; for example, `Tomato Orange` would check if the text contains `Tomato` or `Orange`. | In PostgreSQL, to filter records with the engine as Firefox or Chrome, use `{engine: {search: "Firefox \| Chrome"}}`. In MySQL, to filter records with Firefox but not Chrome in the report, use `{report: {search: "+Firefox -Chrome"}}`.                                            |

#### <mark style="color:purple;">Combining conditions</mark>

When you add conditions to a `WhereInput` object, you are asserting that all of the listed conditions must evaluate to true for an object to be returned, but you are also able to further customize your query’s condition by utilizing the `AND`, `OR`, and `NOT` properties. All of these properties accept an array of the object’s WhereInput type, allowing you to nest and compose different filtering conditions to construct your query.

Here is a more comprehensive overview of these operators:

| Operator | Description                                                  | Example                                                                                                                                                                                                                                                                                                                                                               |
| -------- | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| OR       | Filters for field values when one or more conditions is true | To filter names starting with either "A" or "B", `{OR: [{name: {startsWith: "A"}}, {name: {startsWith: "B"}}]}`. Furthermore, to filter names starting with "A" or ending with "n", `{OR: [{name: {startsWith: "A"}}, {name: endsWith: "n"}]}`.                                                                                                                       |
| AND      | Filters for field values when all conditions are true        | To filter for first names starting with "A" and last names ending with "n", `{AND: [{firstName: {startsWith: "A"}}, {lastName: {endsWith: "n"}}]}`. Furthermore, to filter names starting with "B" and ending with "n", we can use operators such as `startsWith` and `endsWith` in a single object itself, like `{AND: [{name: {startsWith: "B", endsWith: "n"}}]}`. |
| NOT      | Filters for field values when all the conditions are false   | To filter for names that are not "Alan" and not "George", `{NOT: [{name: {equals: "Alan"}}, {name: {equals: "George"}}]}`. Furthermore, to filter names not starting with "C" and not ending with "n", we can use operators such as `startsWith` and `endsWith` in a single object itself, like `{NOT: [{name: {startsWith: "C", endsWith: "n"}}]}`.                  |

Note on Scope of Logical operators:

* Implicit AND: Combining conditions within one object, `{name: {startsWith: "A", endsWith: "n"}}`, uses an implicit `AND` logic, meaning all conditions must be met.
* Explicit Logical Operators: Using `OR`, `AND`, or `NOT` to combine multiple conditions, such as `{OR: [ {...}, {...} ]}`, processes each condition in its own scope before applying the logical operator. This structure allows for complex filtering, evaluating from the inner-most conditions outwards.

Furthermore, you can combine these operators to do more powerful filtering. For example,

* `NOT` and `AND`: To filter for names that do no start with "A" and end with "n", `{NOT: {AND: [{name: {startsWith: "A"}}, {name: {endsWith: "n"}}]}}`.
* `OR` and `AND`: To filter for ids that are between 0 to 10 or 30 to 40, `{OR: [{AND: [{id: {gte: 0}}, {id: {lte: 10}}]}, {AND: [{id: {gte: 30}}, {id: {lte: 40}}]}]}`.

#### <mark style="color:purple;">Filtering with List</mark>

You can use the following operators to perform filtering with lists: `has`, `hasSome`, `hasEvery`, and `isEmpty`.

Additionally, you can employ the `equals` operator introduced earlier.

Here is a more comprehensive overview of these operators:

| Operator | Description                                                             | Example                                                                                                                                          |
| -------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| has      | Filters for lists where a given value exists.                           | To filter when `Canada` is in a `locations` list, `{locations: {has: "Canada"}}`                                                                 |
| hasSome  | Filters for lists where at least one value from the search list exists. | To filter when `Canada` or `United States` are in a `locations` list, `{locations: {hasSome: ["Canada", "United States"]}}`                      |
| hasEvery | Filters for lists where all values from the search list exists.         | To filter when `Canada`, `United States`, and `Spain` are in a `locations` list, `{locations: {hasEvery: ["Canada", "United States", "Spain"]}}` |
| isEmpty  | Filters for empty lists.                                                | To filter for empty `locations` list, `{locations: {isEmpty: true}}`. Similarly, to filter for non-empty lists, use `{isEmpty: false}`.          |

#### <mark style="color:purple;">Filtering with JSON</mark>

You can use the following operators to perform JSON filtering: `array_starts_with`, `array_ends_with`, `array_contains`, `string_starts_with`, `string_ends_with`, and `string_contains`.

Additionally, you can employ operators introduced earlier, such as `equals`, `gt`, `gte`, `lt`, `lte`, and `not`.

To filter a specific part of the JSON object, each of these operators requires a specified `path`. For example, consider a JSON object like `{Produce: {Fruits: {Organic: ["Orange", "Mango", "Banana"], NonOrganic: ["Apple", "Melon"]}}}`. In Postgres, the path `Produce -> Fruits -> Organic` can be represented as `["Produce", "Fruits", "Organic"]`. Similarly, for MySQL, it can be represented as `'$.Produce.Fruits.Organic'`.

Here is a more comprehensive overview of these operators (all the paths are specific to Postgres):

| Operator             | Description                                                                                     | Example                                                                                                                                                                                         |
| -------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| array\_starts\_with  | Filters for JSON objects where a specified path has a list that begins with a specific value.   | To filter when the list at `["Fruits", "Organic"]` path starts with `Orange`, `{Crops: {path: ["Fruits", "Organic"], array_starts_with: "Orange"}}`                                             |
| array\_ends\_with    | Filters for JSON objects where a specified path has a list that ends with a specific value.     | To filter when the list at `["Fruits", "Organic"]` path ends with `Apple` , `{Crops: {path: ["Fruits", "Organic"], array_starts_with: "Apple"}}`                                                |
| array\_contains      | Filters for JSON objects where a specified path has a list that contains a specific value.      | To filter when the list at `["Schedule", "Heathrow"]` path contains 9 , `{Misc: {path: ["Schedule", "Heathrow"], array_contains: 9}}`                                                           |
| string\_starts\_with | Filters for JSON objects where a specified path has a string that begins with a specific value. | To filter when the string at `["Premium Customers", "NYC", "George"]` path starts with `Q2F0cw==` , `{IDs: {path: ["Premium Customers", "NYC", "George"], string_starts_with: "Q2F0cw=="}}`     |
| string\_ends\_with   | Filters for JSON objects where a specified path has a string that ends with a specific value.   | To filter when the string at `["Premium Customers", "NYC", "George"]` path ends with `TmV1cmVsbw==` , `{IDs: {path: ["Premium Customers", "NYC", "George"], string_ends_with: "TmV1cmVsbw=="}}` |
| string\_contains     | Filters for JSON objects where a specified path has a string that contains a specific value.    | To filter when the string at `["FullReport", "Browser"]` path contains `Firefox` , `{Details: {path: ["FullReport", "Browser"], string_contains: "Firefox"}}`                                   |

#### <mark style="color:purple;">Filtering with Relations</mark>

You are able to utilize related objects in a condition too, though the manner in which you do so will depend on the type of relationship that this object has with it’s related object.

When a relationship has one of another object, you can utilize the `is` and `isNot` filters to construct conditions on a related object. For example, if we have a Post object, which has one User object, we can create a condition utilizing the User’s objects properties like so: `{ user: { is: { name: { equal: "George" } } } }`. This filter would return all Post objects where the related User’s name is equal to George.

When a relationship has many of another object, you can utilize the `some`, `every`, and `none` conditions to construct conditions on a set of related objects. For example, if we have a User object that has many Posts, we can create a condition utilizing the Post’s objects properties like so:`{ posts: some: [ { title: { equal: "Cats" } } ] }`. This will return a list of users where at least one of their posts has the title of “Cats”.

Here is a more comprehensive overview of these operators:

| Operator | Description                                                                                                                                        | Example                                                                                                                                                         |
| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| is       | Filters a record when related record "is" equal to the filter condition. Can only be used when a relationship has one of another object.           | If every user has one post, to filter when name equals Alan, `{ user: { is: { name: { equal: "Alan" } } } }`                                                    |
| isNot    | Filters a record when related record "is not" equal to the filter condition. Can only be used when a relationship has one of another object.       | If every user has one post, to filter when name does not start with "A", `{ user: { isNot: { name: { startsWith: "A" } } } }`                                   |
| some     | Filters a record when related record has "some" filter conditions as true. Can only be used when a relationship has many of another object.        | If a brand has many sauces, to find out brands that have "Paprika" in some of their sauces, `{ sauces: { some: [ { ingr: { contains: "paprika" } } ] } }`       |
| every    | Filters a record when related record has "every" filter conditions as true. Can only be used when a relationship has many of another object.       | If a brand has many sauces, to find out brands that have "Paprika" in all of their sauces, `{ sauces: { every: [ { ingr: { contains: "paprika" } } ] } }`       |
| none     | Filters a record when related record has "none" of its filter conditions as true. Can only be used when a relationship has many of another object. | If a brand has many sauces, to find out brands that do not have "Paprika" in any of their sauces, `{ sauces: { none: [ { ingr: { contains: "paprika" } } ] } }` |

Note: You can combine the three sections above to construct complex queries.

### <mark style="color:green;">`order_by`</mark> <mark style="color:green;"></mark><mark style="color:green;">(</mark><mark style="color:green;">`OrderByWithRelationInput`</mark><mark style="color:green;">)</mark>

The `orderBy` argument takes an array of objects, with the following definition:

`{ [key: ScalarName]: "asc" | "desc" }`

You can use any scalar on the object being queried as a key, along with the direction of the sort as the value in the object. Our GraphQL APIs support ordering of nested fields.

For example, given a sample schema with a User object:

```
{
  findManyUser(orderBy: { id: desc }) {
    id
    name
    posts(orderBy: { id: asc }) {
      id
      name
    }
  }
}
```

The response from this request will look like this:

```
{
  "data": {
    "findManyUser": [
      {
        "id": 2,
        "name": "User 2",
        "posts": [
          {
            "id": 1,
            "name": "Post 1"
          },
          {
            "id": 2,
            "name": "Post 2"
          }
        ]
      },
      {
        "id": 1,
        "name": "User 1",
        "posts": []
      }
    ]
  }
}
```

### <mark style="color:green;">`skip`</mark> <mark style="color:green;"></mark><mark style="color:green;">&</mark> <mark style="color:green;"></mark><mark style="color:green;">`take`</mark>

Pagination with Neurelo’s APIs works using the `skip` and `take` options as an implementation of offset based pagination. You can pass an integer to each option to limit or skip the resulting objects.

For example, given a sample schema with a User object, to skip one record and take the next record:

```
{
  findManyUser(skip: 1, take: 1) {
    id
    name
  }
}
```

The response from this request will look like this:

```
{
  "data": {
    "findManyUser": [
      {
        "id": 2,
        "name": "User 2"
      }
    ]
  }
}
```

### <mark style="color:green;">`by`</mark>

The `by` option takes an array of field names (`Array`), to specify the fields to group by with. It must be ensured that every selected scalar field in your graphql body that is not part of an aggregation must be included in `by` option's array of field names.

For example, let us use a sample schema with a User object,

```
# If the selected scalar fields in graphql body are name and country, then by needs to equal ["name", "country"].
query {
  groupByUser(by: [name, country]) {
    name
    country
    _count {
      id
    }
  }
}
```

The response from this request will look like this:

```
{
  "data": {
    "groupByUser": [
      {
        "country": "United States",
        "_count": {
          "id": 1
        }
      },
      {
        "country": "Canada",
        "_count": {
          "id": 1
        }
      }
    ]
  }
}
```

### <mark style="color:green;">`having`</mark> <mark style="color:green;"></mark><mark style="color:green;">(</mark><mark style="color:green;">`HavingInput`</mark><mark style="color:green;">)</mark>

`having` option is used in conjuction with `by` option to filter the groups by aggregate functions. It is a special kind of `where` which accepts all the `where` options, together with the ability to filter aggregate functions.

To filter by aggregate function, the following definition can be used:

`{ [field: ScalarName]: { [key: aggregateFunction]: whereCondition } }`

Supported aggregate functions are: `_count`, `_sum`, `_avg`, `_min`, and `_max`. whereCondition is the same as a `where` body and accepts all the `where` options.

For example, let us use a sample schema with a Post object,

```
query {
  groupByPost(by: [location], having: { num_words: { _sum: { gte: 1000000 } } }) {
    location
    _sum {
      num_words
    }
  }
}
```

The response from this request will look like this, which is the grouped and aggregated object(s):

```
{
  "data": {
    "groupByPost": [
      {
        "location": "United States",
        "_sum": {
          "id": 5179839
        }
      },
      {
        "location": "India",
        "_sum": {
          "id": 3044357
        }
      }
    ]
  }
}
```

Furthermore, similar to `filter`, you can use `AND`, `OR`, and `NOT` operators to do more powerful filtering. For example, to filter when the number of words is between 1000 and 10000, you can use `{"OR": [{"id": {"_sum": {"gte": 1000}}}, {"id": {"_sum": {"lte": 10000}}}]}`.

### <mark style="color:green;">`cursor`</mark>

`cursor` option is used to retrieve results before or after a specified cursor. This cursor is a unique identifier or a combination of unique identifiers.

Implicitly an ordering is performed based on the unique identifiers specified in the cursor, to ensure a consistent and predictable sequence of results.

For example, let us consider a sample schema with a User object. To fetch all users with IDs less than or equal to 2, the following can be used:

```
query {
  findManyUser(cursor: { id: 2 }, orderBy: { id: desc }) {
    id
    name
  }
}
```

The response from this request will look like this:

```
{
  "data": {
    "findManyUser": [
      {
        "id": 2,
        "name": "User 2"
      },
      {
        "id": 1,
        "name": "User 1"
      }
    ]
  }
}
```

Furthermore, to fetch the user after skipping two users, starting from ID 3, we can use the following:

```
query {
  findManyUser(cursor: { id: 3 }, skip: 2, take: 1) {
    id
    name
  }
}
```

The response from this request will look like this:

```
{
  "data": {
    "findManyUser": [
      {
        "id": 5,
        "name": "User 5"
      }
    ]
  }
}
```

In the above example, User IDs 3 and 4 were skipped, and the result set of User ID 5 was returned.

NOTE: Currently, the REST APIs do not have an equivalent functionality. As a workaround, use `order_by` to sort the primary keys, followed by `filter` to exclude the primary keys. For instance, `cursor: { id: 3 }` would have an equivalent of `order_by=[{"id": "asc"}]` with `filter={"id": {"gte": 3}}`.

### Modeling Relationships for MongoDB with Inner Objects and References

Currently, Neurelo for MongoDB doesn't support direct manipulation of objects with relations. However, you can work with inner objects (equivalent to embedded documents, i.e., documents nested within another document) or use references to model such relationships.

To decide which data modeling approach suits your needs best, refer to our guide on [how to work with embedded documents and references in MongoDB](/guides/how-to-work-with-embedded-documents-and-references-in-mongodb).

In summary, inner objects enhance read performance by reducing database queries and ensuring atomic updates within a single document. They are optimal for closely related data that is frequently accessed together, remains relatively static, and adheres to the 16MB document size limit. However, they might lead to data redundancy and scalability challenges as your database grows.

On the other hand, references are more suitable for large or frequently changing data. They excel in many-to-many relationships by offering the flexibility to link documents across different collections, preventing data duplication and maintaining database normalization. The trade-off, however, is the need for additional queries to get related data, which could affect your performance.

**Inner Objects**

Neurelo supports the management of inner objects at the schema level. To learn how to create inner objects for your schema, please refer to the Neurelo Schema Language reference.

Now, assume that will have a sample schema with a User object and an Address inner object. A user **has one** address. For example,

```json
{
  "objects": {
    "user": {
      "properties": {
        "id": {
          "type": "string",
          "sourceName": "_id",
          "sourceType": "ObjectId",
          "default": {
            "function": "auto"
          },
          "identifier": true
        },
        "name": {
          "type": "string"
        },
        "address": {
          "$ref": "#/innerObjects/Address",
          "nullable": true
        }
      }
    }
  },
  "innerObjects": {
    "Address": {
      "properties": {
        "id": {
          "type": "string",
          "sourceType": "ObjectId"
        },
        "street": {
          "type": "string"
        },
        "city": {
          "type": "string"
        },
        "zipcode": {
          "type": "string"
        }
      }
    }
  }
}
```

**Create**

To create a single user with its address, assuming that we have the sample schema running in an environment, we can issue a `CreateOne` mutation, with the data argument set to the `userCreateInput` input type. For example:

```graphql
mutation {
  createOneuser(data: { name: "Admin User", address: { set: { id: "5ca4bbc7a2dd94ee5816238d", street: "Diagon Alley", zipcode: "27000", city: "Nowhere Land" } } }) {
    id
    name
    address {
      id
      street
      city
      zipcode
    }
  }
}
```

Note that, at present, our APIs **do not allow** the user to auto generate inner object ids, hence we had to manually specify it in the above examples.

The response from this insert request will look like this, which is the object that was inserted:

```json
{
  "data": {
    "createOneuser": {
      "id": "65eb623e591811da1638040a",
      "name": "Admin User",
      "address": {
        "id": "5ca4bbc7a2dd94ee5816238d",
        "street": "Diagon Alley",
        "city": "Nowhere Land",
        "zipcode": "27000"
      }
    }
  }
}
```

To create multiple users with their address, we can issue a `CreateMany` mutation, with the data argument set to an array of `userCreateInput` types.

```graphql
mutation {
  createManyuser(data: [{ name: "Admin User", address: { set: { id: "5ca4bbc7a2dd94ee5816238d", street: "Diagon Alley", zipcode: "27000", city: "Nowhere Land" } } }, { name: "Admin User 2", address: { set: { id: "5ca4bbc7a2dd94ee5816238e", street: "King's Court", zipcode: "27100", city: "Nashville" } } }]) {
    count
  }
}
```

The response (`AffectedRowsOutput`) from this insert request will look like this, which is the count of the inserted rows:

```json
{
  "data": {
    "createManyuser": {
      "count": 2
    }
  }
}
```

**Retrieve**

To retrieve a unique user with its address, assuming that we have the sample schema running in an environment, we can issue a query to `findUniqueUser` with a `where` argument that filters on unique properties. For example:

```graphql
query {
  findUniqueuser(where: { { id: "65eb623e591811da1638040a" } }) {
    id
    name
    address {
      id
      street
      city
      zipcode
    }
  }
}
```

The response from this request will look like this, which is the retrieved object:

```json
{
  "data": {
    "findUniqueuser": {
      "id": "65eb623e591811da1638040a",
      "name": "Admin User",
      "address": {
        "id": "5ca4bbc7a2dd94ee5816238d",
        "street": "Diagon Alley",
        "city": "Nowhere Land",
        "zipcode": "27000"
      }
    }
  }
}
```

Similarly, to retrieve all users with their address, assuming that we have the sample schema running in an environment, we can issue a query with `findManyuser`. For example:

```graphql
query {
  findManyuser {
    id
    name
    address {
      id
      city
      street
      zipcode
    }
  }
}
```

The response from this request will look like this, which is an array of the retrieved objects (with their inner objects):

```json
{
  "data": {
    "findManyuser": [
      {
        "id": "65eb623e591811da1638040a",
        "name": "Admin User",
        "address": {
          "id": "5ca4bbc7a2dd94ee5816238d",
          "street": "Diagon Alley",
          "city": "Nowhere Land",
          "zipcode": "27000"
        }
      }
    ]
  }
}
```

**Update**

To update multiple users with their address, we can utilize the `updateManyObject` mutation with the `data` and `where` arguments to provide both our updated properties and a condition set to limit which objects are updated.

```graphql
mutation {
  updateManyuser(data: { address: { set: { id: "5ca4bbc7a2dd94ee5816238d", street: "High Street", city: "Nowhere Land", zipcode: "27000" } } }, where: { address: { is: { id: { equals: "5ca4bbc7a2dd94ee5816238d" } } } }) {
    count
  }
}
```

The response (`AffectedRowsOutput`) from this update request will look like this, which is the count of the updated rows:

```json
{
  "data": {
    "updateManyuser": {
      "count": 1
    }
  }
}
```

**Delete**

To delete specific users with their address, you can issue a `deleteOneuser` mutation with arguments present. For example:

```graphql
mutation {
  deleteOneuser(where: { id: "65eb623e591811da1638040a" }) {
    id
    name
    address {
      id
      street
      city
      zipcode
    }
  }
}
```

The response from this request will look like this, which is the deleted object:

```json
{
  "data": {
    "deleteOneuser": {
      "id": "65eb623e591811da1638040a",
      "name": "Admin User",
      "address": {
        "id": "5ca4bbc7a2dd94ee5816238d",
        "street": "Diagon Alley",
        "city": "Nowhere Land",
        "zipcode": "27000"
      }
    }
  }
}
```

Note that this will **delete both the object and its inner object.** To remove the contents of just the inner object, you can use the UPDATE request with an `unset`:

```graphql
mutation {
  updateManyuser(data: { address: { unset: true } }, where: { id: { equals: "65eb623e591811da1638040a" } }) {
    count
  }
}
```

This approach requires setting the inner object of your schema, specifically the unique ID, to have `nullable` set to `true`.

## API Errors

Errors for the API calls will be presented in a list format so that multiple issues can be communicated at once. Each error object will contain an `errors` property that contains the error message and the location of the error.

Two types of errors can be returned as a response:

* Validation errors - request is invalid or contains invalid data
* Execution errors - request execution failed

For example, a sample schema and a sample request like:

```
{
  "objects": {
    "actor": {
      "properties": {
        "actor_id": {
          "type": "integer",
          "identifier": true
        },
        "first_name": {
          "type": "string"
        },
        "last_name": {
          "type": "string"
        },
        "movie_count": {
          "type": "integer"
        }
      }
    }
  }
}
```

```
query {
  findManyActor(where: { movie_count: { gt: "3" } }) {
    id
    firstname
  }
}
```

Will generate the following response:

```
{
  "data": null,
  "errors": [
    {
      "message": "Invalid value for argument \"where.movie_count.gt\", expected type \"Int\"",
      "locations": [
        {
          "line": 2,
          "column": 18
        }
      ]
    },
    {
      "message": "Unknown field \"firstname\" on type \"Actor\". Did you mean \"first_name\"?",
      "locations": [
        {
          "line": 4,
          "column": 9
        }
      ]
    }
  ]
}
```

The above example contains two errors, each with an error message and the specific location of the invalid attribute in the details section. The location parameter contains a JSON path to the attribute that failed the validation.

<br>


# SDKs

Neurelo provides a range of SDKs designed to work seamlessly with the APIs generated from your schema. Currently, we offer SDKs for the following languages:

* TypeScript / JavaScript
* Go
* Python

## **Downloading SDKs**

You can download the Neurelo SDKs either through our web interface or using our CLI.

**Via Web Interface:**

1. Navigate to the **Definitions** page located in the sidebar.&#x20;
2. Select the **Docs** tab.
3. Click on the **SDKs** button on the right-hand side to download the desired SDK.

{% hint style="info" %}
You can also download these from under the **APIs** tab in your **Environment**
{% endhint %}

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2F79C736fJtasCJwQJ5BU3%2FScreenshot%202024-05-30%20at%209.36.44%20AM.png?alt=media&amp;token=c4272409-459b-453b-acb6-999a42d061f9" alt=""><figcaption></figcaption></figure>

**Via CLI:**

1. [Download and install the Neurelo CLI](/cli-preview-version)
2. Login with `neurelo login` and select the project that you'd like to use with `neurelo project use`
3. Run `neurelo sdk download`, you can provide a commit ID, or leave that field blank to download an SDK based on the most recent commit in your project


# TypeScript / JavaScript SDK

## Overview

The generated Neurelo TypeScript/JavaScript for NodeJS SDK provides easy access to your Neurelo APIs for your applications.

## Installation

* [Download the Typescript / Javascript SDK for your project](/sdks)
* Install the SDK:

  `npm i ./neurelo-sdk-typescript-cmt_<id>.tgz`
* Commit the `.tgz` file along with the package.json and package-lock.json

## Getting Started

Neurelo's TypeScript / JavaScript SDK expects two environment variables to be configured:

* `NEURELO_API_BASE_PATH`&#x20;
  * This is the endpoint for the region where your environment is running, for example, if your environment is running in Neurelo's `us-east-2` gateway, the value for this variable should be `https://us-east-2.aws.neurelo.com`
* `NEURELO_API_KEY`
  * This is the API key generated for your environment under the API Keys tab.

<details>

<summary>Replacing or modifying Neurelo's HTTP Client</summary>

To replace Neurelo's [Axios](https://www.npmjs.com/package/axios) client, you can create a `neurelo.config.ts` or `neurelo.config.js` file in your project's root directory. The configuration file should export a named variable called `customAxios` with your new Axios instance.

</details>

Once you've installed and configured your Neurelo SDK, you're ready to import the generated services into your application for use.&#x20;

For example, if a data definition had an Address object present, we would be able to import the `AddressApiService` and utilize various methods to interact with the application's data, as is shown below:

```typescript
import { AddressApiService } from 'neurelo-sdk';

try {
    const response = await AddressApiService.findAddress();
    const addresses = response.data.data;
    
    console.log(addresses);
} catch (error) {
    console.error('Failed to retrieve list of addresses', error);
}
```

For further documentation on the operations available for each of your objects, or how to construct parameters like Select or Where inputs, please see the documentation available inside the 'Docs' tab under the 'Definitions', or under the 'APIs' tab of the 'Environments' of your project

To review an example of an application built using Neurelo's SDK, please visit [Project Examples](/project-examples#projects-built-using-neurelo-sdks)&#x20;


# Go SDK

## Overview

Neurelo's Go SDK allows you to quickly and easily integrate your app with Neurelo APIs. This SDK is generated from the API spec and provides a set of methods to interact with the API endpoints. The generator creates a Go client that utilizes the std package `net/http` to make HTTP requests. Tested with Go v1.22.3

## Prerequisites

* Go binaries are installed on your system and included in your path.
* Download your generated SDK from the API pages of your project & move the generated SDK file `neurelo-sdk-golang-cmt_<id>.zip` to your project root.
* Tools for configuring environment variables (e.g. [github.com/joho/godotenv](https://github.com/joho/godotenv)) or simply export before starting your dev server (inline).

## Installation

* Copy the generated sdk `neurelo-sdk-golang-cmt_<>.zip` to your project
* Unzip the sdk to `project_root/pkg/neurelo_sdk`
* Add the dependencies to your `go.mod` file

```bash
mkdir -p ./pkg/neurelo_sdk &&\
unzip neurelo-sdk-golang-cmt_<>.zip -d ./pkg/neurelo_sdk &&\
go get github.com/oapi-codegen/runtime
```

## Usage

* Make sure to set `NEURELO_API_ENDPOINT` and `NEURELO_API_KEY` env variables before using the client or you can set them in the client file.
* Create a client file, so that it can be used by other files in the project.

```go
// src/lib/client.go
package lib

import (
  "context"
  "net/http"
  "os"

  // Replace the <project_root> with your project url. eg: github.com/neurelo-public/neurelo-sdk
  neurelo_sdk "<project_root>/pkg/neurelo_sdk"
)

var ApiClient *neurelo_sdk.Client

func RequestEditor(ctx context.Context, req *http.Request) error {
  req.Header.Set("X-API-KEY", os.Getenv("NEURELO_API_KEY"))
  return nil
}

// Setup client after reading env variables or in main.go
func SetupApiClient() {
  hc := http.Client{}
  server := os.Getenv("NEURELO_API_ENDPOINT")
  api_client := neurelo_sdk.Client{
    Server: server,
    Client: &hc,
    RequestEditors: []neurelo_sdk.RequestEditorFn{
    RequestEditor,
    },
  }
  ApiClient = &api_client
}
```

### API Usage

* Use the client in other files to make API calls.

```go
// main.go
package main

import (
  "context"
  "fmt"

  // Replace the <project_root> with your project url. eg: github.com/neurelo-public/neurelo-sdk
  neurelo_sdk "<project_root>/pkg/neurelo_sdk"
  lib "<project_root>/src/lib"
)

func Execute() {
  ctx := context.Background()

  take := 10
  skip := 0

  res, err := lib.ApiClient.FindActor(ctx, &neurelo_sdk.FindActorParams{
    Take: &take,
    Skip: &skip,
  })
  if err != nil {
    panic(err)
  }

  parsedRes, err := neurelo_sdk.ParseFindActorResponse(res)
  if err != nil {
    panic(err)
  }

  fmt.Println(string(parsedRes.Body))
}

func main() {
  lib.SetupApiClient()
  Execute()
}
```

* Execute the main file to see the output

```go
go run main.go
```

## Setup Environment Variables (Optional)

* Install the `godotenv` package

```go
go get github.com/joho/godotenv
```

* Create a `.env` file in the root of your project

```bash
touch .env &&\
echo "NEURELO_API_ENDPOINT=<api-endpoint>" >> .env &&\
echo "NEURELO_API_KEY=<api-key>" >> .env
```

* Load the environment variables in the `main.go` file

```go
// main.go
package main

import (
  // other imports ...
  godotenv "github.com/joho/godotenv"
)

func main() {
  godotenv.Load(".env")
  lib.SetupApiClient()
  Execute()
}
```

## Examples

To review an example of an application built using Neurelo's SDK, please visit: [Project Examples](/project-examples#projects-built-using-neurelo-sdks)&#x20;

* These examples are built to act as a starter template for your project
* You can use these examples to understand how to use the SDK in your project


# Python SDK

## Overview

The generated Neurelo Python SDK provides easy access to your Neurelo APIs for Python applications.

{% hint style="info" %}
Refer to this guide [Python SDK Tutorial -- News Application](/sdks/python-sdk/python-sdk-tutorial-news-application) for a detailed tutorial on downloading, installing, and using the Python SDKs with FastAPI.
{% endhint %}

## Installation

Download the Custom Python SDK for your Project from the APIs page under the Neurelo environment that you want to interact with.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FnJdpdlyBeChk2kq2Au9B%2FDownload_Python_SDK.png?alt=media" alt=""><figcaption></figcaption></figure>

A gzip compressed tar archive (`.tgz`) SDK file should be downloaded. First, **uncompress** this file to get the underlying folder. Doing so, you are likely to see a directory as follows:

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FYFaTd5fZsMWdlZJApqJi%2Fimage.png?alt=media&amp;token=56fcefe4-67f6-45c7-b05c-ebe4f31db42f" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
The downloaded SDK file will be named - `neurelo-sdk-python-cmt_xxxxxx.tgz` (where `xxxxxx` are the last 6 digits of the definition commit applied to the environment)
{% endhint %}

To install the necessary dependencies for this SDK, we will use the `requirements.txt` as follows:

```bash
$ python3 -m pip install -r ./requirements.txt
```

{% hint style="warning" %}
If you have used Neurelo SDK’s in the past, to ensure that the **older version** of `neurelo` package is **uninstalled**, do a `python3 -m pip uninstall neurelo` and rerun your `requirements.txt` command from above.
{% endhint %}

## Usage

### API Usage

Basic usage requires instantiating both a `Configuration` and an `ApiClient` class:

```python
from neurelo.configuration import Configuration
from neurelo.api_client import ApiClient

configuration = Configuration(
	host=NEURELO_API_HOST,
	api_key={'ApiKey': NEURELO_API_KEY}
)

api_client = ApiClient(configuration=configuration)
```

Each object defined in your Neurelo data definition has a class that can be instantiated by passing the `ApiClient` instance into the constructor of the object's class. For example, if your data definition contains a 'User' object, you can instantiate the User class by passing the `ApiClient` instance into its constructor as shown below:

```python
from neurelo.api.user_api import UserApi

user_api = UserApi(api_client)
```

To obtain the `NEURELO_API_HOST`, simply copy the host name mentioned in the Environments tab.

<figure><img src="https://3406482452-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvzFLT4zSSU6J1uzbt5OF%2Fuploads%2FGf1XkFATvxZYUQ1qQWM5%2Fimage.png?alt=media&amp;token=3c7f618a-b5a3-41b6-9f88-57825b1c8776" alt=""><figcaption></figcaption></figure>

Additionally, you can generate a `NEURELO_API_KEY` by [creating a new API Key](/environments/api-keys) from the **“API Keys”** tab. You can export these values using a command similar to the following in our terminal:

```bash
$ export NEURELO_API_KEY="<YOUR-API-KEY>"
$ export NEURELO_API_HOST="<HOST-NAME>"
```

When calling operations with body, the body is encapsulated within specific classes. To use it, create an instance of the respective class and use the parameter values, as shown below:

```python
from neurelo import models

payload = models.UserCreateInput(
  email=email,
  fullname=fullname,
  password=password,
)

user = user_api.create_one_user(payload)
```

Similarly, when calling **operations with parameters** (for example, fetching all user info containing a email as `XYZ`), the parameters are also encapsulated within specific classes. To use these parameters, we create an instance of the respective class and use it as the parameter value, as shown below.

```python
filtered = models.UserWhereInput.from_dict({"email": {"equals": template_email}})
users = user_api.find_user(filter=filtered)
```

**It is important to use our** **`models`** **submodule** **to create these parameters**. The resulting parameter expression, like `{"email": {"equals": template_email}}`, is standard with our **REST API**. More information on this can be found in our [Neurelo API Reference (REST) guide](https://docs.neurelo.com/neurelo-api-reference-rest).

{% hint style="warning" %}
Although you can directly make API calls with parameters using the object API class as follows: `user_api.find_user(filter=<filter-condition>)`, we do not recommend this approach. Instead, use the **models** submodule to create the parameters.
{% endhint %}

Type hints are available for all parameters, for all operations to aid in understanding which class is should be used with each parameter.

## Example Applications

The following applications are provided to demonstrate how to use Neurelo, and Neurelo’s generated Python SDK.

* [Python SDK Tutorial (News Application)](/sdks/python-sdk/python-sdk-tutorial-news-application)
* [Python FastAPI + Jinja FullStack App](https://github.com/neurelo-public/neurelo-sdk-examples/tree/main/python/fastapi-jinja)

To review more examples of applications built using Neurelo's SDK, please visit [Project Examples](/project-examples#projects-built-using-neurelo-sdks)&#x20;




---

[Next Page](https://docs.neurelo.com/llms-full.txt/1)

