How to Build APIs with GraphJin in Just Minutes

May 20, 2023 | Programming

Creating APIs can often feel like an uphill battle, taking weeks or even months. However, with GraphJin, you can build your backend APIs in minutes, not weeks. Let’s dive into how you can leverage GraphJin to create APIs effortlessly.

What is GraphJin?

GraphJin is a new kind of Object-Relational Mapping (ORM) that allows you to define your API using simple GraphQL queries. It automatically converts these queries into SQL, allowing you to fetch the data you need instantly. Ideal for use with NodeJS and Go, GraphJin supports various databases, including Postgres, MySQL, AWS Aurora RDS, and Google Cloud SQL.

How to Install GraphJin

Installing GraphJin is a breeze! Follow the procedure below:

  • For Mac (Homebrew): Run brew install doscographjin
  • For Ubuntu (Snap): Execute sudo snap install --classic graphjin
  • For Debian and Redhat: Download the .deb or .rpm from the releases page and install it with dpkg -i or rpm -i respectively.

Creating Your First API with GraphJin

To illustrate the power of GraphJin, let’s consider the example of fetching products and their details:

graphql
query getProducts {
  products(
    limit: 20,
    order_by: { price: desc },
    where: { price: { and: { greater_or_equals: 20, lt: 50 }}}
  ) {
    id
    name
    price
    owner {
      full_name
      picture: avatar
      email
      category_counts(limit: 3) {
        count
        category {
          name
        }
      }
    }
    category(limit: 3) {
      id
      name
    }
  }
}

Understanding the Code: An Analogy

Imagine you are in a restaurant. You (the GraphQL query) order different dishes (the data) from the menu (your database schema). The restaurant management (GraphJin) takes your order and prepares your meals (converts the query to SQL), serving it on your table (fetching data). Just like how part of your meal requires more time or specific ingredients, GraphJin manages complex relationships and constraints for data retrieval while ensuring everything is well-organized and prompt.

Using GraphJin with NodeJS

To utilize GraphJin in a NodeJS application, you’ll need to install it via npm:

npm install graphjin

Here’s an example code snippet for defining a server:

javascript
import graphjin from 'graphjin';
import express from 'express';
import http from 'http';
import pg from 'pg';

const Client = pg;
const db = new Client({
  host: 'localhost',
  port: 5432,
  user: 'postgres',
  password: 'postgres',
  database: 'appdb-development',
});

await db.connect();
const config = { production: true, default_limit: 50 };
var gj = await graphjin('./dev.yml', db);
var app = express();
var server = http.createServer(app);
app.get('/user', async function(req, resp) {
  const res2 = await gj.query(`
    query getUser {
      users(id: $id) {
        id
        email
      }
    }`, { id: 1 });
  resp.send(res2.data());
});
server.listen(3000);
console.log('Express server started on port %s', server.address().port);

Using GraphJin with Go

In Go, install GraphJin and access it as a library. Here’s an example setup:

golang
import (
  "context"
  "database/sql"
  "log"
  "net/http"
  "github.com/doscographjin/core"
)

func main() {
  db, err := sql.Open("pgx", "postgres://postgres:@localhost:5432/exampledb?sslmode=disable")
  if err != nil {
    log.Fatal(err)
  }
  gj, err := core.NewGraphJin(nil, db)
  if err != nil {
    log.Fatal(err)
  }
  query := `query getPosts { posts { id title } }`
  router := chi.NewRouter()
  router.Get("/", func(w http.ResponseWriter, request *http.Request) {
    context := context.WithValue(request.Context(), core.UserIDKey, 1)
    res, err := gj.GraphQL(context, query, nil, nil)
    if err != nil {
      log.Fatal(err)
      return
    }
    w.Write(res.Data)
  })
  log.Println("Go server started on port 3000")
  http.ListenAndServe(":3000", router)
}

Troubleshooting Tips

If you encounter issues while using GraphJin, consider the following troubleshooting steps:

  • Check your database configuration: Ensure all environment variables are correctly set.
  • Ensure the correct permissions: Make sure your database user has the necessary read/write permissions.
  • Verify the GraphQL query syntax: Syntax errors can lead to unexpected results.
  • Consult the documentation for detailed troubleshooting topics.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Conclusion

GraphJin dramatically simplifies API development by transforming your GraphQL queries into efficient SQL, allowing you to focus on your application rather than on the underlying code. Whether using NodeJS or Go, GraphJin offers a quick and effective way to build and deploy APIs faster than ever before.

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Final Thoughts

As you dive deeper into GraphJin, you’ll discover a multitude of features designed to enhance your productivity—from user management to real-time updates. Happy coding!

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox