Hands-On With SwiftUI, GraphQL, & Neo4j AuraDB

Rate this content
Bookmark
Github

Bring the power of graphs to iOS mobile app development in this hands-on workshop. We will explore how to use the Neo4j GraphQL Library to build GraphQL APIs backed by Neo4j AuraDB and how to integrate GraphQL into an iOS app using SwiftUI and the Apollo iOS GraphQL library as we build a news reader mobile app.


Table of contents:

- Intro to Neo4j AuraDB

- Building GraphQL APIs with the Neo4j GraphQL Library

- Intro to SwiftUI

- SwiftUI + GraphQL


Prerequisites

To follow along during the workshop attendees will need a Mac laptop with a recent version of Xcode installed. Some familiarity with Swift and iOS app development will be helpful, although not required.

156 min
07 Dec, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Today's Workshop focused on building native iOS applications using SwiftUI and GraphQL, with a database powered by Neo4j. The Neo4j GraphQL library reduces boilerplate code and offers performance advantages. SwiftUI allows for building declarative UIs and includes a preview functionality. Cypher and GraphQL are both used to query and interact with graph data, with Cypher being more focused on graph databases and GraphQL being more versatile. The workshop also covered topics like building a GraphQL API, configuring the Neo4j GraphQL library, and using Apollo iOS for GraphQL data fetching in iOS apps.

Available in Español

1. Introduction to Neo4j, GraphQL, and SwiftUI

Short description:

I work for Neo4j, an open source database company. Today, we'll focus on GraphQL and building native iOS applications using SwiftUI. We'll use Neo4j GraphQL library and Apollo iOS library. Xcode on a Mac is the only local development environment required.

So, a little bit about me. I work for an open source database company called Neo4j. Neo4j is a graph database, we'll talk about what that means in a minute. I work on the developer relations team. So largely my job is helping developers build applications with Neo4j and other technologies. It's really important to understand how database fits in with different technologies, different pieces of your architecture. So that's a big piece of my job is I think sort of contextualizing the database piece for different technology communities. So GraphQL is one of those, which is the focus of our workshop today. I also wrote a book recently published by Manning's called full stack graphical applications. This book is available for free or the ebook version is available for free, sponsored by Neo4j so I'll drop a link to that. Now we'll take you to a form if you're interested in downloading the book. The book focuses on using graph QL in a full stack architecture with react for the front end. So today we're going to look at native iOS with Swift UI as sort of the client front end for our application. If you're interested in similar architecture but using react and we look at different cloud services like how do I deploy to Netlify? How do I use op zero? So here's a rough outline for what we're going to do today. So we will have I guess roughly four sections here. One is we're going to look at near for jay and aura DB, which is near for J is hosted cloud service. If you're in the workshop on Tuesday, we use aura as well. So we're going to use the free tier for aura which is nice because we can spin up a database that's private to us that we don't have to put in a credit card or incur any costs. So that's really good for hobby projects. We have something like that where we don't want the database to go away, but we just have sort of lower use of it. That's what we're going to do for the database layer. Then we're going to talk about building graphical APIs. So building graphical servers, and specifically, we're going to use a GraphQL database integration called the Neo4j GraphQL library that's going to help us provision our GraphQL API without writing a lot of boilerplate code, generating database queries, that sort of thing. Then we're going to take a look at SwiftUI. So building native iOS applications using Swift. And we'll see how to integrate GraphQL and SwiftUI. So we're going to use the Apollo iOS library for SwiftUI, which allows, or for Swift, rather, not specific to SwiftUI. SwiftUI is the user interface component that is available with Swift. There's a few different ways of building UIs for iOS. SwiftUI is similar, conceptually similar, I think, to a lot of web frameworks like React. So if you're familiar with things like React, there's some concepts that transfer nicely in SwiftUI. And then the only local development environments that you need to have set up is Xcode on a Mac. If you don't have that setup, that's fine. You can sort of just watch as we go through the exercise at the end. The SwiftUI part is the last piece we're going to do. For the other pieces for using Neo4j, we're going to use the AURA cloud service and nothing to download or install for that. And then for building the GraphQL API piece, we're going to use CodeSandbox, which is a sort of hosted development environment, so we don't need to set up anything locally for that. But then there is a GitHub repository for the Xcode SwiftUI piece of the project that has just sort of a getting started component.

2. Newsreader App with Neo4j, GraphQL, and SwiftUI

Short description:

Here's what we're going to build today: a newsreader iOS application using Neo4j as our database and GraphQL as the layer between our client iOS app and the database. Neo4j is a graph database, which means the data model is a graph composed of nodes and relationships. We'll use the Cypher query language to work with the data. GraphQL is an API query language with a strict type system, and we'll use it to build our GraphQL API. The Neo4j GraphQL library is a JavaScript library focused on building node.js GraphQL APIs backed by Neo4j. It reduces boilerplate code and offers performance advantages. And finally, we'll be using SwiftUI for building the iOS app.

Cool! Here's some links to various resources that will be helpful as we're going through things today. The slides, of course, and a link to the GitHub repository for the Xcode project, documentation for the Neo4j GraphQL library, as well as an overview page for that. We'll talk a lot more about what that is.

And then the Apollo GraphQL iOS tutorial is a helpful resource that shows how you can install and set up the Apollo GraphQL iOS package in an Xcode project. And then the developer docs for SwiftUI is a good resource as well.

So here's what we're going to build today. It's pretty fairly simple app. So we're not going to focus too much on a lot of the nitty gritty pieces of SwiftUI to make everything look super nice. Really I think the focus of what we want to do today is talk more about how the pieces fit together in this sort of architecture.

What we're going to build is a newsreader iOS application. So we're going to fetch news articles and show them to the user and then think a bit about how we can add personalization features to our iOS app. How can we show news that's relevant for users either by factoring location or finding similar articles that a user might be interested in. And we're going to do this using Neo4j as our database. So we're going to be modeling and working with this data as a graph. So when we're talking about a graph, we're talking about a data structure that's composed of nodes. These are the entities and relationships that connect nodes. And we're going to do this with GraphQL.

So GraphQL is going to be the layer that sits between our client iOS app and our database. We're going to build a GraphQL API. One thing that you'll notice, when we're talking about using a graph data model in the database, that's very close to the same graph model that we use in GraphQL. We'll talk a bit more about that.

Cool. So let's take a look at what exactly is Neo4j. So I said earlier that Neo4j is a graph database. That means unlike relational databases that use tables or document databases that use a document like a JSON document, the data model in graph databases like Neo4j is a graph. So nodes are the entities, relationships connect nodes. We use a query language called cypher, which is kind of like SQL but for graphs is a good way to think of it. There's an example, cypher example here in the upper right. Can see we're sort of on the first line drawing this ASCII art representation of the graph pattern that we are looking for in this data set.

The first part here, match, which is go find some pattern that exists in the database. These open and closed parentheses are drawing sort of a node circle around an address. We're saying find where this pattern exists. We want address nodes that have a registered address relationship. A promise node here, we're putting square brackets with the arrow. That's connecting to nodes, in this case, connecting an address node to an officer node. And then we're traversing out from that officer node to find entity nodes. So this query says find addresses in New York, find the officers who are connected to those addresses, and then find the entities connected to those officers with an address in New York. And this is a question from the Panama Papers dataset, which was a investigative journalism project a few years ago, that was using Neo4j to make sense of offshore corporate records to try to find interesting things around mostly folks hiding assets in offshore companies, which is a fun data set to look at. That's a public data set. On the Neo4j sandbox, cool.

So let's talk through the different technologies we're going to use today. So we're at least on the same page about at least what they are, some of the benefits, and so on. So we talked about Neo4j. GraphQL is the next piece. I think a lot of folks here at the conference this week have learned a lot about GraphQL if you weren't familiar with GraphQL already. But basically, GraphQL is an API query language and a way of building API applications, so API servers. With GraphQL, we have a very strict type system, so we describe the data that's available in the API. We have types, types have fields, and we know the data type of each of those fields.

So the example here is, we have a project type, we have fields like name, tagline and contributors. Name and tagline are strings, contributors is what's called an object field. Specifically, this is an object array field. So this project has one or more users connected to it. And this is where the Graph piece of GraphQL comes in. So types can refer to other types. We think of this as a relationship field that connects the project and one or more users. So that's the Graph piece of GraphQL. Then at query time, the client requests basically a traversal through this data graph in the form of what's called a selection set. So here we're searching just for a project and bringing back the tagline, but we could traverse to the contributors as well and bring back information about the contributors. This is nice for the client because the data that comes back exactly matches the selection set of the query or the mutation operation. So we have very predictable data that we are working with when we use GraphQL.

To make building GraphQL APIs easier when working with databases, there's really a whole crop, I guess, of database GraphQL integrations out there, and we see this in the SQL world. We see this in the graph database world as well. And so one of those is the Neo4j GraphQL library. So this is a JavaScript library focused on building node.js GraphQL APIs backed by Neo4j. And so the idea here is that we can use GraphQL type definitions to define the data model for the API, the GraphQL API, but also to drive our database. And this is really nice because this reduces a lot of the boilerplate data-fetching code that we end up writing when we're building GraphQL servers. It also has a lot of performance advantages because we're able to generate a single database query for any arbitrary GraphQL request. But then we also have some really neat features as well for things like adding custom logic using the Cypher query language that we talked about a minute ago, features for adding authorization rules in our GraphQL schema. So really powerful library for building GraphQL APIs. And then SwiftUI.

3. Introduction to SwiftUI

Short description:

SwiftUI is a UI framework specifically for iOS, Mac OS, and Apple TV. It allows for building declarative UIs and includes a preview functionality for real-time updates. Swift, the language, is open-source and can be run on Linux and server applications. B is familiar with native iOS apps.

Does anyone use SwiftUI before? I'm curious if we have any folks that are familiar with building native iOS apps. So if you're not familiar with SwiftUI, there's kind of two pieces here. One is the Swift programming language. So this was originally created by Apple. This is sort of the successor to Objective-C. Objective-C was a language used mostly by Apple for building iOS, Mac, and tvOS apps. Swift was open-sourced in, I think, was it 2012 or maybe 2014? And then SwiftUI is a UI framework, specifically Apple's UI framework. So Swift itself is open-sourced. It's not specific to Apple. You can run Swift, the language, on Linux as well and also on server applications, Linux-based server applications. But SwiftUI is specific to iOS, Mac OS and Apple TV, which includes sort of a UI framework for building declarative UIs. So one of the neat features in swift UI is the preview functionality. So you can see that here in the screenshot from Xcode. So previously, we had to build and preview the app running to sort of see any changes Swift UI, we can sort of see changes in real time to our UI as we're making updates. Yeah, we'll talk a bit more about Swift UI. So B says, they're familiar with native iOS apps. Great, got some some level of experience there. That's good.

4. Working with Graphs in Cypher and GraphQL

Short description:

Let's talk about working with graphs in Cypher and GraphQL. A graph is a data structure composed of nodes and relationships. We use the property graph data model, which includes labels and key-value pair properties. Knowledge graphs provide context and a canonical representation of entities. The dataset we'll use comes from the New York Times API. We'll interact with the data as a graph in the database and in GraphQL. The GraphQL API is read-only and offers introspection functionality. We can construct complex queries and explore the available data. The articles query field is the entry point for our GraphQL API. We can filter, sort, and limit the results based on specific criteria.

Cool. Let's talk a little bit about working with graphs in Cypher, working with graphs in GraphQL, because I think there's kind of some similarities there. Right, we're talking about graphs in the database. We're talking about graphs in the API layer. Like, let's sort of see how we can compare and contrast working with graphs in those two different pieces of our application architecture.

So, first of all, at a high level, what is a graph? Well, a graph is a data structure composed of nodes, those are the entities and relationships that connect nodes. To be able to work with data in a graph, we use a data model called the property graph data model. And so what this means is that we introduce labels, so labels describe the type of the node, it's a way to sort of group nodes. So in that example earlier, we saw things like the address node, the officer node, those were labels that described what sort of type of node it is. And then we have arbitrary key value pair properties that we can store on nodes or relationships. And these are the attributes, these are the values that we're working with. Similar to labels, relationships have a single property type and a direction. So that's the basic data model that we use.

