Convert a REST API to GraphQL and Deploy it in One Command

Convert a REST API to GraphQL and Deploy it in One Command

·

5 min read

Originally written by Lucia Cerchie and published by StepZen


StepZen's latest CLI command, stepzen import curl, lets you transform a REST endpoint into a deployed GraphQL API in minutes with a one-line command.

You start by specifying the REST endpoint. The CLI command stepzen import curl accepts curl command syntax and StepZen transforms the JSON response automatically into a GraphQL schema. You can deploy your new GraphQL endpoint right away with stepzen start. It’s quick, and as you’ll see, you can then customize your schema with a close level of control.

Convert REST to GraphQL With StepZen

Let’s learn how to use it, using our sample REST API as an example. Let’s say you’re an e-commerce developer working with a REST API that returns information about your customers. You’d like to build a GraphQL layer to make the communication between backend sources, as well as the communication between backend and frontend, easier.

The first thing to do is to sign up for StepZen so you can install the CLI:

npm install -g stepzen

Then, you’ll login:

stepzen login -a YOUR_ACCOUNT

and finish up by entering your login key.

Next, create a new folder and run this command inside it:

stepzen import curl "https://introspection.apis.stepzen.com/customers"
```![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lwcxb8g5mqm856jh1ewu.png)


This REST API returns data on customers, including their email, name, and id.

Next up, you’ll choose your GraphQL endpoint name and import the schema:

```bash
? What would you like your endpoint to be called? api/interesting-manta
Created /Users/luciacerchie/blog-post/stepzen.config.json
Starting... done
Successfully imported 1 schemas from StepZen

The last command, to upload and deploy your schema to StepZen, is stepzen start.

Deploying api/interesting-manta to StepZen... done in 5.8s 🚀

Your API url is  https://username.stepzen.net/api/interesting-manta/__graphql

You can test your hosted API with cURL:

curl https://username.stepzen.net/api/interesting-manta/__graphql \
   --header "Authorization: Apikey $(stepzen whoami --apikey)" \
   --header "Content-Type: application/json" \
   --data '{"query": "your graphql query"}'

or explore it with GraphiQL at  http://localhost:5001/api/interesting-manta

Watching ~/blog-post for GraphQL changes...

As the output says, the endpoint is running and deployed at https://username.stepzen.net/api/interesting-manta/__graphql. You don’t have to re-deploy, since StepZen watches your schema for changes, it automatically re-deploys on save. There’s a separate URL, localhost:5001/api/interesting-manta, that enables you to ping that endpoint from a GraphiQL Explorer:

screenshot of graphiql

As you can see, you can play with the queries and create new ones in the GraphiQL interface. Now, say you wanted to connect another REST API— if your e-commerce client was running a promotion in conjunction with DEV.to, say, and wanted to give every customer with a DEV.to account matching their name a sticker. That means you’d want to connect to the DEV.to API,

Connect a Second API: the DEV.to Schema

Make sure you’re in the same directory, and run

stepzen import curl https://dev.to/api/articles --query-name DevtoQuery --query-type Devto
Starting... done
Successfully imported 1 schemas from StepZe

Now, if you begin coding in your editor of choice, you’ll see a folder structure similar to this:

.
├── curl/
│   └── index.graphql
├── curl-01/
│   └── index.graphql
├── graphql.config.json
├── index.graphql
└── stepzen.config.json

Now, run stepzen start. Now you can run two queries side-by-side:

**query MyQuery {
  myQuery {
    email
  }
  DevtoQuery {
    cover_image
  }
}**

and receive your JSON data back from your APIs:

{
  "data": {
    "myQuery": [
      {
        "email": "lucas.bill@example.com"
      },
      {
        "email": "mandy.jones@example.com"
      },
...ETC
    ],
    "DevtoQuery": [
      {
        "cover_image": "https://res.cloudinary.com/practicaldev/image/fetch/s--_pD4K_cY--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zwgscljjob349l7zr76a.jpg"

Combine the Data From Two REST APIs Into One GraphQL Response

But what if you wanted to run a single query and get data back from both APIs?

This is where StepZen’s custom directive @materializer comes in. @materializer’s basic syntax looks like this:

@materializer (query: "DevtoGetUser" arguments: [{ name: "url" field: "name"}])

It specifies a query, in this case, DevtoGetUser,

DevtoGetUser(url: String!): [DevtoRoot_Entry] @rest(endpoint: "https://dev.to/api/users/by_username?url=$url")

It also specifies arguments. The url is the parameter that needs to be filled in the query, while the name refers to the name of the field that @materializer modifies in the type:

type OrdersEntry {
  carrier: String
  createdAt: Date
  customerId: Int
  id: Int
  shippingCost: Int
  trackingId: String
}
type RootEntry {
  address: Address
  email: String
  id: Int
  name: String
  orders: [OrdersEntry]
  devto_info: [DevtoRoot_Entry]
      @materializer (query: "DevtoGetUser" arguments: [{ name: "url" field: "name"}])

This way, when you make queries like:

query MyQuery {
  myQuery {
    devto_info {
      canonical_url
      title
    }
  }
}

The URL is auto-populated with the name of any customers in your database that have DEV.to accounts, and their data will be returned back to you. Now you can find every customer that has a DEV.to account matching their name! Now that you have that information, you can help your client send them stickers. (Speaking of stickers, if you’d like some StepZen ones, send a query with us).

Wrap Up

You’ve learned how to quickly import an API with a single command. You’ve discovered how to integrate multiple REST APIs as backends in a unified GraphQL API. You can also connect the data from two REST APIs in a single response. In the coming weeks you can do even more with stepzen import curl, including POST requests in the GraphQL layer that you’ve built with StepZen.

You've seen how stepzen import curl smooths out the process of creating a GraphQL schema. Manually, you'd design your schema by ‘reverse-engineering' an API’s JSON response. With stepzen import curl, this process is reduced to the single step of pointing your command to the REST API endpoint URL. The resultant schema is ready to deploy using stepzen start and customize as needed.

Beyond REST with stepzen import curl, StepZen provides CLI commands that let you easily convert other backends into GraphQL: See the Getting Started page to get started quickly converting a MySQL, PostgreSQL and other backends to GraphQL - see the connecting backends in the docs. There’s much more you can do to customize yoru GraphQL with StepZen, including adding pagination and handling mutations.

If you have any questions or would like to share your projects, we’d love to hear what you’re building and answer any questions over on the Discord Community!