Bring RESTful Data Into Your GraphQL Responses Using Dgraph Lambda - Dgraph Blog

If you have a RESTful API that performs some business logic or 3rd party info that isn’t within your data, you’ve likely thought about how to use this data within your GraphQL API. Most of the time, a RESTful service may be used by sources outside of just your application, so moving it over to GraphQL may not make sense. Conversely, you may not even own the RESTful service but still want to expose that data through your GraphQL API for your users.

Luckily, with Dgraph Lambda we can do exactly that. We simply need to add the field to our schema, annotate it with the @lambda directive, and then build out the logic that calls the RESTful API from within Dgraph Lambda. In just a few steps, you’ll be retrieving RESTful data while exposing it through your GraphQL API. If you want to follow along, simply create a free Dgraph cloud account, launch a backend, and follow the steps below. Let’s take a deeper look!

You can check out the accompanying video for this article from our YouTube channel below:

Populating a field with data from a RESTful endpoint

The service we will build is quite simple. It will consist of a City data type containing id, name, state, and country fields which will retrieve data from the database. There will also be a fifth field named current_weather. This field will contain a string with the description of the current weather. This data will be retrieved from the OpenWeather RESTful API using data in the other GraphQL fields within the City type.

Step 1: Define The Schema

With this in mind, let’s create our GraphQL schema to power this API. In Dgraph Cloud, navigate to the Schema screen and add the following schema:

type City {
  id: ID!
  name: String!
  state: String!
  country: String!
  current_weather: String! @lambda
}

Once populated, click Deploy to deploy the schema to the backend.

You’ll notice that we have annotated the current_weather field with the @lambda GraphQL directive. This tells Dgraph that this field will be derived from some custom logic within Dgraph Lambda.

Step 2: Create The Lambda Function

Once we have added the schema, we can now define our Lambda as well. To do this in Dgraph Cloud, navigate to the Lambda screen through the left-side menu. Once on the screen, implement the following Lambda function in the provided text area:

self.addGraphQLResolvers({
  "City.current_weather": getCurrentWeather,
});
async function getWeather(name, state, country) {
  let url = `https://api.openweathermap.org/data/2.5/weather?q=${name},${state},${country}&appid=944f9bf37b47e039c6466b185de46269`;
  let response = await fetch(url);
  let data = await response.json();
  return data.weather[0].description;
}
async function getCurrentWeather({ parent }) {
  const { name, state, country } = parent;
  var weather = getWeather(name, state, country);
  return weather;
}

Let’s break down each function for understanding.

  • self.addGraphQLResolvers will tell Dgraph that City.current_weather should be resolved by the getCurrentWeather function we have defined below.

  • The getWeather function will take a name, state, and country, call the OpenWeather API with these parameters and return a JSON object with some weather information. Out of this information, we will only return the description of the weather.

  • The getCurrentWeather function is the one that actually “resolves” the data for the current_weather field. It extracts the name, state, and country from the parent object and calls the above getWeather function that actually retrieves the data.

You could combine the getCurrentWeather and getWeather functions but I’ve chosen to keep them as separate routines: one as a simple resolver function and the other containing the RESTful API call.

Step 3: Add Some Data

With our schema and Lambda ready, let’s add some data! For that, we will run a mutation that will add Toledo, Ohio to our database. Navigate to the GraphQL screen via the left-side menu and populate the Query text area with the following:

mutation MyMutation {
  addCity(input: {name: "Toledo", state: "OH", country: "US"}) {
    numUids
  }
}

This will add a single entry to our database. Feel free to add more (but there are no guarantees that the OpenWeather API will have the data need and you may end up with an error!).

Step 4: Query The Data With a Dynamic Field

Lastly, let’s query Toledo, Ohio through our GraphQL API and get the dynamic current_weather field in our GraphQL response. On the GraphQL screen where we ran the mutation, add in a query that looks like this:

query MyQuery {
  getCity(id: "0x2de670e66") {
    name
    state
    country
    current_weather
  }
}

Press the Play button to execute the query. You should get back a response that includes a brief weather description in the current_weather field. At this point, our Dgraph Lambda has been invoked, retrieved the data from the RESTful API, and mapped it back into the GraphQL response.

Conclusion

As you can see, using RESTful APIs to retrieve dynamic data in Dgraph is extremely simple to get started with. Hopefully, this brief overview gives you the confidence to build more complex Lambda functions in Dgraph as you build your next application! Get started on Dgraph Cloud today to start building quickly and easily with GraphQL. Feel free to share your work with our community or ask any questions you might have on Discuss!

Matt Tanner, Author

Matt is a Developer Relations Lead at Dgraph passionate about all things related to data, development, and architecture. Previously, Matt has worked as a developer, tech lead, and architect for some of the largest financial institutions and insurers in Canada. Most recently, he has focused on working with global startups to help with Developer Relations. He is always dabbling in the latest tech and applying this to his own ventures in technology


This is a companion discussion topic for the original entry at https://dgraph.io/blog/post/restful-data-using-lambda/
1 Like