Another term that you might hear frequently is the term knowledge graph. And knowledge graph, I guess I like to think of knowledge graphs as an instance of a property graph. So we have some real world data that we're modeling in a property graph. And the value of a knowledge graph is that they put things in context. And when I say things, I guess what I'm referring to is like a canonical representation of something, of a value, of an entity. So this example on the screen, this comes from our news data set that we're going to be working with today, which comes from the New York Times. And so for every news article, we have the topic or we have multiple topics. We have the people mentioned in the news article, there are geographic regions that may be relevant for the article. And we can see how these articles, topics, and people are connected in this news knowledge graph. So here, for example, we have a canonical representation of the topic, US politics and government. So when we have a new article that is about that topic, we connect it to the topic node and we can see similar articles by traversing the graph here. So we can traverse from one article node to others through the same topic. And this applies also for our geo regions, if we wanna see all of the news about a particular geographic region, if we wanna see all the news about a certain person and so on. The term knowledge graph was, I think, really introduced formally when Google released the Google knowledge graph. And they talked about this idea of Things, Not Strings, where we have some context, we have some canonical representation of these entities, which is I think, a good way to think about knowledge graphs.

So the dataset we're gonna use today comes from the New York Times API. So we I've set up, let's see on this repo, I've set up a sort of cron job using GitHub actions to fetch this data from the New York Times API. So once a day we fetch the most popular articles, I guess there's three kinds, the most popular viewed, the most popular emailed and the most popular articles shared on social media. And once a day we fetch that and load that into a Neo4j Aura database using this GitHub action. And I've been running this for, I don't know, probably about a year or so. So we're gonna use a snapshot of this data to work with. I'll drop a link to that GitHub repository. Cool, so that's the data we're gonna work with. Let's talk a bit about how we can think of interacting with that data. So how do we work with data as a graph in the database? And also how do we work with data as a graph in GraphQL?

So, first of all, this is the GraphQL API or very similar to the GraphQL API we're gonna build today. And this is running without any authentication so anyone can open that and query this dataset and zoom in a little bit. So if we look at the Docs tab, you can see here we have queries, we don't have any mutations. So this is just a read only API. We can see the data we're working with here. This is GraphQL playgrounds, which if you've used GraphQL or if you've used Apollo Studios sandbox tool, similar functionality based on GraphQL's introspection functionality. So there's lots of really neat developer tooling for GraphQL. Most of it based on this idea of introspection, which is that we can query a running GraphQL API to say, Hey, what are the, what are the types that we're working with? We can use this to generate things like documentation that we're seeing here for the API. So we know all the data available. It's also available for things like, or say it also enables things like autocomplete in developer tools, which is quite neat. Cool. So there's a query here. I guess this was the last query I ran that this gives us a pretty good idea of what sort of data we have and how we can construct a GraphQL query. So feel free to open this up and take a look at the API documentation, try to write some GraphQL APIs to query this data. This one is a fairly complex query that I think shows a few features of the API that we're going to build. So first of all, we're starting with the articles query field. So this is our root entry point to our GraphQL APIs. So we're searching for articles and the query type is a special type in GraphQL. Any fields on the query type are the entry point, the root level of a GraphQL query. So we have to start from a field on the query type to start our traversal through this data graph. The other special types are mutation and subscription. Mutation for right operations typically. So create, update, delete, those sorts of things. We're not gonna look at mutations today. Subscriptions are GraphQL's specialization. Sorts of pub sub realtime functionality, which we're also not gonna look at today. We're gonna focus mostly on queries for our news app. But what we're doing here is we're starting at the article query field. We are passing in a couple of field arguments. So this where argument is a filter. So we're filtering for articles that are connected to the topic exercise and where the Geos are not null so where we have some geographic information about the article. And then we are sorting these by published date in descending order and bringing back the most recent 10. So this basically says find me the most recent 10 articles about exercise that have something to do with some geographic location.

5. Querying Articles and Working with Neo4j

Short description:

We want to build a GraphQL API to query articles, including title, URL, published date, and geographic regions. We can pass field arguments in the selection set, and for each article, we'll bring back the title and URL. We'll use GraphQL Playground to explore the API and run queries. There are optional arguments for filtering and pagination. We can also work with the data in Neo4j using Cypher queries. Neo4j browser provides a query workbench for interacting with Neo4j.

And then here's the fields we're bringing back. So we want the title, the URL, and the published date of the article. We want to know all the geographic regions the article is connected to and then for each of these geos, you can see the nesting in the selection set here. So this is basically anytime we have nesting in the selection set, which by the way, the selection set is this part of the GraphQL query where we're defining, first of all, a traversal through the data graph. So which nodes are we traversing to, but then also which fields are we returning? And those are the two main purposes of a selection set. And anytime we have this nesting in the selection set, so going from the geographic regions to, in this case, the articles that's traversing from one node to another. So anyway, so we're traversing from any of these geographic regions to find other articles in those geographic regions, but only three. So we can pass field arguments in our selection set as well, not just at the root. And for each article, we're bringing back the title. So here, first one we have is an article about the Ironman and the URL of that article. It is something to do with Hawaii, and then we can see some other articles about Hawaii and so on for an article about cycling in Brooklyn, and then some articles about Brooklyn and so on. Cool, so that gives an idea of the type of data we're working with and the type of GraphQL API that we want to build. So this is going to be our goal to build this sort of GraphQL API, get it deployed, and then we'll see how to build a native iOS app to query this API.

Anthony says, is there a trick to getting results when I hit the URL? So if you open that URL, you should see, yours will probably look something like this. It will be blank, right? So mine loaded with a query already. And so the first thing you can do with GraphQL Playground is click on this Docs tab. So this will give you the generated documentation for any GraphQL API. So this gives an idea of what sort of data you're working with and the entry points. And then every GraphQL query starts with an open and closed curly brace, and then we can do a Control Space to get this autocomplete to show, in this case, all of the fields on the query type, which are the entry points. So we can select articles, and then we're gonna have another open and closed curly brace because we know we need some selection set now in our query. And if I do a Control Space again, I can start to see the fields that are available. And this is kind of the simplest query we can run. This returns all of the articles, which is probably more data than we want to return, I don't know, however many, 10,000s or so articles that we have. So try, I'll drop this in the chat. Try that query, that's sort of the simplest form. From there, we can look at, again, in the docs for this articles field. We can see here that there are two optional arguments. So where and options. If I scroll down to the bottom here, I can get more information about the filtering. So where is the filtering options. And then options, those are going to be things like for pagination. So I don't want to return all articles. I can do things like options, limit 10, but then I probably want some sorting on that as well. So we'll say sort by publish descending. And you can see mostly I'm relying on auto-complete to tell me what fields are available. And then let's bring back the publish date as well. So this should be the most recent news, so just if our scraper ran getting news, getting articles from yesterday. So I guess we didn't pick up today's articles for some reason. And Anthony says he's getting a syntax error. Yeah, share the query you're using. We can try to debug that, if you're getting an error. It says he figured out, okay, cool, great. Cool, yeah, well, this API, this is up running. So this is a good one to play around with using some real world data. You can always use it to check the day's news as well, but let's see how we can work with the same data in Neo4j. So let's see, I think we can do newsscript. News.zone. Oh yeah, I noticed some DNS issues on this. I have a backup though. We can do news.graph.fyi. I think that's my backup. Yeah, there we go. So you can follow along if you like on this one. Here's the URL for this one. This is a Neo4j instance. And then the, I think I'm already signed into this, but the username and password is just news.graph, all lowercase like this, or the username and password. And this is a read-only user. So don't worry about making any changes or accidentally deleting data. I just have read-only permissions. So this is Neo4j browser, which is like a query workbench for interacting with Neo4j. The idea here is we can write GraphQL queries, and then we get back a visualization or perhaps a tabular result depending on the type of data that we are returning. So let's see how we would write a query similar to this one. So here's how we do this in GraphQL to find the 10 most recent articles. Let's see how we would do that in Cypher. So to start off with, we're gonna say match, and then, so matches is the keyword to find some pattern and match takes a graph pattern. And, starting off, if I don't know the data model I can do a call DB.schema.visualization. So call, this is a Cypher keyword that is going to execute some built-in function or a procedure. DB.schema.visualization is gonna give me a graph view of the data that I'm working with. There's some additional metadata here, you'll see here at the underscore Bloom perspective in Bloom scene. And this is just some data for a visualization tool.

6. Data Model and Article Information

Short description:

This is the data model we're working with. It includes information about people, topics, geographic regions, and organizations mentioned in the articles. The data comes directly from the New York Times API, so no additional natural language processing is required. The model also includes information about images and photos in the articles.

So we can ignore that, this is the piece that we're interested in. And if I do a colon style reset, and I should be able to see all my captions, there we go. So this is the data model we're working with. And this matches what we saw in the slide a few minutes ago when we were talking about how this data came from the New York times API, and we were modeling for every article, we have the people and the topic and the geographic region that the article mentions. We also have organization. So it's like people place in thing, basically. So do we have any like companies that are mentioned in the article that would be an organization? These are kind of the standard things you get when you run a natural language processing model on a piece of text. What's nice is this comes directly from the New York times API. So we didn't have to do any natural language processing to find those things. And then we also have information about any images, any photos that are in the article. So that's the basic data model.

7. Comparing Cypher and GraphQL

Short description:

We construct a query to find the 10 most recent articles, ordering them by the published date in descending order. We can include additional information, such as topics, using a more complex graph pattern. The database can be explored using visual tools like Bloom, which allows for interactive graph visualization without writing Cypher queries. Cypher is a graph database query language that uses declarative pattern-matching functionality. It includes database-specific functions and graph-specific operations. GraphQL, on the other hand, is a query language specifically for APIs and models application data as a graph. It can be used with any backend and allows for traversing the application data graph using nested selection sets. Both Cypher and GraphQL are used to query and interact with graph data, but Cypher is more focused on working with graph databases, while GraphQL is more versatile and can be used with any backend.

So now that we know that we can start to write our query. So we're interested in finding the 10 most recent articles. So I'm going to start constructing my query to look for article nodes. And let's start off. Let's return the article nodes. Let's look at the first 10. And so this a is a variable that gets bound to a piece of the pattern. So the thing after the colon is the node label. In this case, article, the thing before the colon is the variable to be bound to that piece of the graph that matches that piece of the pattern. And then we can refer to that variable later on in the query. So here we're saying find article nodes, return those article nodes, but only give me 10. And if I click on these, I can see the properties for the node. So here's an article about someone who illustrated children's books. We can see when it was published, the URL for it and so on. But this is kind of an old article we want the most recent. So let's add an order by 10. Order by a dot published in descending order. On each my order by goes first. And then the limit. Like that. Cool. And so this is the most recent news, which is yesterday's articles. Here's one about Victor Bud. So there's what, this is what the prisoner exchange in Russia. And it's helpful to have some context about these articles. So if I double click, then we start to traverse the graph. So here we can see the topics, the geo regions, the photos connected to the article, and so on. But I don't wanna sort of double click on things to add this information to my query. We can construct a more complex graph pattern to describe that traversal in the query. So we want to include the topics, then we add a relationship piece to our graph pattern. And so let's bring in the topics as well. And then when I return those in my return clause, I need to here I'm only seeing the article nodes because I'm only returning A. We could add T to that. Let's just add a asterisk to return everything that we have found on. Cool, so now I'm seeing the most recent articles and the topics they're connected to. I could then go out and do things like let's find other articles connected to those topics as well. And return those. We get the idea we can start to describe more complex pieces of our pattern. Cool and that that database again that's public. You can use that using the credentials in the chat there. To play around with this data set. It's a fun one it updates every day. We can also use visual tools to query this data as a graph. I want to show a demo of this one but Bloom is a graph visualization tool that allows us to explore or find insights with graph visualization interactively without having to write cipher. So this is a good tool if we want to expose the data to let's say like an analyst type who has some domain knowledge of the data. Maybe they're doing something like a fraud detection investigation or something like this. If you're a developer familiar cypher you can configure Bloom to include some saved cipher queries for more complex analysis. We can use graph algorithms with Bloom as well to do things like run page rank or community detection algorithms just by a few clicks visually. So that's a very compelling tool if you're not interested in writing cipher to explore the dataset. Okay, so we've seen some examples now of cypher and of GraphQL. I think it's helpful to kind of compare these two and make sure that we're using the right tool for the right job, depending on what we're trying to accomplish, depending on which piece of our architecture we're talking about, because conceptually, both cypher and GraphQL are working with graphs, right? Where we're sort of querying and interacting with graph data in each case. So let's maybe compare and contrast a little bit to see where we should use one and not the other. So, Cypher is a graph database query language. We said we use this declarative pattern-matching functionality where we draw this sort of ASCII art representation of graph patterns. And then the database figures out how to find where that data exists or how to work with that data. Cypher includes, and all of the database specific functions we would expect, so similar things that we would find in SQL, things like aggregation functions, math functions, database operations for things like creating indexes, even importing data from CSV. And then lots of graph specific operations, so things like a variable-length path operator where I'm trying to find like the shortest path between nodes, those types of things. If we look at GraphQL, we said GraphQL is a query language specifically for APIs, so GraphQL is not a query language for databases. We'll see sort of why that is in a minute. And then also GraphQL is this runtime for fulfilling API requests. We have a strict type system that we talked about a little bit ago that specifically defines the data that we're working with. And GraphQL is, it is modeling data as a graph. It's modeling your application data as a graph. So GraphQL can be used with any back end. We can build GraphQL APIs on top of multiple data layers and kind of combine them together. GraphQL can act as sort of a federation layer. And then at query time, we're describing a traversal through this application data graph that GraphQL is allowing us to model using this idea of the nested selection set that we saw earlier. So using our articles data set, let's see a few sort of use cases and see how we would use Cypher, how we would use GraphQL to find them. Well, this one we already did. Show me all of the articles.

