How to connect your GraphQL API to your VueJS Frontend

I recently wrote about how to create an API with Hasura’s GraphQL engine. If you are not familiar with GraphQL yet, I recommend reading this post first. Now, we will build a very simple Vue app and we’ll learn how connect it to our GraphQL API.

If something is unclear during the creation of the Vue app or if you want to see the full solution, you can always view the project on Github.

Table of Contents

  • Creating a Vue project
  • Movie list component]
  • Movie detail component
  • Add movie component
  • Connecting to GraphQL API
  • Fetch actual data from GraphQL API
  • Movies list
  • Add movie
  • What now?
  • Join the community

Creating a Vue project

Let’s create a Vue project in our terminal by running:

vue create harry-potter-app

Select the default preset and open the project in your favourite editor. In order to make the appearance of our app a little prettier, we add the Milligram library. In the public index.html, add these three lines inside the <head>:

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic">

<link rel=“stylesheet” href=“//cdn.rawgit.com/necolas/normalize.css/master/normalize.css”>

<link rel=“stylesheet” href=“//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css”>

Go to your terminal, cd into your project, and run your application by typing locally:

With yarn:

yarn serve

With npm:

npm run serve

You should see Vue’s Hello World page with the Vue logo:

When we look at our Harry Potter API that we created in the previous post, we can see that we have several tables: movies, characters, actors and scenes. What we want to in our Vue app is to create components for movie. In the end, we want a component for a list of movies that consists of several components that represent a single movie. And we want to create a component that allows us to add movies.

Movie list component

Let’s get started. First, we’ll register the MoviesList component to the App.vue file. Inside the file, we need to replace the <HelloWorld/> component with <movies-list/>. Now this will fail, because we haven’t registered our new component. A little further down in the same file in the components list, let’s import our renamed component from the right location and replace the HelloWorld component with the MoviesList component. When you’re done, it should look like this:

<template>
<div id=“app”>
<img alt=“Vue logo” src=“./assets/logo.png”>
<movies-list/>
</div>
</template>

<script>
import MoviesList from “./components/MoviesList.vue”;
export default {
name: “app”,
components: {
MoviesList
}
};
</script>

Now, we need to rename the HelloWorld.vue file to MoviesList.vue. Inside the file, we’ll replace the <template>and the <script> so it looks like this:

<template>
<div>
<div v-for=“movie in movies” :key=“movie.id”>{{movie.id}}</div>
</div>
</template>

<script>
export default {
name: “MoviesList”,
data() {
return {
movies: [
{
id: “123123123”,
title: “Harry Potter and the Order of the Phoenix”,
director: “David Yates”,
composer: “Nicholas Hopper”,
release_date: “2007-07-11”
}
]
};
}
};
</script>

Let me explain what happens here. Inside the template, we add a <div> that iterates over all our movies with v-for. We have to tell Vue how to identify each movie, which we’ll do by their id. Using the double curly braces, we tell Vue what to display in the browser, which is in our case the id of the movies. Inside the <script> tag, we define what data should be displayed. For now, we display dummy data which is a movie with an ID that we defined. If you now look at the app in your browser, you’ll see the Vue logo and the id of the movie.


Movie detail component

As we said before, we also need a component to display one movie. The purpose of this being that we can later display a collection of actual MovieItems in the MoviesList, instead of using dummy data. So let’s go ahead and inside the components folder, let’s create a new file called MovieItem.vue. For each MovieItem in the MoviesList, we want to display the title, the director, the composer and the release date. So let’s go ahead and add the component to the MovieItem.vue file.

<template>
<div :key=“movie.id”>
<h3>{{ movie.title }}</h3>
<p>{{ movie.director }}</p>
<p>{{ movie.composer }}</p>
<span>{{ movie.release_date }}</span>
</div>
</template>

<script>
export default {
name: “MovieItem”,
props: [“movie”]
};
</script>

Now, we’ll have to go back to MoviesList.vue, and change it, so that we can display the actual MovieItems in our list.

<template>
<div>
<movie-item v-for=“movie in movies” :key=“movie.id” :movie=“movie”></movie-item>
</div>
</template>

