DEV Community

Cover image for Graph query your data in REST API without GraphQL
Ahmed Abdalla Elbilal
Ahmed Abdalla Elbilal

Posted on • Updated on

Graph query your data in REST API without GraphQL

API-Graph

Specify exactly what you want from the API.

Why

why to use GraphQL

Use graph queries in your rest API without the need for graphQl and without editing any parts of your logic in the endpoints code, it just works, but adding one middleware in your app.

Installation

npm install api-graph
Enter fullscreen mode Exit fullscreen mode

Usage

To use this package, you will need to import it and use it as middleware in your express application. Here is an example of how to use it:

import apiGraph from "api-graph";
import express from "express";

const user = {
  id: 1,
  name: "ahmed",
  age: 23,
  photos: [
    { id: 1, path: "img1" },
    { id: 2, path: "img2" },
  ],
};

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(apiGraph({ extract: "graph" }));
app.get("/", (req, res) => res.json(user));
app.listen(3000, () => console.log("server running at 3000"));
Enter fullscreen mode Exit fullscreen mode

Then you pass what fields you want to return in body fields when you request the endpoint

body : { graph : "{id, name}" }
Enter fullscreen mode Exit fullscreen mode

and that's it, only the name and id will be returned from the endpoint

Postman

An image that showing sending a request from postman

an image that showing sending a request from postman

How it works
The imported middleware apiGraph which is the main function that must add to the app, it takes one parameter the extract which is the key that the server will look at when trying to get the query send from the client, and the default value for it is graphQuery. The server then gets the values from the key to parse it and extract data from the object that was passed to res.json function, in case no query was sent from the client then the whole data will be returned.

Errors

  • property not found in case you were trying to ask for fields in the data that are not exits.
  • Parsing error in case you send an invalid query.

Links

Feel free to take look at api-graph sites in GitHub and in NPM

Top comments (0)