8. Querying Articles in Cypher and GraphQL

Short description:

We saw how to query article nodes in GraphQL by defining a simple graph pattern and selecting the desired fields. While Cypher has built-in functionality for sorting, ordering, and pagination, GraphQL uses field arguments to achieve the same results. To handle cases where articles may not have topics, we use an optional match and add a nested layer to the selection set. We can add complexity to our graph patterns by traversing to other articles connected to the topics of the 10 most recent articles. In GraphQL, we add another nesting to the selection set to accomplish this.

We saw how to do that in Cypher by defining the simple graph pattern we're looking for which is drawing this ASCII art representation. We're interested in article nodes, returning them in GraphQL. We find the query field entry points, in this case, we have one for articles and then we select what fields we want to return. In this case, we're returning just title and abstract. We saw this one as well, give me the most recent articles. So Cypher has functionality built in for sorting, ordering, pagination, these sorts of things.

Now, GraphQL does not have ordering, sorting, pagination built into GraphQL, but we can use field arguments to model these sorts of things. And so there's some conventions out there for how to do this. Here we have the options field arguments on the articles query field where we can specify the sorting and a limit here. So how we can do pagination this way, and we saw something similar to this. So show me the 10 most recent articles and the topics connected to those articles.

The proper way to do this is to use what's called an optional match, because we may have some articles that don't have any topics. So you can see this loan node down here is an article without any topics. So first we need to find the 10 most recent articles, and then we can optionally traverse out from those articles to find any topics. If we just included article has topic, topic as the top-level match here, we would only find articles that have topics. anyway, so that's how we can do that in Cypher in GraphQL, we just add a nested layer to our selection set. So here we've added topics and name to represent that traversal from the article nodes once we find them to any topics that might exist. And because topics is a nullable field, we will find articles if they may not have any topics. So here's that one here, you can see the topics array, this is an empty array, which is similar in concept to this idea of the optional match. So how about adding more complexity to our graph patterns? So now we want to find the 10 most recent articles, the topics of those articles, but then other articles connected to those topics. And again, this is very similar to the example we saw a few minutes ago. We just add another piece to our graph pattern here. So now once we found the topic nodes for today's articles, we add another piece of the pattern to traverse out following that incoming has topic relationship to find other articles that have the same topics as today's articles. And in GraphQL, we just add another nesting to our selection set here to do that. So we within the topics field here, so starting on line seven, on lines nine and 10, we're now traversing two articles connected to these topic nodes.

9. Finding Shortest Path Between Nodes

Short description:

To find the shortest path between two nodes in the dataset, we can use Cypher's variable-length path operator. By specifying a pattern with the National Park Service and Federal Aviation Administration nodes, connected by any number of relationships, we can find the shortest path connecting them. This is achieved by using the shortest path function in Neo4j, which performs a binary breadth-first search. In our case, the shortest path is fairly short and is related to articles about worker shortages affecting both organizations.

Okay, what about something like this? So find the shortest path between two nodes in the dataset. So here we wanna find the shortest path from the National Park Service Organization to the Federal Aviation Administration. Well, Cypher has a couple of built-in functions here that are very useful for these sorts of operations. One of those is this idea of a variable-length path operator. So here, so we have these brackets with an asterisk. So we know that brackets represent relationships. So this is saying a pattern where, here's our National Park Service node, here's our FAA node, our organization nodes. If I didn't say this earlier, the way we represent properties in patterns is within curly braces. So this is saying find node with a label organization that has the name National Park Service, similar for the Federal Aviation Administration, these are government agencies in the U.S. But this bracket with the asterisk, this is saying find a pattern where these two nodes are connected, but connected by any number of intermittent nodes. So follow as many relationships as needed to find a connection between these two nodes in the graph. That's what the asterisk means. And I can parameterize this, I can say more than two, but less than five, like the sort of thing we typically don't want to have just this open-ended asterisk, but that's sort of the default. And this is wrapped in a shortest path function. So it's saying, find where this pattern exists, these two nodes are connected following any number of relationships, but find me specifically the shortest path connecting these and specifically Neo4j will do a binary breadth-first search or yeah, to find the shortest path connecting these two nodes and it ends up being fairly short. So here's the FAA, here's the National Park Service. There's an article about, FAA is an article about the National Park Service. They're both about shortages is the topic connecting these two articles specifically I think they're about worker shortages and having difficulty maintaining normal operations because of worker shortages. So it's being a fairly short path connecting these.

10. GraphQL and Database Querying

Short description:

GraphQL doesn't have built-in functionality for variable length paths or finding the shortest path between nodes. To show recommended articles, we can traverse the graph to find overlapping topics or geo regions. GraphQL doesn't have this functionality built-in, but we can add a query field in the data layer. When building a mobile app, it's best to have an intermediate API layer between the client and the database for handling authorization, caching, and custom logic. The iOS app queries the GraphQL API, which then queries the database layer.

Now, if we think about how we would write this query in Graph QL well, Graph QL doesn't really have this sort of functionality built in. There's no concept of variable length path. There's no concept of the shortest path between two nodes. We could expose the sort of functionality if we added a query fields that took in the sort of information we could certainly expose this through Graph QL but it's not something that is built in.

Here's another one. So show me recommended articles. So a common way to approach this if you're in the workshop on Tuesday we looked at this concept similarly for movies but a common way to do this is to traverse the graph to find overlapping in this case topics or geo regions or the author. So if I'm interested in an article that I'm reading that has certain topics show me other articles that are about similar topics if they have the most number of overlapping topics that's probably the best ranked recommendation. How would we do the same GraphQL? Well, GraphQL doesn't really have the sort of functionality built in. Of course, we could add a query field that exposes the sorta functionality. We would build that somewhere in the data layer but it's not something built in to GraphQL.

So then as we're thinking about how to architect our application we know we wanna build a mobile app that is allowing us to read the most recent news, personalize the news a little bit, or should we query the database directly? Do we wanna use GraphQL to do that? Well, looking at differences between Cypher and GraphQL we know we don't wanna just expose the database directly to our client but that's not typically what we wanna do in most cases. We wanna build some intermediate API layer that sits between the client and the database that allows us to handle things like authorization, caching, custom logic, these sorts of things that we wanna control in this API layer. So instead architecture should look something like this where our iOS app is querying a GraphQL API in this case maybe it's deployed as a Lambda function or something like that. And that API layer, that GraphQL server is the thing that is querying our database layer.

11. Building a GraphQL Service

Short description:

Let's talk about building a GraphQL service. We start with GraphQL type definitions and implement resolver functions. Resolver functions fetch data from the data layer, such as a database or another API. We combine the type definitions and resolver functions to create an executable GraphQL schema. To handle the N plus one query problem, we can use tools like DataLoader or database integrations. The Neo4j GraphQL library allows us to generate a fully functional GraphQL API without writing any resolvers. We'll start by setting up a Neo4j Aura instance and loading a database dump file. Let's sign in to Aura and create a blank database. We'll download the dump file and import it into our Neo4j Aura DB instance. Once we're set up, we can build our GraphQL API.

So let's talk about how we build a GraphQL service. There's sort of a standard approach that we can take here. One is we start with our GraphQL type definitions. So we define the data that we are working with, and then we need to implement resolver functions. So resolver functions are functions that have the logic for fetching data from the data layer, whether it's the database, whether it's on the wrapping another API that's encoded in these resolver functions, then we combine the type definitions and combine our resolver functions to have, what's called a executable GraphQL schema, which we can then expose over some networking layer to actually handle incoming requests.

So here's an example. This comes from an app that was built for showing conference sessions. You can see some type definitions on the left that describe the types we're working with. So we have a type for the conference session. We have a type for the speaker that's connected to the session. And then things like what company does the speaker work for? What room is the session in? And what is the theme of the session? So then our resolver functions might look something like this on the right where we have a map of functions that matches the type definitions. So for the entry point, we're not showing the query field on the left, but for the entry point, we would have a session field on the query type. That's the root resolver. So in this case, we start by searching for a session with a search string. So imagine a website somewhere where you type in, you know, GraphQL or whatever, whatever kinds of sessions you're interested in. And then this is using like an ORM that is injected into this context object here. So the context object is passed to every resolver function. And this is where we can do things like add handles to APIs or databases, or often we may just have some other data abstraction layer that we use in our resolvers. But here we're grabbing that database handle for some sort of like ORM type wrapper here to search for sessions by some search string. But then when the results of that query come back, so we found some sessions that match our search string, well then we have to go back to the database to find out what room it's in. We have to go back to the database to find out the theme of the session. And then another resolver function, if we've asked it for recommended or sort of like what are similar sessions to the ones we have searched for, that might be a fairly expensive operation depending on how we're doing that. And we have to do these three things for each session that comes back from our search results, so that could be lots and lots of round trips to the database. And so this is what's called the N plus one query problem, this comes up when we follow that sort of standard approach for building GraphQL APIs. And there are some ways around this. The one we'll see out there a lot is called data loader, which is a combination of batching and caching to try to reduce the number of requests to the database. Another option is using these database integrations that generate a single database query from a GraphQL request, which is what we're gonna do today when we use the Neo4j GraphQL library. But there's some other issues that come up as well, right? So, this is a lot of kind of boilerplate data fetching code that we're writing. We don't necessarily wanna be focusing on that as developers, we wanna focus on things where we can really add a bit more value. Things like schema duplication, mapping and translation layer for not using graphs on the backend and our resolvers, we have to kind of think of how to map from the graph model that we're using in GraphQL to some other data model. So this is where database integrations like the Neo4j GraphQL library come in. So, in this case, we're gonna see how we can take just type definitions and generate a fully functional GraphQL API without writing any resolvers. But to do that, first we need to start with a database.