<script>
import MovieItem from “./MovieItem”;
export default {
name: “MoviesList”,
components: { MovieItem },
data() {
return {
movies: [
{
id: “123123123”,
title: “Harry Potter and the Order of the Phoenix”,
director: “David Yates”,
composer: “Nicholas Hopper”,
release_date: “2007-07-11”
}
]
};
}
};
</script>

In order to do so, we need to change line 3 to use the <movie-item> component instead of a simple <div>. Also, in line 8, we need to import the MovieItem from its corresponding file. Finally, in line 11, we need to state that MovieItem is the component that is used inside the current file as an instance of a list of movies.

When you now refresh your browser, it should look like this:


Add movie component

Let’s now add the capability to add new movies to our application. In order to do so, inside the components folder, we’ll create a new file called AddMovie.vue and leave it empty for now. Now we’ll open App.vue and inside the <template>, we’ll add the <add-movie/> component before the <movies-list> component. Also, like with the MoviesList component, we need to import the component from the correct location and add the AddMoviescomponent to our components list. When you’re done, your <template> and <script> should look like this:

<template>
<div id=“app”>
<img alt=“Vue logo” src=“./assets/logo.png”>
<add-movie/>
<movies-list/>
</div>
</template>

<script>
import MoviesList from “./components/MoviesList.vue”;
import AddMovie from “./components/AddMovie.vue”;
export default {
name: “app”,
components: {
MoviesList,
AddMovie
}
};
</script>

Inside the AddMovie.vue file, we’ll add a form to create new movies. When we have a look at our API, we can see what fields the movie table has. For now, we want to be able to create a movie that has a title, a director, a composer and a release date. The file should look like this:

<template>
<form @submit=“submit”>
<fieldset>
<input type=“text” placeholder=“Title” v-model=“title”>
<input type=“text” placeholder=“Director” v-model=“director”>
<input type=“text” placeholder=“Composer” v-model=“composer”>
<input type=“text” placeholder=“Release date” v-model=“release_date”>
</fieldset>
<input class=“button-primary” type=“submit” value=“Send”>
</form>
</template>

<script>
export default {
name: “AddMovie”,
data() {
return {
title: “”,
director: “”,
composer: “”,
release_date: “”
};
}
};
</script>

It is a very simple form that allows us to enter the fields for a movie and submit. Note that we haven’t added any methods to the component yet, so nothing happens if we click the submit button.

When you refresh your browser, you should see this:

Connecting to GraphQL API

The next step is to connect our Vue app to our GraphQL API that we created in the last post, so that we can display actual data instead of dummy data. Let’s go ahead and get started.

In the previous post, we’ve seen how we can run queries in the GraphiQL tool. We can go to the Hasura console and in GraphiQL, let’s test the methods to get a list of all movies, as well as the functionality to add a new movie:

query getMovies {
movies {
id
title
director
composer
release_date
}
}

mutation addPost($title:String!, $director:String!, $composer:String!, $release_date:date!) {
insert_movies(objects:[{
title:$title,
director:$director,
composer:$composer,
release_date:$release_date
}]) {
returning {
id
}
}
}

Now, in from Vue project, we want to invoke exactly these methods. In order to do that, we will use the Apollo client. Apollo is a GraphQL platform that allows you to make queries to your API in a simplified language. Let’s install Apollo by running this command in the command line (in your project folder):

with npm:

npm install apollo-client apollo-cache-inmemory apollo-link-http graphql-tag graphql --save

with yarn:

yarn add vue-apollo graphql apollo-client apollo-link apollo-link-http apollo-cache-inmemory graphql-tag

First, we need to establish the link to our Hasura project and to instantiate Apollo. Change your main.js so it looks as follows.

import Vue from ‘vue’;
import App from ‘./App.vue’;
import { createProvider } from ‘./vue-apollo’;
import { ApolloClient } from ‘apollo-client’;
import { HttpLink } from ‘apollo-link-http’;
import { InMemoryCache } from ‘apollo-cache-inmemory’;

import VueApollo, { ApolloProvider } from ‘vue-apollo’;

Vue.config.productionTip = false;

const httpLink = new HttpLink({
uri: ‘https://graphql-harry-potter-api.herokuapp.com/v1alpha1/graphql
});

const apolloClient = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
connectToDevTools: true
});

