1548039441
GraphQL is a way to send data over HTTP and is often presented as a revolutionary new way to think about APIs and seen as the successor of REST (Representational State Transfer). Indeed GraphQL is able to overcome major shortcomings of REST.
GraphQL can be user in any application, web application or mobile app. In this tutorial you’ll learn how to use GraphQL in a React web application. To make use of GraphQL inside your React project we’ll be using the React Apollo library.
Many consider GraphQL as a replacement for REST which is quite inaccurate.
REST (Representational State Transfer) is an API design architecture used on network-based software to transfer the data.
It has many limitations. It could require multiple round trips to fetch related resources. Another common problem is under-fetching ( not getting everything in one go), or over-fetching ( getting more than what is needed in one go.
1. Multiple http calls to the API servers:
Eg: Consider a micro-blogging platform for example. When you have to display a user’s detail on left pane, his/her posts in middle and below them the comments, you have to hit the server thrice (at least):
2. Way more data transfer than required:
In example above, we just had to display user’s name, handle and profile pic, but the user API gives way more data (email, phone-number, date-of-birth, etc) out of which we use only the required ones. More data transfer over network means:
3. API versioning and maintenance:
In the user API, if we have to give out some new field and deprecate few old ones, we’ll have to do API versioning (keep the old version to support old clients and create a new version for new clients). In long run maintaining different versions for same resource becomes a nightmare. You have to announce when will you be deprecating old versions or force your users to update to the latest version, etc.
GraphQL solves all the 3 and also provide few more things that REST doesn’t:
1. Multiple http calls to the API servers:
With graphQL you can get all the resources in one single http call, just the way you do in server side by using joins and getting all the data in one SQL.
{user(id: 10) {
id
name
handle
profilePicUrl
post(last: 5) {
heading
postUrl
comment(last: 2) {
description
commentBy
}
}
}
}
Above is an example of a GQL for displaying last 5 posts with recent 2 comments of a user with id 10. As you can see we got all the 3 resources in a single http call.
2. Way more data transfer than required:
In the example above, we can add/remove the fields we want. Thus the data transfer over network is controlled by client and not by server, saving both processing and network time.
3. API versioning and maintenance:
The query part is done by client, so client can add and remove the data it wants as long as it is present on server side without changing API version.
I have tried GraphQL in Java-Universe (with spring-boot, spring-jpa, jersey, gradle, etc) and found out to be one of the best technology out there. Here’s the ready-to-deploy code that you can try: thekosmix/GraphQL-SpringBoot
Let’s dig into the topic of the post, which is getting started with graphQL in React. Although we went through a basic introduction of graphQL, this tutorial assumes that you are already familiar with React and implementing a simple React app. Now we will take a look at how to use graphQL in react.
To get started we first need to setup a new React project. The easiest way to do so is to use create-react-app. This script creates a new React project with zero build configuration. The project’s website can be found at https://github.com/facebook/create-react-app.
To make use of create-react-app you simply need to make sure that Node.js is installed on your system. There is no need to install create-react-app before using it. Instead the Node.js npx command can be used in the following way:
$ npx create-react-app Hello-graphql
$ cd Hello-graphql
$ npm start
This is initiating a new basic React project in the newly created project folder react-graphql. By using the npm start command the live-reloading development web server is started and the output of the default React project can be accessed in the browser:
We’ll also need a few extra packages in our project, namely graphql, graphql-tag, apollo-boost and react-apollo. Add them using npm or Yarn:
$ yarn add graphql graphql-tag apollo-boost react-apolloor, using npm:
$ npm i graphql graphql-tag apollo-boost react-apollo
With our project in place and packages added, we can now setup the Apollo client.
The client setup couldn’t be easier. We’ll initiate a client and give it the URI to our GraphQL server endpoint and then use the ApolloProvider component to to make the client available in our app’s components.
For this example our endpoint will point to an Apollo Launchpad instance with data about Star Wars:
index.js
import React from ‘react’;
import ReactDOM from ‘react-dom’;import { ApolloProvider } from ‘react-apollo’;
import { ApolloClient, HttpLink, InMemoryCache } from ‘apollo-boost’;import ‘./index.css’;
import App from ‘./App’;const client = new ApolloClient({
link: new HttpLink({ uri: ‘https://mpjk0plp9.lp.gql.zone/graphql’ }),
cache: new InMemoryCache()
});const AppWithProvider = () => (
<ApolloProvider client={client}>
<App />
</ApolloProvider>
);ReactDOM.render(<AppWithProvider />, document.getElementById(‘root’));
A few things to note:
Now that everything’s in place, we can start running queries against the GraphQL endpoint. For this, we’ll use React Apollo’s Query component, which makes use of the render prop pattern to give us the data back from the query.
Here’s an example where we query for a Star Wars’ episode hero and his/her friends:
App.js
import React from ‘react’;
import PropTypes from ‘prop-types’;import { Query } from ‘react-apollo’;
import gql from ‘graphql-tag’;const QUERY = gql
query HeroFriends($episode: Episode!) { hero(episode: $episode) { name friends { name } } }
;const HeroAndFriends = ({ episode }) => (
<Query query={QUERY} variables={{ episode }}>
{({ data, error, loading }) => {
if (error) return ’ Oops!';
if (loading) return ‘Patience young grasshopper…’;return ( <React.Fragment> <h1>Hero: {data.hero.name}</h1> <h2>His/her friends: </h2> <ul> {data.hero.friends.map(friend => ( <li key={friend.name}>{friend.name}</li> ))} </ul> </React.Fragment> );
}}
</Query>
);
HeroAndFriends.propTypes = { episode: PropTypes.string };
HeroAndFriends.defaultProps = { episode: ‘NEWHOPE’ };const App = () => <HeroAndFriends episode=“EMPIRE” />;
export default App;
And let’s breakdown the important things happening here:
#graphql #database #sql
1595808240
In the first quarter of 2020, I had the experience of being in a short term advisory role for a company that had built a type of Linkedin product for a specific vertical market. They had done a valiant job, but it was clear that scalability was a problem and they had created a problem for themselves by having used MongoDB as the datastore.
The client knew this and wanted to do a rebuild using the neo4j, but despite its popularity, I am not a big fan of it as an implementation of a graph database for a variety of reasons, one of which is that it is written in Java. This led me to hunt around for alternatives which ultimately led me to Dgraph, which I initially liked because it was written in golang but I was won over by just how well the system is built and thought out.
In the process of thinking about Dgraph, they released a private beta for their managed GraphQL backend service called Slash GraphQL. This really caught my attention as it allowed me to just dive in and try out some ideas without having to deal with learning how to install the system. So with that as some preview, I went ahead and signed up for the private beta, I was immediately accepted, I don’t know if there is any real threshold to get access other than they want your information, but a small price to pay.
Let’s cover a bit of the ecosystem before we dive in. While GraphQL has become something of a standard for working with Graph databases, that isn’t what it was developed to do, so Dgraph set out to make something that was more specifically suited by modifying GraphQL into GraphQL± and I assume the ± in the name is in reference to the fact that they added and removed features from it.
When working with Dgraph you can use either GraphQL or GraphQL±, but keep in mind that those languages are really targeted to backend developers and this new Slash GraphQL environment is targeted at full-stack developers.
So with all that said, let’s get into it when we first login we see the following screen:
The quickstart video is definitely worth a few minutes to get a sense of what is going on, in addition, you should read the in-process, quick start guide for Slash GraphQL.
The quick start guide has some specific examples and a working ToDo app at the end that you can check out, but I wanted to build something from scratch. I gave it a lot of thought as to various clever things I could do, but ultimately I decided to use the example in the quick start to provide consistency. If you are familiar with GraphQL, then the syntax is easy.
If you aren’t, but know how to code and know JSON, then it’s not too hard to figure out. This is probably a good time to note some distinguishing characteristics of Dgraph.
Dgraph doesn’t not run on top of another DBMS, it manages data in a way the is optimized for how GraphQL stores and retrieves data. That means you don’t have to deal with creating the schema for the underlying DBMS and then doing it in GraphQL and try to keep them in sync whenever you need to make a change. That means that Slash GraphQL empowers you to only deal with GraphQL schemes without knowing anything about the database.
With that said, let’s create our schema:
#graphql #lowcode #nocode #pros-of-graphql #tutorial-for-beginners #tutorial #learn-to-code #design
1622105190
One of the fastest ways to get up and running with GraphQL is to install Apollo Server as middleware on your new or existing HTTP server.
In this short post, we demonstrate how to use Apollo Server to create a GraphQL server with Express.js using the [apollo-server-express] package. At the end, we’ll discuss the tradeoffs of this approach.
#graphql #javascript #graphql.js #graphql.js tutorial
1596728880
In this tutorial we’ll learn how to begin programming with R using RStudio. We’ll install R, and RStudio RStudio, an extremely popular development environment for R. We’ll learn the key RStudio features in order to start programming in R on our own.
If you already know how to use RStudio and want to learn some tips, tricks, and shortcuts, check out this Dataquest blog post.
[tidyverse](https://www.dataquest.io/blog/tutorial-getting-started-with-r-and-rstudio/#tve-jump-173bb26184b)
Packages[tidyverse](https://www.dataquest.io/blog/tutorial-getting-started-with-r-and-rstudio/#tve-jump-173bb264c2b)
Packages into Memory#data science tutorials #beginner #r tutorial #r tutorials #rstats #tutorial #tutorials
1596513720
What exactly is clean data? Clean data is accurate, complete, and in a format that is ready to analyze. Characteristics of clean data include data that are:
Common symptoms of messy data include data that contain:
In this blog post, we will work with five property-sales datasets that are publicly available on the New York City Department of Finance Rolling Sales Data website. We encourage you to download the datasets and follow along! Each file contains one year of real estate sales data for one of New York City’s five boroughs. We will work with the following Microsoft Excel files:
As we work through this blog post, imagine that you are helping a friend launch their home-inspection business in New York City. You offer to help them by analyzing the data to better understand the real-estate market. But you realize that before you can analyze the data in R, you will need to diagnose and clean it first. And before you can diagnose the data, you will need to load it into R!
Benefits of using tidyverse tools are often evident in the data-loading process. In many cases, the tidyverse package readxl
will clean some data for you as Microsoft Excel data is loaded into R. If you are working with CSV data, the tidyverse readr
package function read_csv()
is the function to use (we’ll cover that later).
Let’s look at an example. Here’s how the Excel file for the Brooklyn borough looks:
The Brooklyn Excel file
Now let’s load the Brooklyn dataset into R from an Excel file. We’ll use the readxl
package. We specify the function argument skip = 4
because the row that we want to use as the header (i.e. column names) is actually row 5. We can ignore the first four rows entirely and load the data into R beginning at row 5. Here’s the code:
library(readxl) # Load Excel files
brooklyn <- read_excel("rollingsales_brooklyn.xls", skip = 4)
Note we saved this dataset with the variable name brooklyn
for future use.
The tidyverse offers a user-friendly way to view this data with the glimpse()
function that is part of the tibble
package. To use this package, we will need to load it for use in our current session. But rather than loading this package alone, we can load many of the tidyverse packages at one time. If you do not have the tidyverse collection of packages, install it on your machine using the following command in your R or R Studio session:
install.packages("tidyverse")
Once the package is installed, load it to memory:
library(tidyverse)
Now that tidyverse
is loaded into memory, take a “glimpse” of the Brooklyn dataset:
glimpse(brooklyn)
## Observations: 20,185
## Variables: 21
## $ BOROUGH <chr> "3", "3", "3", "3", "3", "3", "…
## $ NEIGHBORHOOD <chr> "BATH BEACH", "BATH BEACH", "BA…
## $ `BUILDING CLASS CATEGORY` <chr> "01 ONE FAMILY DWELLINGS", "01 …
## $ `TAX CLASS AT PRESENT` <chr> "1", "1", "1", "1", "1", "1", "…
## $ BLOCK <dbl> 6359, 6360, 6364, 6367, 6371, 6…
## $ LOT <dbl> 70, 48, 74, 24, 19, 32, 65, 20,…
## $ `EASE-MENT` <lgl> NA, NA, NA, NA, NA, NA, NA, NA,…
## $ `BUILDING CLASS AT PRESENT` <chr> "S1", "A5", "A5", "A9", "A9", "…
## $ ADDRESS <chr> "8684 15TH AVENUE", "14 BAY 10T…
## $ `APARTMENT NUMBER` <chr> NA, NA, NA, NA, NA, NA, NA, NA,…
## $ `ZIP CODE` <dbl> 11228, 11228, 11214, 11214, 112…
## $ `RESIDENTIAL UNITS` <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1…
## $ `COMMERCIAL UNITS` <dbl> 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
## $ `TOTAL UNITS` <dbl> 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1…
## $ `LAND SQUARE FEET` <dbl> 1933, 2513, 2492, 1571, 2320, 3…
## $ `GROSS SQUARE FEET` <dbl> 4080, 1428, 972, 1456, 1566, 22…
## $ `YEAR BUILT` <dbl> 1930, 1930, 1950, 1935, 1930, 1…
## $ `TAX CLASS AT TIME OF SALE` <chr> "1", "1", "1", "1", "1", "1", "…
## $ `BUILDING CLASS AT TIME OF SALE` <chr> "S1", "A5", "A5", "A9", "A9", "…
## $ `SALE PRICE` <dbl> 1300000, 849000, 0, 830000, 0, …
## $ `SALE DATE` <dttm> 2020-04-28, 2020-03-18, 2019-0…
The glimpse()
function provides a user-friendly way to view the column names and data types for all columns, or variables, in the data frame. With this function, we are also able to view the first few observations in the data frame. This data frame has 20,185 observations, or property sales records. And there are 21 variables, or columns.
#data science tutorials #beginner #r #r tutorial #r tutorials #rstats #tidyverse #tutorial #tutorials
1599097440
A famous general is thought to have said, “A good sketch is better than a long speech.” That advice may have come from the battlefield, but it’s applicable in lots of other areas — including data science. “Sketching” out our data by visualizing it using ggplot2 in R is more impactful than simply describing the trends we find.
This is why we visualize data. We visualize data because it’s easier to learn from something that we can see rather than read. And thankfully for data analysts and data scientists who use R, there’s a tidyverse package called ggplot2 that makes data visualization a snap!
In this blog post, we’ll learn how to take some data and produce a visualization using R. To work through it, it’s best if you already have an understanding of R programming syntax, but you don’t need to be an expert or have any prior experience working with ggplot2
#data science tutorials #beginner #ggplot2 #r #r tutorial #r tutorials #rstats #tutorial #tutorials