And so in this section, what we're gonna do is spin up a free Neo4j Aura instance, loaded with some news data, and then we can start to build our GraphQL API. So, let's all set up our Aura instance. So there's two things we're gonna do here. One is, we're going to sign in to Aura, you can create an account with either a Google sign-in or username and password, email and password, if you don't wanna use Google. And then we're gonna load a database dump file, so a snapshot of that news data, so that we all have the dataset loaded and ready to go. So the first thing we're gonna do is go to neo4j.com slash Aura, and you'll see like a start free sign in button. So go ahead and open that up, sign in to Aura. And the first thing you'll be prompted with is option to start a database. You'll see different options, I'll go through this in a minute, so we can all see what it looks like. Options for loading different datasets, so there's one for like movies, one for stack overflow examples, but we want to create a blank database, we're gonna load our own data. And then you'll see a generated password pop up, be sure to copy that, paste that somewhere, we'll need to access that later. You can also download a.env file from that screen, so that's a good idea too, just to download that so you have it. And then we'll see the connection URI, so the connection string for your Aura instance as well, which is something we'll note for later. Once you've done that, then we're gonna download this dump file, drop a link to that in the chat as well. So this is an archive or a snapshot of the Newsgraph data, and then we're going to import that into our Neo4j Aura DB instance. So if you click on your instance in the console, go to import database, you'll see a place to drag and drop or select the dump file to import. So let's all go ahead and do that. So we have our data ready to go. I'll go through and do that now so you can see what it looks like, and then we'll take a break for a couple of minutes to make sure everyone is set up with that and ready to go. So I'm going to go to Neo4j.com slash aura and click on start free. And see there's different tiers for Aura. So there's the free tier, which is good for like it's kind of workshops or hobby projects. And then there's the professional tier where we can start to scale up our database if we have production deployments, larger data sets we want to work with. And then of course there's an enterprise tier if we need more features for that. So I'm going to sign in. Like I said, we can either use Google or you can create an account with email and password. I'll just use Google since that's easy enough for me to do. And then, oh, I have an instance running. I'm going to kill this one. That's from, I think that's our one from the Tuesday workshop. So I'm going to kill that one. But if you haven't signed into aura before you won't see that. Instead, what you'll see is this screen that says get started by picking a dataset. And if we select one of these, we'll have a dataset already loaded, but I want this empty instance. I'm going to say create that. I'm going to download the.env file and I'm going to copy my password and save it somewhere so I have access to that later. Yeah, and it's important always to make sure we grab that before clicking off the screen since we can't find that initial password again.

12. Setting up Aura and Loading Dataset

Short description:

While waiting for the Aura instance to spin up, download the news dump file. The dataset includes articles, authors, topics, people, organizations, and georegions from the New York Times API. The New York Times API provides free access to the data, which is suitable for building applications. Once the Aura instance is running, import the news dump file. Pause for a few minutes to allow everyone to set up their Aura instance and load the dataset. After the data is loaded, we can proceed to build a GraphQL API. If you encounter any issues during the process, let us know in the chat for assistance. The free tier of Aura has a limit on the size of the data that can be stored.

Okay, so this'll take a few moments. While that's spinning up, I'm going to download this news dump. So let's copy that. And this'll just download a zip archive from S3. That's fairly small. I think it's only maybe like 10 megs or something like that. And then once my Aura instance is up and running, and this'll take a minute or so to spin up, then we can import our news dump.

Once we have that running, you have just a preview of where we're gonna go with this, and then we'll pause for a few minutes. This will load the NewsGraph datasets. I'm at the snapshots, so it doesn't have the most recent news. It's from I'm not sure when I took it, maybe a month or so ago, but the same basic data model. So articles, authors, topics, people, organizations, and georegions about news from the New York Times API. I linked the site for the New York Times API. It's free, you just need to request a developer key to work with this data. It's a good dataset for building applications. They also have things like book reviews and other. I think they have sort of their own knowledge graph for more information about people, these sorts of things. But if you're interested in more in this data set, this GitHub repository, which I'll link in the chat. This has the code I showed earlier, the GitHub Action for fetching this data. But then there's some examples for how to work with the data in Cypher. There's a graphQL directory, which we're gonna look at in a moment. And then also, I did a workshop on building a Cloudflare workers API to fetch this data. Anyway, so that is all online.

Let's see, is our Aura instance not up yet? So maybe let's go ahead and pause here for a few minutes for everyone to have a chance to go ahead and sign into Aura, create a new blank instance, download the dump archive. And we'll wait a few minutes for that to spin up and then load that dataset. So we'll pause here for a few minutes. Maybe we'll come back at 15 after the hour. That's in four minutes. So if you run into any issues, let us know in the chat and we'll get that figured out because we do wanna have our Aura instance with our dataset loaded before we move on.

While we're waiting I'll just go through the steps here. Now that mine is running, we can tell it's up and running because we see this green circle that says running. So I'm gonna click on this and I can see some sample code and whatnot, but I wanna go to import database. I can either drag and drop or click, oops, that's not what I meant to click on. That's why I have a larger dataset. I'm gonna click on this and browse and this is just downloaded to my downloads folder News-Graph, mine has number three because this is the third time I've downloaded it. It's called News-Graph.dump. Warnings is gonna replace my empty database. Yep, that's fine. And so this will take a few minutes to upload and then restart the database, but okay. Now we will pause to give everyone a chance to go through this process and get your aura instance set up and then when we come back, we will take a look at building a GraphQL API.

So I see a question from Anthony. Oh yeah, talking about the new UI and aura not having an option to upload a dump file only CSV. Yeah, so let's look at that. That's a good point. So there's a new workspace. I think it's called workspace experience for Neo4j aura. And so you may, I think it's now the default. So you have this open button, which my database is restarting. So it won't load right now. Otherwise, and then you can toggle between this. If I click on my user icon, it says I'm using the new workspace experience. Or I can switch back to the classic experience where I have things like explore query import. So that's one thing we can toggle back and forth between those. I'll talk about what that is in a second, it's basically a different way of combining the things like Neo4j browser, Bloom and a data importer option.

So here's what that looks like. If I click open, that will take me to a workspace and I can connect to my instance. And Anthony, if you're looking at the import, that's where the option for uploading CSVs is. But what I wanna do to upload a dump file instead is to click on the card. Like, I should've said this earlier, not click on the open icon, but if I click on the card for the database, then I get this screen. And here I can go to import database and click browse to find my dump file. So if you find yourself in this screen, so if you find yourself in this screen which is import for uploading CSVs, that's not the one we want where, this is the data import tool, which is really cool, a way to visually define a graph model from CSV files, which is quite neat. The query bar, this is similar to Neo4j browser, we have similar functionality here and then explore. This is the bloom visualization tool, which I showed a couple of screenshots before. So the new workspace UI, the idea is to combine, what were previously different developer tools into a single developer tool. Anyway, yeah, so instead what we want is go back to the Aura console, click on the card for our database and look for the import database option. Cool, Anthony, cool, it says you figured that out. Cool, anyone else get stuck with anything? Is there anyone else done, anyone else able to start their Aura instance and then also upload the dump file? Let us know if you got through that or even if you didn't, if you're stuck on something. Once the data is loaded, you'll see the number here for nodes, what do we have? We have 31,000 nodes and 80,000 relationships. And you'll see like a percentage of, what is this, 200,000 and 400,000. So the free tier has a limit on the size of the data that we can store.

13. Working with Datasets and the flat graph Action

Short description:

Our news dataset is fairly small, so we have plenty of space in our free tier. We use GitHub Actions, specifically the flat graph action, to fetch data from JSON APIs or databases and load it into a Neo4j instance. We can set up a cron job to periodically fetch data and load it into an Aura instance. I also use this for lobsters, a tech news site similar to hacker news. I wrote a visualization tool that uses GraphQL to render the lobsters articles.

So you can see our news dataset that we're working with is fairly small. So we have plenty of more space in our free tier but that's what the limit there is on the number of nodes and relationships just because we're using the free tier. If we're using the pro tier, we can choose to scale that up by memory for the different instant sizes. Cool, I don't see anyone else say that they are stuck. So let's go back to the slides here and we'll talk about the dataset. We already talked a little bit about the dataset. I talked a bit about where the data comes from. I linked that GitHub page. I said that we're using GitHub Actions to do this. Specifically, we're using this action that I wrote called flat graph. So flat is a GitHub Action that the GitHub Open Source Team published for fetching data from like JSON APIs or from a database. And then checking it into the GitHub repo. And flat graph was an action that I wrote that just allows you to write a Cypher query to define how you want to work with that data. So, you know, in our case, we're using that JSON data that the flat GitHub Action fetches for us and then checks into the repo. Then with flat graph, we just write a Cypher query that says how we want to load that data into, in this case, a Neo4j Aura instance. But you can point it at any Neo4j instance. So I thought that was a handy way of just kind of setting up a cron job to periodically fetch data, load it into an Aura instance, which was kind of fun. I have this running also for lobsters. If you know lobsters, it's a tech news site that kind of similar to hacker news, but I think a little more friendly. So I also fetched the days articles on lobsters using that same flat graph option. And then I wrote a couple of blog posts about how to do that. There's, I think we have... Yeah, here it is. There's just a little visualization tool that I wrote. This also uses GraphQL to give us a sort of visual representation of the days lobsters articles as well. So this is querying a GraphQL API to render this visualization. Anyway, that's a bit of an aside.

14. Writing a Recommendation Query

Short description:

We had an exercise to write a recommendation query. We're going to write a Cypher query to find similar articles to the one we're looking at. We'll use a count aggregating function to compute a score for the recommended articles. We can add other pieces to the pattern, such as organizations and people mentioned in the articles. This is our top-rated recommendation for a follow-up article for a user to read. We can use this query to add personalization to our news app. If you have any questions, feel free to ask in the chat or on Discord.

Let's see, we had an exercise here to write a recommendation query. Maybe let's go through this one to gather since we're maybe a little short on time. Let's just do this one kind of quickly. And this also makes sure we're able to work with our Aura data and make sure we loaded the data correctly.

So now I'm going to click this Open button and this is going to launch workspace. And again, I think this is the default. So if you're using Aura for the first time, I think everyone will see that, but you may also see this Explore Query Imports. So you can either hit Query, which will take you to Neo4j Browser or if you're using the new workspace, just hit Open and that will then ask you for your Neo4j password, which popped up on the screen. That's the thing we had to click through to say, yes, I did save that, cool. And I think by default, first, it takes us to Explore, which is the visualization tool, but we want Query because we're going to write some Cypher Queries. And so the first thing we can do is just make sure we have the right dataset. So I'm going to do a call db.schema.visualization. And we can see this is the same dataset we were working with earlier. And here's the query we wrote earlier to find the day's news, order by published and descending order, show me the most recent time, so here's the most recent news articles. Oh yeah, and let's see, this is from June. Okay, so this archive is a few months old at this point, so we have some old news. That's okay though, it's the same data model. And we can double-click to traverse out to explore the graph.

But okay, so the exercise for this one is, give an article, write a Cypher query to find similar articles. So got multiple workspace windows, let's close those. Here's the one we want. Okay, so give it an article, so let's just say limit one. So just assuming we're working with one article. Here's Gerber Baby, what does that say? That's like the model for baby food, okay. There are actually multiple articles about baby food in our dataset. Okay, so we're going to write a baby food article recommendation query here. So if I'm reading this article about baby food in our app, we might want to show other articles that the user might be interested in based on the article they're currently reading. So you scroll through the article, you get to the end. And the question now is how do I show sort of more articles for the user to read? They're probably interested in reading things similar to the one they sort of clicked on and read through. So how can we write a Cypher query to find similar articles to this one that we're looking at? So I'm gonna change this return to a WITH. WITH just allows us to sort of pipe through results to my Cypher, later pieces of my Cypher query. And we're gonna do another MATCH. And we're gonna say, so here's A, this is the article node. And what we're gonna do is look for other articles that have similar, or the same topic rather. Here. And we're gonna call that rec, so this is our recommended article. So here's articles that have at least one overlapping topic with our Gerber baby article. But we can score these, as well. So we can use a count aggregating function to compute a score. So in Cypher, anytime we use an aggregating function along with some value, we implicitly group by the value that we're returning alongside the aggregating function. In SQL, you would write specifically a group by statement to do this. If we look in the table, result, and let's return rect.title. So it's a little more obvious. So in this case, the score is one. We're always finding just one overlapping topic. So the score doesn't quite help there, but can we add maybe some other... pieces to the pattern here? No, we still get, we'll just get one. So one thing that's nice is we can add other pieces here. So are there organizations that are mentioned? Are there people that are mentioned? We can do this pipe, which becomes an OR operation. Here we go, we found one. So there's multiple articles about, I'm guessing about Gerber. Since we added the organization. So now this article has a score of two because it has an overlapping organization and topic. So this is our top rated recommendation for a followup article for a user to read. And of course this is gonna be different. We did like a, let's do a skip and a limit here to find other articles. Let's find one thing not about guns and mass shootings. Okay, and let's order by, order by score. We want to show the top recommendations first. So here's some articles about coffee and caffeine and cockroaches, various health-related things. So this query should be good for sort of a general purpose article recommendation query. And so we'll use this later on to add some personalization to our news app. Cool.