Vue.use(VueApollo);

const apolloProvider = new VueApollo({
defaultClient: apolloClient
});

new Vue({
el: ‘#app’,
apolloProvider,
render: h => h(App)
});

Let’s go through this. First, we need to import the libraries we just installed, because we will use them in this file. Using HttpLink, we establish a connection to our GraphQL API on lines 12–14. You find your own custom link in the GraphiQL tool on your Hasura project:

Next, in lines 16–20, we create an instance of the ApolloClient. As arguments, we pass our HttpLink, so that the data gets polled from the correct API. Next, we pass our cache. InMemoryCache is the default cache implementation for ApolloClient, so we use this one. Finally, we pass the option to connect to dev tools, so that we get an Apollo tab in our chrome inspector in case we have to debug.

On line 22, we configure our Vue instance to use VueApollo.

In order to to be able to make queries and mutations from our Vue app, we need to create an instance of ApolloProvider (lines 24–26). We’ll pass it our Apollo client with which we will commit these operations.

Finally, on lines 28–32, we launch our Vue app where our Apollo provider is passed, so that we can make database queries and manipulations throughout our app.

Fetch actual data from GraphQL API

So far, we’ve been displaying dummy data in our Vue frontend. Now, we want to display actual data. In our MoviesList, we want to display the movies that are currently stored in our database. Also, we want to be able to add movies, so that they get saved in our database and displayed in our frontend.

Movies list

In order to display movies from our database, let’s change MoviesList.vue to the following:

<template>
<div>
<movie-item v-for=“movie in movies” :key=“movie.id” :movie=“movie”></movie-item>
</div>
</template>

<script>
import MovieItem from “./MovieItem”;
import gql from “graphql-tag”;
const GET_MOVIES = gql query getMovies { movies { id title director composer release_date } };
export default {
name: “MoviesList”,
components: { MovieItem },
data() {
return {
movies: []
};
},
apollo: {
movies: {
query: GET_MOVIES
}
}
};
</script>

Inside the <script> tag, we need to import GraphQL, which will allow us to make queries. On lines 11–21, we define the GraphQL query to retrieve the list of movies.

Inside the export default function, we remove the dummy data and return the list of movies that we poll from the database. We also need to tell Apollo which query should be sent to the API, and we pass the GET_MOVIES query that we defined earlier.

When we refresh the browser, we can see the whole list of movies from our database:

Yay!

Add movie

So far, when we submit our form, nothing happens. We now want to be able to add movies over our form. For this, we need some changes in our AddMovie.vue file:

<template>
<form @submit=“submit”>
<fieldset>
<input type=“text” placeholder=“Title” v-model=“title”>
<input type=“text” placeholder=“Director” v-model=“director”>
<input type=“text” placeholder=“Composer” v-model=“composer”>
<input type=“text” placeholder=“Release date” v-model=“release_date”>
</fieldset>
<input class=“button-primary” type=“submit” value=“Send”>
</form>
</template>

<script>
import gql from “graphql-tag”;
import { InMemoryCache } from “apollo-cache-inmemory”;
const ADD_MOVIE = gql mutation addMovie( $title: String! $director: String! $composer: String! $release_date: date! ) { insert_movies( objects: [ { title: $title director: $director composer: $composer release_date: $release_date } ] ) { returning { id } } };
export default {
name: “AddMovie”,
data() {
return {
title: “”,
director: “”,
composer: “”,
release_date: “”
};
},
apollo: {},
methods: {
submit(e) {
e.preventDefault();
const { title, director, composer, release_date } = this.$data;
this.$apollo.mutate({
mutation: ADD_MOVIE,
variables: {
title,
director,
composer,
release_date
},
refetchQueries: [“getMovies”]
});
}
}
};
</script>

Again, inside the <script> tag, we need to import GraphQL. Also, we need to import the InMemoryCache. We’ll see why in just a bit.

In lines 17–39, we define our mutation to add movies to our database. First, we define the parameters that are passed. Second, we pass them as an object for a movie to be inserted. And third, we state the return value of our mutation which is, in our case the id of the movie that we just created.