So let's see where we are now. So we did that. Now we're ready to build a GraphQL API. Did anyone have any questions before we move on to the next session? You can always ask any questions in the chat, but I just want to call that out. Oh, and I'm also looking at Discord too. So if you're asking in Discord, we can do that as well, but just be sure that that option is available to folks. If you get stuck on something or want to clarify something or want to dig in more to a certain topic, feel free to just ask in the chat.

15. Building a GraphQL API with Neo4j GraphQL Library

Short description:

Let's talk about building a GraphQL API using the Neo4j GraphQL library. We define our data model with GraphQL type definitions and can add schema directives for custom logic and data mapping. The Neo4j GraphQL library generates a GraphQL API from our type definitions and translates GraphQL requests into database queries. We can also add custom logic using the Cypher GraphQL schema directive. There are two ways to get started with the Neo4j GraphQL library: building a NodeJS GraphQL server or using the Neo4j GraphQL toolbox for low-code development and testing.

Okay. Let's talk now that we have our database set up. We've got our news articles data loaded, our knowledge graph of news data. Let's see how we can now build a GraphQL API to expose that data to our clients' application.

So we've talked about the Neo4j GraphQL library a couple times now. We are going to use it to build a GraphQL API on top of the Neo4j Aura instance that we each configured and set up just now.

So let's talk a little bit about some of the features of the Neo4j GraphQL library and how that relates to what we are trying to do with building our news application. So first of all, the high-level goal of the Neo4j GraphQL library is to support this idea of GraphQL-first development. So the idea is we take our GraphQL type definitions that define the data model for our GraphQL API, but also for the database.

Now, we don't necessarily want to expose all of the data in our database. Maybe we want to add some authorization rules. Maybe we want to tweak some of the mappings for how we're exposing data. And we can do that by adding schema directives to our GraphQL-type definitions. So schema directives are GraphQL's built-in extension mechanism to indicate, hey, there's some sort of custom logic that should happen here. So we'll see a few of these.

16. Configuring Neo4j GraphQL Library

Short description:

We exclude mutation operations in the generated API to prevent users from making updates to the database. Relationship fields in Neo4j include the direction and type of the relationship, which can be different from GraphQL conventions. Schema directives in the Neo4j GraphQL library configure the generated API by augmenting the type definitions with query and mutation fields, arguments, and native database types. The library translates GraphQL requests into database queries, fetching only the required data.

So we'll see a few of these. So here's an exclude directive. Think of a directive as kind of like an annotation on a field or on a type. So this exclude directive is specific to the Neo4j GraphQL library. And this is saying exclude the following operations in the generated API for the article type. So exclude, create, update, and delete. So because we're not adding data to our GraphQL API, our newsreader app is going to be just a reading app. We don't want users to be able to make updates to the database from the app. So we're gonna exclude any mutation operations.

We also need to add the relationship directive to any relationship fields, so fields that are connecting types to include the direction of the relationship in Neo4j. So when we were talking about the property graph model earlier, we mentioned that the property graph model includes a direction for every relationship. And then we can also specify the type of relationship, and this is nice because we have different conventions for the naming in the property graph model that we use with Neo4j and in GraphQL. So here we're saying that the photo field which is a relationship field in the database that's represented as, has photo in, what is this called, snake case, whereas in GraphQL, we typically use camel case. And so that allows us to have a different mapping of how we want to expose that data as a field in GraphQL to how we want to store that data in the database.

The concept here is GraphQL type definitions define the GraphQL API, but also the database. And we configure the generated APIs. We're gonna generate a GraphQL API using the Neo4j GraphQL library. We configure that by using schema directives, which are these annotations in our type definitions. So the Neo4j GraphQL library is going to auto generate a GraphQL API from our type definitions. And so this is, you think of this as sort of augmenting the type definitions to include things like the query or mutation fields, the arguments that we saw earlier for things like ordering, pagination, the filter argument. And then adding types that are native in the database. So things like the geospatial point type or the date type that we have in the database, adding those to our schema in GraphQL. Then at query time, the Neo4j GraphQL library is going to translate or generate a database query from any arbitrary GraphQL request. So here we're looking for the 10 most recent articles, some fields on the article node, the topics. That's gonna be translated automatically with the generated resolvers to this cipher statement. That's going to fetch just exactly the data that we need from the database.

17. Using Cypher GraphQL Schema Directive

Short description:

We can use the cypher GraphQL schema directive to define CustomLogic in our GraphQL type definitions. By attaching a cypher statement to a field, we can calculate Jaccard similarity of articles to generate personalized recommendations. This functionality can be added to our API by including the cypher query in our GraphQL type definitions.

So so far, we've been talking about basic sort of CRUD operations, so create read, update, delete, so searching, filtering, we've skipped over mutations, but by default, we're also generating operations for creating nodes, for updating, deleting, those sorts of things. But how do we deal with CustomLogic? Well, for that, we can use another schema directive, this is the cypher GraphQL schema directive, where we can annotate a field in our GraphQL type definitions with a schema directive and attach a cypher statement that defines CustomLogic. So now we've added a similar field on the article type. So now we're using this cypher statement and this is using a graph data science function called Jaccard similarity to calculate Jaccard similarity of articles to generate recommendations. So that's another way of generating personalized recommendations. So we saw previously this query where we were finding recommendations for an article by traversing the graph. So imagine we wanted to add this functionality to our API so that we can expose custom logic. We would take this cypher query and we would basically add that cypher query here in our GraphQL type definitions to expose that functionality through our GraphQL API.

18. Getting Started with Neo4j GraphQL Library

Short description:

There are two ways to get started with the Neo4j GraphQL library: building a NodeJS GraphQL server application or using the Neo4j GraphQL toolbox for low-code development and testing. Dependencies like the Neo4j GraphQL library, GraphQL JavaScript reference implementation, and Neo4j driver need to be installed. The Neo4j JavaScript driver allows connection to the Neo4j instance, and Apollo server is used as the GraphQL server.

So there are two ways to get started with the Neo4j GraphQL library. One is we can build a NodeJS GraphQL server application and then use a GraphQL server like Apollo server, GraphQL yoga. Any JavaScript GraphQL implementation will work or we can use a sort of low code in browser tool for development and testing called the Neo4j GraphQL toolbox. Here's what this looks like for building a NodeJS GraphQL server with the Neo4j GraphQL library. We're gonna install our dependencies, so the Neo4j GraphQL and you don't need to follow along. We're gonna use a code sandbox that has this set up for us in a minute, just showing how we would get started. There's some dependencies we need to install like the Neo4j GraphQL library of MPM. We need the GraphQL JavaScript reference implementation and the Neo4j driver. Those are peer dependencies of the Neo4j GraphQL library, so the Neo4j JavaScript driver just allows us to make a connection to our Neo4j instance from our JavaScript code. And then whatever flavor of GraphQL server we're gonna use, here we're using Apollo server.

19. Building a Newsreader iOS App with Neo4j GraphQL

Short description:

Mohammed apologizes for joining late. We're building a newsreader iOS app using the Neo4j GraphQL library. We can define GraphQL type definitions for movies and actors. We create a driver instance with the connection credentials for our Neo4j instance. The Neo4j GraphQL library generates a Neo4j schema object, which we pass to Apollo Server to spin up our GraphQL API. Another option is to use GraphQL Toolbox, a low-code tool for working with the Neo4j GraphQL library and Neo4j. We can introspect the data in our database and generate GraphQL type definitions that match the data. We can modify the field names to make more sense. The build schema button generates a GraphQL API based on the type definitions. The GraphQL Explorer allows us to build queries and see the generated Cypher statements. We can enable debug mode to see the generated database queries. We'll pause for participants to set up GraphQL Toolbox and think about how to recommend articles. We'll add the recommended article feature to our type definitions.

Mohammed says, sorry for joining late. Oh, yeah, no worries. Thanks for joining, we're building a newsreader iOS app. You should be able to see the slides and the various repositories linked in the chat, if you want to kind of follow along. Yeah, thanks for joining, no worries.

Here's the basic snippet now for using the Neo4j GraphQL library. Basically, we pull in those imports, the first step is defining our GraphQL type definitions. Here we're using movies and actors. Then we create a driver instance with the connection credentials for our Neo4j instance. We pass the type definitions and our driver instance. When we instantiate the Neo4j GraphQL, this gives us a Neo4j schema object, which we can then pass to Apollo Server to spin up our GraphQL API. So that's one way of building a Node.js GraphQL server.

The other option, which this is really nice for testing and development, is to use this tool called GraphQL Toolbox, which is a low-code tool for working with the Neo4j GraphQL library and Neo4j. So we're gonna start with this one, and this has a really powerful introspection feature. So because we're starting with a database, we can load type definitions that match the database without having to write them automatically. So let's go ahead and open up GraphQL Toolbox, and remove this piece of the instructions. That's no longer relevant. So what we're gonna do is open up GraphQL Toolbox. So here's the URL, I'll drop this in the chat. So we'll open that up. And then the first thing we're gonna see is a prompt for what database we want to connect to. And this is where we're going to use our Neo4j Aura instance. So here we're gonna go back to the Aura console and this connection URI. So whatever that is for your database instance, let's copy that. And then the username by default is gonna be Neo4j. And then your password for your instance. Okay, cool. And this has some type definitions from a previous project I was working on, but you'll see a box to ask if you want to introspect your dataset. So go ahead and click that to introspect the data. What that is gonna do is that's gonna go to the database data about the news articles and generate GraphQL type definitions that matches the data that we have in the database. So we'll see a type for article, a type for the geo regions, a type for organization, person photo and topic and the connections between them, those relationship fields. And by default some of these names don't make a whole lot of sense. So the convention is to use the name of the relationship type combined with the node label for the field names. So things like article about geo geos, that doesn't make a lot of sense. We can change this, this is just sort of our initial starting point. So we can change this to geos, we can change this to organization, we can change this to people and so on for something that makes a bit more sense. And then if we hit this build schema button, that's now going to go through the schema generation process and generates a GraphQL API based on those type definitions. And we can see the operations. This is a query from a previous project and I deleted that. But we can see the entry points here. This is a GraphQL Explorer. You can also toggle the documentation on if we want to see the documentation view, but GraphQL Explorer allows us to see the query fields and the various options available to build up a selection set. So we want what probably publish date, title, and URL of the article. We want to limit, so you'll need the first 10 and let's sort by publish descending. You can see how as I'm just sort of clicking through here on Explorer, that query is getting built up in the query editor. We'll give that a run and we should see the most recent articles in the database. If I open up the developer tools, I'll go to the JavaScript console and we also need to enable debug mode and then build my schema again. But now when I run the queries, I'll zoom in a bit on the developer console. When I run the queries, I can see the generated cipher statements. So here's the generated cipher statements for this GraphQL query. So this is really nice for development. I can see what database queries are being generated for my GraphQL queries that I'm running. Cool, well, let's pause here for folks to set up GraphQL toolbox, point that at your Neo4j Aura instance and write a few queries. If you already have that done and you want to get ahead a little bit, think about how would we recommend articles that users might be interested in. So we saw the query that we wrote here in Cipher, and we talked about the Cipher schema directive. Think about how we could update our type definitions here in the type definition editor to include that field on the article type to show recommended articles. So if you wanna work ahead, think about that, we'll pause for a few minutes. And then when we come back, we will take a look at adding that recommended article feature to our type definitions. I'll drop a link to the documentation, which we should be looking at that. So if we go to neo4j.com.doc, so we have all the documentation for all things Neo4j, but we're using the Neo4j graphical library. So this is a link to the documentation for the library. And then for that specific Cypher feature, if we look here under directives, we can see all of the directives available with the Neo4j GraphQL library. Specifically we want a Cypher. So here's the docs for how we would handle that custom logic with Cypher. Okay, cool. So I see a question from Anthony in the chat. So this is in toolbox and looking at the response up to the type definitions, toggled, enable debug, but not seeing the debug panel. Yeah, so the way that works, I'll close this. So the way that the debug option works, so here in the type definition screen, if we toggle this and then hit build schema again to go back to the query editor, debug mode basically logs to the console. And so you have to go to open developer tools in your web browser to see that.

20. Using the Cypher Directive for Custom Logic

Short description:

To debug the application, open the developer console or JavaScript console in your web browser. Check if everyone has set up the toolbox and generated type definitions for their Aura instance. Write a GraphQL query to find the most recent news articles. Add personalization to the app by showing similar articles after a user finishes reading. Use the Cypher directive to express custom logic in Cypher. Add a similar field to the article type and execute the query to find similar articles. Modify the cypher statement to compute recommendations for a specific article. Add a field argument to limit the number of similar articles returned. The cypher directive is a powerful feature for adding custom logic to the GraphQL API. It allows us to use any logic expressed in cypher and addresses the n plus one query problem. The GraphQL toolbox is still in beta, so stay tuned for more features and the final name.

So in Chrome, that's view developer JavaScript console. You're using Firefox or Safari, they have something similar. I'm not sure what the flow is to get that, but you want the developer console or the JavaScript console, whatever it's called in your web browser. And then that will show the things that the application is logging to the console. And that's where you should be able to see the debug output.

How about everyone else? Did everyone get the toolbox pointed at their Aura instance and generate type definitions? Are folks able to write a GraphQL query to find the most recent news articles? What about the recommended article feature? Did anyone get that one? Let's take a look at that.

So, finding the most recent articles, we've seen that we've done that one a couple of times now. This is what that looks like. We're gonna use the options field arguments to do a limit ten and sort by published and descending order for the articles. But the next question which is, okay, I'm seeing some articles in the app, I wanna add some sort of personalization so that after a user is done reading it, I wanna show them similar articles. And we saw how to do that in Cypher, but we don't have that sort of functionality exposed through GraphQL, right? But we can express that custom logic in Cypher. So, that's this query here, where we were traversing from the article to find other articles that have overlapping topics, people or organizations. And we're using the count of that overlap as sort of a score for the recommendations. So, let's take this query, we'll just copy this, and go back to toolbox. And in the type definition editor, I'm going to add a field to the article type. And let's call this similar. And the similar field, this is going to be an array field of articles. And we're going to add a cypher directive. And cypher directive takes a statement argument, which is going to be my cypher query. And a little awkward, that's a long traversal statement here. But this is the same query we're looking at earlier where we're looking for overlapping topics, people and organizations. So this cypher directive field, let me zoom in a bit and make that as big as I can. So what we're saying here is the article type, we're adding a field called similar, that's gonna evaluate to an article, object array field. But we don't just have this in the database somewhere so we can't just fetch that from the database, this is something we need to compute using Cypher. And so the Cypher schema directive allows us to take a Cypher statement and add logic to a field so that when we request a similar field, we are executing this Cypher statement. And so we need to tweak this Cypher statement that we copied and pasted a little bit instead of matching on any article, we want to compute this recommendation for a specific article and that specific article is the article that we're currently resolving. And so there's a convention here that we use to inject a Cypher variable called this. So this now refers to the Cypher variable node that we are currently resolving. So I don't need this width and the order and limit. And instead of starting my traversal from some node A, I'm gonna start it from this. And what I'm gonna return now is the recommendation. So now I'm gonna return the recommended article nodes and I'm gonna go to build schema. And now if I look in Explorer over here, I should have now a similar field that's gonna give me similar articles and let's add title and URL and let's run this. So this is saying find the 10 most recent news articles and then for each one of those, show me similar articles. And now, so here's, was this a red flag gun law and the similar articles I'm getting to that are articles about gun control, school shootings. It's this kind of stuff. Anthony says, can I paste the snippet in the chat? Yeah, definitely. So here's the similar field that we added. Let's grab that. I'll just paste that in the chat. Hopefully that formatting is okay. Might be some weird spaces in there in the Zoom chat. Not sure, hopefully that works. Okay, so one thing to think about is when we run this, when we run this we're returning as many similar articles as we find, which basically, well, you just for this one article, this looks like hundreds of overlapping topic nodes for this article. So we probably wanna tweak this a little bit to allow the client to say, only show me the, I know, top 10 or top three or whatever. And so we can do that by adding a field argument here. So similar is going to take, I don't know if we can call it first, and it's gonna be an integer field and we can give it a default value. So this is just saying, we're going to add a field argument first, it's an integer, and we're setting that default value to three. So now any field arguments that we define here these are available in the cypher statement as cypher variables. So we can add a limit first here. We're only going to return the first by default three, but we can configure that number. We just pass in a value. I like to add a default value when we do this because we know that this is always going to be defined. So when we reference these variables in cypher we know that those are always defined. So now I'm going to, I hit build schema and then I execute the query. And now we're only getting three similar articles for each one. And we can change that to say, let's just bring back one. And now we're just bringing back one similar article for each of our most recent 10 articles that we're switching. Cool. So that's the cypher directive. That is a super powerful functionality for adding custom logic to our GraphQL API. We can really use any logic that we can express in cypher here. We can attach to our GraphQL schema to add that custom logic, which is a super powerful feature when we're using the Neo4j GraphQL library. And we're also, let's look at the generated cypher statement for this. This looks a little weird, but we can see that we're generating a single cypher statement, even with our custom cypher statement that we wrote for finding recommendations that's embedded in the overall generated cypher statement as a sub query, which is really cool because we still are addressing that n plus one query problem with custom logic just by sending one round trip to the database. So super cool feature, super powerful. So that was a look at toolbox. This GraphQL toolbox is still in beta. So not the finalized feature sets or the finalized name even if you have ideas for naming definitely.

21. Building a GraphQL Server with Code Sandbox

Short description:

We're going to look at writing JavaScript code to build a GraphQL server using Code Sandbox, an in-browser development environment. We'll fork the sandbox and update the connection credentials to our Neo4j Aura instance. The.env file sets environment variables for the GraphQL server. We'll clarify the syntax for providing arguments in a GraphQL query, ensuring integers are passed instead of strings. The GraphQL schema in the code sandbox is similar to the one generated in the toolbox application. We'll use the extend functionality to add the similar field to our type definition.

So not the finalized feature sets or the finalized name even if you have ideas for naming definitely. Taking suggestions there. Cool, so, toolbox that's just a hosted web app. You can use that and anytime and just point it at a Neo4j database.

Let's take a look at the other option that we talked about, which is the case where we have a application that we want to build and deploy somewhere. So, toolbox is useful for testing and development but it doesn't give us a GraphQL server application that we can deploy somewhere and query our clients using our clients.

So, now we're gonna look at actually writing some JavaScript, excuse me, some NodeJS JavaScript code to build a GraphQL server. So, let's open up Code Sandbox and I'll drop this link in the chat. So, we had an open up this link. This will open up Code Sandbox, which is like an in-browser development environment. This allows us to write NodeJS JavaScript code just in the browser that runs on a container somewhere for free that we don't have to think about. This code you can see here, this links to a GitHub repository.

Okay, and so what we wanna do, this is just pulling the code from GitHub and we can see there's this dotenv file with a Neo4j database that we were looking at earlier. Although I did notice there was some DNS issue with this. So we want to replace this with our Aura database anyway. What we wanna do now is fork this. So we want to fork the sandbox so that we can make changes to it and then it'll be personalized to us. In order to fork it, it'll ask you to sign in the code sandbox. You can sign in with GitHub or Google or create an account, something like that. But the first change I wanna make is in this.env file. We'll take a look at all the code in a minute. But in this.env file, I wanna change the connection credentials to my Neo4j Aura instance. The database that we created with our news data. So I'm gonna go back to the Aura console, I'm gonna grab the connection URI from right here. So this is specific to whichever instance we created for ourselves. And that goes in the Neo4j URI environment variable. So this is a.env file that's just setting environment variables when our GraphQL server starts up. And then we reference these to create a connection to Neo4j. So this, the protocol here by the way, this Neo4j plus S colon slash slash, the Neo4j this is the the protocol, the binary protocol for how to connect to Neo4j. And then the plus s just means this needs to be a secure connection. If we didn't have that plus S we would allow unencrypted connections. But with Aura, we have that ability to make security connections. So that's what the plus S is. And this is just the domain for my database. In this case, yours will be different. The Neo4j user is gonna be neo4j. And the password is going to be whatever your Aura password was. I'm gonna paste mine in here. Okay, and then I saved that. And then I think I need to restart the server, maybe, to get that to pick up again. So that's gonna restart my container to pick up those changes. Anthony asks, can you clarify syntax for providing arguments in a GraphQL query? And so specifically with looking at the first argument in the similar field. Yeah, and Anthony, in that example that you pasted, I see you have quotes around the one, and so that is gonna make that a string with the quotes around it, and we specifically wanna pass integers. But yeah, that's a good one. Let's do that right now, actually, for our, we'll do this in code sandbox since we're here. So let's look at the code. So here's our.env file. If we look at, sort of package.json, I can just see what packages we're bringing in. We're bringing in the Neo4j GraphQL Library, ApolloServer,.env is just for setting environment variables, and then the peer dependencies for the Neo4j GraphQL Library are the GraphQL JavaScript implementation and the Neo4j JavaScript driver. In index.js, we're pulling in those packages, loading our environment variables. Here, we're creating a connection to Neo4j using the JavaScript driver. And then we're loading our type definitions from the schema.graphql file. Which we'll look at in a minute. Then we're passing that, those type definitions and our driver instance when we instantiate a new instance of Neo4j GraphQL, it's this neoschema. And then we go through the schema augmentation process. So that's this neoschema.getschema. This is a async function. The reason it's async is because there can be some index configuration directives. So, we have the ability to say, hey, we should have an index or a constraint on this field. And so this is an async function because the Neo4j GraphQL library will go to our database and make sure those indexes are online before generating the executable schema object. And we're passing that to Apollo server. We're using the GraphQL playground Apollo server plugin so that we're just being consistent with using GraphQL playground. The default now with Apollo server is the Apollo studio sandbox. Okay, here's our GraphQL schema, and this should look pretty similar to the schema that we generated in our toolbox application. And so Anthony's question was on clarifying syntax for arguments in the GraphQL query. So let's look at that. So if we go back to toolbox, I'm gonna grab our similar field here that we added and go back to my code sandbox. And here we're going to, let's just use, let's use the extend functionality. So this is useful if we have our type definition split up across multiple files, which is a common pattern, we can, instead of just adding a field in our initial type definition, we can use the extend to add fields. And we're gonna add this similar field.

22. GraphQL Data Fetching in iOS with SwiftUI

Short description:

So Anthony's question was about finding articles similar to the one being resolved. We added a field argument with a default value of three that gets injected into the Cypher statement. We use SwiftUI to build iOS, Mac OS, and tvOS applications. SwiftUI allows for composing multiple views and using view modifiers to style them. We can do GraphQL data fetching in an iOS app using the Apollo iOS library, which is a Swift GraphQL client.

So Anthony's question was, okay, here I've, let me paste this into chat as well. So we have the full thing. So this Cypher statement is finding articles similar to the article we're currently resolving. So that's, this is the special keyword for the article we're currently resolving. And we added this first field argument with a default value of three that gets injected into the Cypher statement using Cypher variables.

Here, with this first Cypher variable, we're referring to the field argument. And it has a default value of three, so if we don't specify it, then we, we're using that value of three. So I save that change. I thought I had nodemon set up for this, but I don't, so I need to go restart. Can you do at least restart the sandbox to pick up those changes? So let's restart the server again, pick up those changes. I think that's how that works. I should edit this to, if I had this using nodemon instead of just node, that I think anytime we change those files, it will update the app. So kind of a pain to restart our sandbox each time. But anyway, so now we can go articles, options, limit 10. Let's not worry about sorting. And I can bring back the title and URL. Let's run that. This can't connect to the database. Yeah, I think for some reason that didn't pick up my changes to that.env file. So I think we're still trying to access a different database. That's not actually available for DNS. So Code Sandbox is great when we don't have issues with it. But anyway, I think we should still see the syntax here. So similar, first one title, so that's the syntax that we use. And so now that the similar with the first one one is the field argument passed in to our Cypher statement here. And now we get a different error. Why is that? Unknown function. Well, it shouldn't be unknown. This is my ora instance. Yeah, that's odd. Yeah, something's going on. I think we're not, oh, here we go. So now that picked up our database change. Maybe our sandbox wasn't quite restarting. Not sure what the issue is there. Anyway, yeah. That is a look at the code that we use for writing a GraphQL server using Node.js. So notice that we didn't have to write any resolvers. That is very nice for developer experience. That allows us to get up and running really quickly. Everything is driven from our type definitions, which is super cool.

Okay, cool. So we have a little bit of time left. So let's jump to talking about Swift UI so we can put our GraphQL API into use in an iOS app. Swift UI is, like we said earlier is, Apple's UI framework for building iOS, Mac OS and tvOS applications. I say one of Apple's UI frameworks, there's UI kit, which is an older option to actually use when Objective-C was the common language, Objective-C and UI kit are still around, that was when I was a mobile developer, and that was what I was using, although I did do a little bit with Swift, when it first came out, I was working as an iOS developer for a company that made mobile apps for the real estate industry, so something that allowed you to search for property listings, and then we would brand those for a real estate agent.

So here's, if you follow these steps in Xcode, which you don't need to, we're gonna fetch an Xcode project that has kind of a skeleton, for what we want to work with initially, but if you follow these steps in Xcode to create a new SwiftUI project, you'll end up with something like this, this is the basic starting point, and so SwiftUI gives you this content view struct, which allows you to then use what are called view modifiers and other views. So SwiftUI basically allows you to compose multiple views and use view modifiers to style those views. So what does that mean? Well, here in our body variable, we're using a text view passing in hello world to render in the text view and this dot padding, that's a view modifier to tweak the text view and then the text view is part of our overall content view. So we have just one view object here, we could have multiple, this is just the default that we start with. And so the view modifiers are declarative way, it's sort of saying, this is how I want to style this and then Xcode figures out how to combine the styling for multiple views to render our overall app. That's the basic idea of SwiftUI.

So, if you're following along in Xcode, there's this GitHub project, which I will drop in the chat. If you don't have Xcode up and running, that's fine, I'll go through this. You can just kind of watch as we go through it. But if you have Xcode up and running, you can download that Xcode project from GitHub and open it up. And that has the code for basic skeleton for our app. We're gonna tweak a couple of things to add some GraphQL functionality. So, I guess a few things from the screenshot, one is that on the right we can see the preview of our app running inside Xcode, which doesn't seem like that big a deal. But if you've been a mobile developer having to build your app and use a simulator to see any changes, having that preview that updates in real time as you're making changes to your SwiftUI code, is nice. So let's talk about how we can do GraphQL data fetching in an iOS app with SwiftUI. So we're gonna use the Apollo iOS library. This is written in Swift by Apollo. If you're not familiar with Apollo, Apollo makes tooling for GraphQL both on the client and the server. So we were using Apollo Server just a minute ago. That's maintained by Apollo. They also make client tooling. I think the most popular version of Apollo Client is the React Client for building React applications. But they've also released and maintain Apollo iOS which is a Swift GraphQL client. So the main functionality in Apollo iOS, there's a few interesting things going on.

23. Caching, Code Generation, and Other Clients

Short description:

Caching and code generation are important functions in Apollo iOS. In addition to Apollo iOS, there are other Swift iOS clients like Swift GraphQL. Apollo Kotlin is available for Android, and there's also an Apollo client for React Native.

One is caching. So caching is an important function for a lot of GraphQL clients. We don't want to make lots of unnecessary requests to the server. So we can use in-memory caching or on iOS and it's also true, I think for the Apollo Kotlin which is the Android clients using SQLites which is an embedded on-device database for caching so that data can stick around between app restarts which is quite nice. The other big piece of functionality in Apollo iOS is code generation. So Swift is strongly typed, GraphQL is strongly typed so we can take advantage of the typing in both of those languages to generate code and what kind of code are we generating. Well, a couple of things. One is we're generating model code for our models and then the other thing is generating API code for executing our GraphQL queries and we'll see what those look like in a minute. There are some other Swift iOS clients out there. There's one maintained by the Guild, which I think is just called Swift GraphQL, something like that. So there are a few different options. I'm not too familiar with that one. I can't speak to what the differences are between that and Apollo iOS. There are also clients for Android. That's the Apollo Kotlin. And then also for React Native. For React Native, there's an Apollo client for React Native as well.

24. Using Apollo iOS in a Swift UI Project

Short description:

Here are the steps to follow for using Apollo iOS in a Swift UI project: add the Apollo iOS package using Swift Package Manager, download the GraphQL schema to enable code generation, define the operations (queries, mutations, subscriptions) in your Xcode project, generate Swift API and model code using the schema and operations, create a network class to interact with the GraphQL API, use the model-view-viewmodel (MVVM) pattern in SwiftUI, and declare the view model as a state object for data binding. This allows for dynamic rendering of views based on changes to the view model.

So these are kind of the steps that we go through for using Apollo iOS in a Swift UI project. And I guess I should say it doesn't have to be in a Swift UI project. We can use UI kit and Swift with Apollo iOS. And I think, can you use, I know we can bridge Objective-C and Swift. So I think we can even use Objective-C to interact with Apollo iOS through kind of a Swift bridge, although I haven't looked at that recently, but these are the basic steps.

So we need to add the Apollo iOS package, depending on which package management we're using. So, with package manager, I think is now becoming kind of the default, but CocoaPods is still around and there's another one, the name of which is escaping my mind that we can also use, but we're gonna use Swift package manager today. And then we need to download the GraphQL schema, and this is a JSON representation of the schema that we download into our Xcode project. And the reason we do that is to enable code generation. So, for the code generation to work, we need to know what is the GraphQL schema that we're working with. Then we need to define any operations that we wanna use in our app. So, any queries, mutations, subscriptions, we need to go ahead and write those and have those available in our Xcode project. Then, we can go through the code generation step, which is gonna use our downloaded GraphQL schema and the GraphQL queries, the operations and the mutations as well that we wrote and included our Xcode project to generate a Swift API code and Swift model code for use in our Swift code. And then, we can work with that data and we'll see how we can use Swift UI specifically to work with that GraphQL data. So, those are the basic steps. I'll show those sort of in a screenshot. These are set up already in that Xcode project that is available on GitHub. So, this is how we use Swift Package Manager to add a dependency for Apollo iOS. There are a few different packages depending on what we're trying to do. One of these I think is supporting subscriptions. We just need the Apollo package. Cool, so I'll show up in Swift Package Manager as a dependency. Then the next thing we need to do is set up a build phase script to do two things. One is to download the GraphQL schema. And then once we've downloaded the GraphQL schema, we want to add a step in the build phase script to go through the code generation. When we add Apollo iOS as a dependency, we also bring in some command line tools that will enable downloading the schema and going through that code generation step. So this is a script that I just copied from the Apollo documentation and added that. So here we've created in the build phases script in Xcode. I've created a new build phase script. So this is going to run any time we build our project called Apollo GraphQL. And we can see what the script is doing. Here, I'm starting on line 26 is using the bundled command line tool to download a schema from some end point. And I've pointed at the news graph end point. We're gonna change this to point to our code sandbox GraphQL end point. So that will download a JSON version of our schema in this schema.json. And then this next line, line 28, this is triggering the code generation to look at any.GraphQL files. So those are gonna be the operations that we've written. So any queries or mutations that we've written in our Xcode project that we wanna use in our app, it's going to use those and then also our schema.JSON or GraphQL schema file to generate api.swift. So that's the generated API code that the Apollo iOS is going to co-generate for us. Here's what the schema.json file looks like. This is just a JSON representation of our schema. This is a result of running the introspection query. And then here's the GraphQL query that we wrote. So we're gonna just search for the most recent articles. So giving the 30 most recent articles ordered by published date and the associated information for those. And then here is the generated api.swift file. And so this, we don't wanna tweak. This is generated by that build phase script. And you can see basically it embeds the query that picked up from any.graphql files. So any of the crazy mutations, we just want to make sure that we're saving those as.graphql files in our Xcode project. And this has the logic for interacting with our GraphQL API. So then we just need to create a network class that in this case is going to create an instance of Apollo Client and the URL for our GraphQL API. Then we have a few options for depending on kind of what paradigm we're following. We have the common framework, common way to build apps with SwiftUI is to use model of view, ViewModel, where we have a model class or struct that defines the data that we're working with. We have a view that defines in SwiftUI how to construct the view given some model data and a ViewModel is basically where we are interacting with the GraphQL API. We may need to modify some of the data that comes back depending on how we want to think of our models. What we're doing here in our ViewModel, we've created an articles ViewModel that we're saying is observable objects. And also, we've added this Publish directive here on our articles, which are an array of articles. And we define a fetch function, which is using our shared network class and Apollo Client to execute the most recent articles query. This is from our generated API that picked up our most recent articles GraphQL query that we wrote. So what's going on here? Well, the observable object and this published directive, this is kind of similar if you're familiar with React to the way that data binding in React works with state variables. So you can think of our view model as kind of a state object. And indeed and our Swift UI code over here, which we'll look at in a minute, we are declaring that our article view model instance is a state object. And so when that object changes, we need to rerender our view, taking into account how that data has changed. So this is a really powerful feature of Swift UI. We can then use that in our view to show the result of that graph QL data fetching code. Let's go ahead and open up Xcode and look at that. So if you downloaded the project on GitHub, and open that up, you'll see, zoom in a bit here, you'll see exactly the code that we walked through. So we already saw what the schema.JSON looked like. Here's our articles.graphQL, the most recent articles, graph QL query.

25. Building a Newsreader iOS App with Apollo iOS

Short description:

We looked at the content view and the Swift UI code. The content view is composed of other views, including a scroll view. We iterate over each article in the articles view model and create an article view card for each article. The article card view struct combines text views and a divider view. We also define a preview provider for testing purposes. We use the Apollo iOS library to handle GraphQL data fetching and the Neo4j GraphQL library for the GraphQL API. We looked at building a GraphQL server in JavaScript using the Neo4j GraphQL library. We also explored SwiftUI and the Apollo iOS clients for building native iOS apps with GraphQL. We covered a lot of ground and hope you enjoyed the conference. If you have any questions, feel free to reach out on Twitter or visit my blog. Regarding GraphQL bindings for OraDB, GraphQL is not a database query language, so it's not directly integrated with the database. Some attempts have been made, but they haven't been successful.

And we saw here creating an instance of our API view model. Let's look at the content view. So this is our Swift UI code, and we're not going too crazy here. This is using a scroll view. So we say that our content view, which is the overall app, is composed of other views. And in this case, we have a scroll view, then we're iterating over each article that we've found in the articles view model. And because articles view model is an environment object, like a state variable is a way to think of that, as the articles view model changes, we will re-render pieces of our views. So when the app initially launches, there's no data, the article view, view model changes as data comes back from our graph QL query that triggers a re-render for iterating over each article. And then for each article, we create an article view card, which is another view that we've defined down here. And this is just a simple view for rendering this piece. So for each article, each article is a article card view struct, and that takes a title and abstract and then combines a couple of text views. We can see the view modifiers that we use here, zoom in a little bit more. The view modifiers that we use here to do things like set the font for the title. We have the abstract text and we have a simple divider. So our scroll view is composed of, so a bunch of these article card view structs, which is a view that we defined here that's composed of two text views and a divider view, taking in data from our articles view model. We also want to define a preview provider. So when we're working with data, we can either use the same environment object that we're using in our app, so this will actually fetch data and use the fetch data. Or if we want to, we can just mock some data so we don't have to think about handling like network requests, maybe we don't want to test that piece of our app. We could create a content view here in the preview that just has maybe some hard coded data or something like that. And that's how we get data in the preview mode in our app which is quite nice. And we can see, so that changes as we are making changes here. Let's see what this looks like. So let's set maybe medium or something. We can make changes and see how that changes live without updating our, without building and running simulator. Let's go ahead and build our app in simulator. See what this looks like. So here's simulator on a iPhone 14 Pro, and here is, here's our app with the most recent articles. So we're using the Apollo iOS library to handle our GraphQL data fetching. Requiring a GraphQL API that we've built using the Neo4j GraphQL library on top of the Neo4j Or instance, where we using data from the New York Times API to show the most popular articles in a newsreader app. Which is pretty cool. That was a look at Apollo iOS. We have an exercise here, which is to do a couple of things. One is we want to change the GraphQL API that we're using instead of, let's in our network layer, this is a sort of the default one that was up and running. We want to change this to the GraphQL API that we built with code sandbox. And then we want to see how to incorporate some personalization features. How can we update that GraphQL query to show maybe local news or just some personalization. But it seemed like there were some issues with code sandbox and it's just a few minutes before the end of time on a Friday. So maybe we'll just leave that for an exercise for folks to do at home. So that's pretty much all that I had for us today. Here's a link to the resources from today. I'll drop a link to this in the chat if I can copy it. Copy link, there we go. So everything is linked in the slides which are available here. So that's probably the best place to go. If you have questions or comments or anything, let us know in the chat. But I think since we're so close to the end of time anyway that we will we will call it a day there. Just to reiterate a little bit again on what we did is we looked at near for j in the property graph model, we looked at the cipher query language. So how do we query data as a graph in a graph database using cipher and some of the graph pattern matching functionality there. We looked at GraphQL. We sort of compared and contrasted GraphQL and cipher try to think about when we wanna use one versus the other when it makes sense to use cipher in the database when it makes sense to use GraphQL with APIs. We took a look at the nearest GraphQL library which allows us to build GraphQL API is backed by Neo4j. We took a look at the Neo4j GraphQL toolbox sort of a low code way of building and testing GraphQL APIs. We also looked at building a GraphQL server in JavaScript. So no JS GraphQL server using the Neo4j GraphQL library. And then we took a look at SwiftUI and the Apollo iOS clients for building native iOS apps with GraphQL. So we covered quite a bit. Hopefully that wasn't too much of a whirlwind. And I don't see any more questions in the chat. So I guess we will call it a day. If you're interested in learning more things about GraphQL or Neo4j the best way to get ahold of me is probably on Twitter. My Twitter handle is here. I also publish a blog at lionwj.com. It's my personal site as well, where you can find me. Cool, so I hope everyone enjoyed the GraphQL Galaxy conference. I think today is the panels, the talks were yesterday I think. So a question from Anthony. Will GraphQL bindings be added to OraDB and what will they look like? Yeah, so that's a good question. I think, like we discovered like GraphQL is not a database query language. So we're not interacting directly with the database with GraphQL. A few database folks have tried that I think it didn't quite work out well.