The most substantial change inside the export default function is reflected in lines 52–67 where define what happens when the submit button is clicked. First, we need to prevent the default behaviour of a form being submitted when clicking on the button. Then, we define the data that is passed to the mutation. Next, we call our mutation on the $apollo instance and we pass the variables for the object creation. In the end, we need to refresh the movies list, because we don’t want to reload the browser for the newly added movie to appear in the list. For this, we need our cache. Because we ran the query to list movies before, we can just refetch it from the cache.

What now?

Good job! We now created a small Vue app and connected it to our GraphQL API. This was quite easy, wasn’t it? But this is just the beginning! There are a lot more features that can be added to our app. For example updating and deleting movies. Or displaying the characters and their corresponding actors for each movie. Check out the Hasura documentation. You can find everything that you need to extend this app.


Originally published by Marion Schleifer  at medium.com

==========================================================


Learn More

☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

☞ Nuxt.js - Vue.js on Steroids

☞ Build Web Apps with Vue JS 2 & Firebase

☞ The Modern GraphQL Bootcamp (Advanced Node.js)

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ GraphQL with React: The Complete Developers Guide

☞ Build a CMS with Laravel and Vue

☞ Vuejs 2 Authentication Tutorial

☞ GraphQL Tutorial: Understanding Spring Data JPA/SpringBoot

☞ GraphQL API with AWS and Use with React

☞ Build a Simple Web App with Express, Angular, and GraphQL

#vue-js #graphql

What is GEEK

Buddha Community

How to connect your GraphQL API to your VueJS Frontend

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

Autumn  Blick

Autumn Blick

1601381326

Public ASX100 APIs: The Essential List

We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.

Method

The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:

  1. Whether the company had a public API: this was found by googling “[company name] API” and “[company name] API developer” and “[company name] developer portal”. Sometimes the company’s website was navigated or searched.
  2. Some data points about the API were noted, such as the URL of the portal/documentation and the method they used to publish the API (portal, documentation, web page).
  3. Observations were recorded that piqued the interest of the researchers (you will find these below).
  4. Other notes were made to support future research.
  5. You will find a summary of the data in the infographic below.

Data

With regards to how the APIs are shared:

#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api

Marcelle  Smith

Marcelle Smith

1598083582

What Are Good Traits That Make Great API Product Managers

As more companies realize the benefits of an API-first mindset and treating their APIs as products, there is a growing need for good API product management practices to make a company’s API strategy a reality. However, API product management is a relatively new field with little established knowledge on what is API product management and what a PM should be doing to ensure their API platform is successful.

Many of the current practices of API product management have carried over from other products and platforms like web and mobile, but API products have their own unique set of challenges due to the way they are marketed and used by customers. While it would be rare for a consumer mobile app to have detailed developer docs and a developer relations team, you’ll find these items common among API product-focused companies. A second unique challenge is that APIs are very developer-centric and many times API PMs are engineers themselves. Yet, this can cause an API or developer program to lose empathy for what their customers actually want if good processes are not in place. Just because you’re an engineer, don’t assume your customers will want the same features and use cases that you want.

This guide lays out what is API product management and some of the things you should be doing to be a good product manager.

#api #analytics #apis #product management #api best practices #api platform #api adoption #product managers #api product #api metrics

Autumn  Blick

Autumn Blick

1602851580

54% of Developers Cite Lack of Documentation as the Top Obstacle to Consuming APIs

Recently, I worked with my team at Postman to field the 2020 State of the API survey and report. We’re insanely grateful to the folks who participated—more than 13,500 developers and other professionals took the survey, helping make this the largest and most comprehensive survey in the industry. (Seriously folks, thank you!) Curious what we learned? Here are a few insights in areas that you might find interesting:

API Reliability

Whether internal, external, or partner, APIs are perceived as reliable—more than half of respondents stated that APIs do not break, stop working, or materially change specification often enough to matter. Respondents choosing the “not often enough to matter” option here came in at 55.8% for internal APIs, 60.4% for external APIs, and 61.2% for partner APIs.

Obstacles to Producing APIs

When asked about the biggest obstacles to producing APIs, lack of time is by far the leading obstacle, with 52.3% of respondents listing it. Lack of knowledge (36.4%) and people (35.1%) were the next highest.

#api #rest-api #apis #api-first-development #api-report #api-documentation #api-reliability #hackernoon-top-story