26. Managed GraphQL Service and the Future

Short description:

GraphQL as a service, managed by Neo4j and integrated with Aura, could be the next evolution. It would provide a layer of abstraction for developers using type definitions to configure the API. The client would only need to know the GraphQL endpoint. This is not currently available, but it is something that Neo4j is considering. The Neo4j GraphQL Library offers features for building the API layer, but there are still management aspects that developers have to handle. Moving these common boilerplate tasks to a managed GraphQL service in the cloud makes sense. Cypher and GraphQL have different use cases, with Cypher being more suitable for direct database querying and GraphQL for building general-purpose APIs. GraphQL also offers features like authorization that are not available in a database query language. Understanding how Cypher and GraphQL fit into different parts of the application architecture is important. Thank you for joining the GraphQL Galaxy conference!

I think GraphQL was designed to be an API query language. And so we want to use it to build that API layer that sits between the client and the database. Having said that, of course, like the New York State GraphQL library, the whole point is to make it easier to build GraphQL APIs backed by a database. So there's definitely space for these GraphQL database integrations.

Now, when we move to cloud services, I guess the question is what does that look like? So that would be something more like a managed GraphQL service backed by Neo4j Aura I think is what that would look like. And actually the GraphQL team is looking into that and they are taking feedback. So if you notice on toolbox, there's a link here at the top. It says wants to manage your new to GraphQL API or register entrance here, and it's a Google form that's basically this form basically asking for feedback about a potential GraphQL API managed service that would integrate with Aura. So anyway, so it's a long answer to your question, Anthony. If GraphQL bindings are gonna be added to aura, I think the answer is that would look something like a, I'm thinking like GraphQL as a service, GraphQL managed service, where you have some interface, more similar to toolbox where you're configuring an API and that API is then deployed somewhere managed by Neo4j combined with aura. So something like that, you can also see maybe GraphQL toolbox integrated with the workspace flow in Aura with the other developer tools that might be something that makes a lot of sense. So there was a lot of interesting possibilities there for sure.

It's kind of things that, what definitions we save to the server then what? Yeah, so it would be basically with toolbox, you have type definitions and query editor and this is all in your browser, the next step would be something like deploy this API. And what we did here is we sort of took the API type definitions and then we went to code sandbox and that was managing a GraphQL server application for us. But in sort of the cloud world, rather than like building our own node JS server that we have to manage, how could we sort of think of integrating that into a cloud service where the just like serverless doesn't mean that there isn't an actual server, it's just that you're as a developer, your sort of layer of abstraction is no longer a server. So taking that concept where the layer of abstraction for the developer is your type definitions. So we saw how we can use these type definitions and specifically directives to configure the generative API. So a managed GraphQL service, I think would look something like that where your layer of abstraction is the type definitions and that's how we're configuring as a developer the API. And then there's some cloud service integrated with Aura behind the scenes as a developer, we don't have to think about, that's deploying and managing a GraphQL endpoints for us. I think that's sort of the shape that a managed GraphQL integration with Aura might look like. And then Anthony says, the client would be different because it doesn't know about the schema, just endpoint. Yeah, so then for the GraphQL clients, it sort of doesn't matter where that GraphQL service is hosted, right? It's just a GraphQL endpoints and through the powers of things like introspection and all the other developer tooling that we have with GraphQL, we can build apps that take advantage of that. And again, yeah, I mean, this is not something that exists today, something though that I think folks at Neo4j are thinking about, I think it makes sense sort of the next evolution that if you think about it, the Neo4j GraphQL Library, which this is one of the pages that we've linked that has a lot of overviews here, talks about, all about the features for building this API layer, but there's still a lot that you kind of have to manage and think about as a user that maybe necessarily don't add a lot of specific value, right? Like we have to manage, what is essentially an Express, Node.js app and deploy that somewhere and scale that horizontally with multiple instances. And like, that's not really something that developers are able to add competitive advantage around anymore, right? Because we have things like Lambda functions that we can just sort of use to deploy these apps. And so I think it's largely thinking about what are some of the common boilerplate things that developers are doing that don't add a lot of competitive advantage to their app, what are some of those features we can move into the move into Cloud services. And so, yeah, so again, like thinking of Cypher versus GraphQL, like Cypher, you know, has its use cases for interacting directly with the database. And when we're building those kinds of applications that we want to have that sort of logic querying the database directly with the power of Cypher, that's sort of the time and place for it. But when we're building the more sort of general purpose API that's sitting between client and the database, GraphQL is a great option for that. Again, GraphQLs, typically not something we want to think about as interacting directly with the database, we want that API layer. And there's all kinds of features too that we didn't talk about today, like authorization. I think there's some examples on this page where we can add authorization rules to specify like only users who created an order should be able to edit it, like these sorts of things, this sort of functionality you don't necessarily have in a database query language, these are like application level authorization functionality. So yeah, understanding, like how Cypher and how GraphQL fit into different pieces of your application architecture. Hopefully we touched on some of that today. Well, cool, thanks a lot. I hope everyone has a great weekend and thanks for joining and thanks for hanging out at GraphQL Galaxy. We will see you next time.

Watch more workshops on topic

GraphQL Galaxy 2021GraphQL Galaxy 2021
140 min
Build with SvelteKit and GraphQL
Top Content
Featured WorkshopFree
Have you ever thought about building something that doesn't require a lot of boilerplate with a tiny bundle size? In this workshop, Scott Spence will go from hello world to covering routing and using endpoints in SvelteKit. You'll set up a backend GraphQL API then use GraphQL queries with SvelteKit to display the GraphQL API data. You'll build a fast secure project that uses SvelteKit's features, then deploy it as a fully static site. This course is for the Svelte curious who haven't had extensive experience with SvelteKit and want a deeper understanding of how to use it in practical applications.

Table of contents:
- Kick-off and Svelte introduction
- Initialise frontend project
- Tour of the SvelteKit skeleton project
- Configure backend project
- Query Data with GraphQL
- Fetching data to the frontend with GraphQL
- Styling
- Svelte directives
- Routing in SvelteKit
- Endpoints in SvelteKit
- Deploying to Netlify
- Navigation
- Mutations in GraphCMS
- Sending GraphQL Mutations via SvelteKit
- Q&A
React Advanced Conference 2022React Advanced Conference 2022
95 min
End-To-End Type Safety with React, GraphQL & Prisma
Featured WorkshopFree
In this workshop, you will get a first-hand look at what end-to-end type safety is and why it is important. To accomplish this, you’ll be building a GraphQL API using modern, relevant tools which will be consumed by a React client.
Prerequisites: - Node.js installed on your machine (12.2.X / 14.X)- It is recommended (but not required) to use VS Code for the practical tasks- An IDE installed (VSCode recommended)- (Good to have)*A basic understanding of Node.js, React, and TypeScript
GraphQL Galaxy 2022GraphQL Galaxy 2022
112 min
GraphQL for React Developers
Featured Workshop
There are many advantages to using GraphQL as a datasource for frontend development, compared to REST APIs. We developers in example need to write a lot of imperative code to retrieve data to display in our applications and handle state. With GraphQL you cannot only decrease the amount of code needed around data fetching and state-management you'll also get increased flexibility, better performance and most of all an improved developer experience. In this workshop you'll learn how GraphQL can improve your work as a frontend developer and how to handle GraphQL in your frontend React application.
React Summit 2022React Summit 2022
173 min
Build a Headless WordPress App with Next.js and WPGraphQL
Top Content
WorkshopFree
In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.
GraphQL Galaxy 2020GraphQL Galaxy 2020
106 min
Relational Database Modeling for GraphQL
Top Content
WorkshopFree
In this workshop we'll dig deeper into data modeling. We'll start with a discussion about various database types and how they map to GraphQL. Once that groundwork is laid out, the focus will shift to specific types of databases and how to build data models that work best for GraphQL within various scenarios.
Table of contentsPart 1 - Hour 1      a. Relational Database Data Modeling      b. Comparing Relational and NoSQL Databases      c. GraphQL with the Database in mindPart 2 - Hour 2      a. Designing Relational Data Models      b. Relationship, Building MultijoinsTables      c. GraphQL & Relational Data Modeling Query Complexities
Prerequisites      a. Data modeling tool. The trainer will be using dbdiagram      b. Postgres, albeit no need to install this locally, as I'll be using a Postgres Dicker image, from Docker Hub for all examples      c. Hasura
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
The Graph is an indexing protocol for querying networks like Ethereum, IPFS, and other blockchains. Anyone can build and publish open APIs, called subgraphs, making data easily accessible.

In this workshop you’ll learn how to build a subgraph that indexes NFT blockchain data from the Foundation smart contract. We’ll deploy the API, and learn how to perform queries to retrieve data using various types of data access patterns, implementing filters and sorting.

By the end of the workshop, you should understand how to build and deploy performant APIs to The Graph to index data from any smart contract deployed to Ethereum.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
From GraphQL Zero to GraphQL Hero with RedwoodJS
Top Content
We all love GraphQL, but it can be daunting to get a server up and running and keep your code organized, maintainable, and testable over the long term. No more! Come watch as I go from an empty directory to a fully fledged GraphQL API in minutes flat. Plus, see how easy it is to use and create directives to clean up your code even more. You're gonna love GraphQL even more once you make things Redwood Easy!
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
How many times did you implement the same flow in your application: check, if data is already fetched from the server, if yes - render the data, if not - fetch this data and then render it? I think I've done it more than ten times myself and I've seen the question about this flow more than fifty times. Unfortunately, our go-to state management library, Vuex, doesn't provide any solution for this.For GraphQL-based application, there was an alternative to use Apollo client that provided tools for working with the cache. But what if you use REST? Luckily, now we have a Vue alternative to a react-query library that provides a nice solution for working with server cache. In this talk, I will explain the distinction between local application state and local server cache and do some live coding to show how to work with the latter.
GraphQL Galaxy 2022GraphQL Galaxy 2022
16 min
Step aside resolvers: a new approach to GraphQL execution
Though GraphQL is declarative, resolvers operate field-by-field, layer-by-layer, often resulting in unnecessary work for your business logic even when using techniques such as DataLoader. In this talk, Benjie will introduce his vision for a new general-purpose GraphQL execution strategy whose holistic approach could lead to significant efficiency and scalability gains for all GraphQL APIs.