Search

Create GraphQL API With Example

Recently, GraphQL has made a lot of buzz among the developer community, and it has been receiving a lot of attention because of its dynamic nature along with its capability to fetch data, which is a lot less redundant. In this Code Tutorial, you will get to learn about what GraphQL really is, why has it created such hype amongst new-age developers, how is it different from the REST approach, and finally you will be building our own API with GraphQL along with Code Tutorials. Let’s get started!What is GraphQL? A quick primerBefore understanding what GraphQL is, let’s first understand what Query Languages are. Query Languages are computer languages that request the data from a database (called queries) to a client-side application through a server. A well-known example is Structured Query Language or SQL.Coming to GraphQL, by definition - “GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data” (source: Wikipedia). Simply put, GraphQL is a new age Query Language developed by Facebook in 2012 that helps Application Programming Interfaces (APIs) fetch only that data which is requested by the client, and nothing else. This enormously reduces the redundant data at the API endpoint and making the requests blazing fast and developer friendly.Initially, GraphQL was an internal project of Facebook and it was created for fetching specific data and reducing network usage. In 2015, it was released publicly at the React.js conference and reference implementations and specifications of GraphQL in JavaScript were open-sourced. Later most of the programming languages adopted that. New languages like Python, Node.js, Java, C#, PHP, GO, and many more, support GraphQL.But wasn’t the same thing already being done by RESTful APIs? The answer is yes, but GraphQL is different than REST in a lot of ways.GraphQL is Client-Driven, whereas REST is Server-Driven.Queries are organized in terms of Schema and strict typecasting in GraphQL, whereas REST has Endpoints for that task.GraphQL calls Specific data with a single call. REST calls Fixed data with multiple calls.Instead of the GET, POST, PUT, DELETE operations in REST, GraphQL has Query, Mutation, and Subscription for data manipulation.Some of the other advantages of using GraphQL are:GraphQL is faster than other communication APIs.GraphQL can retreat multiple resources and results with a single request.It is easy to use complex systems and microservices with GraphQL as it unifies and hides their complexity.It offers multiple libraries and powerful tools for various projects such as GraphiQL, GraphQL Explorer, Apollo.No under and over data fetching. It fetches the amount of data that is required.The core building block of GraphQL is its schema which is used as a middle way between server and client while defining the accessibility of the data.  A GraphQL schema is written in Schema Definition Language (SDL) and refers to the exact mutations and queries that a client can execute against your data graph. It can be built with any programming language. Simply, the schema defines the type of data that can be fetched, the relationships between these types of data, and what type of queries are allowed. The most basic components of a GraphQL schema are object types. They represent a kind of object you can fetch from your service along with the fields it has. Further, schema helps the client validate their query and eliminate unavailable data or the wrong structure stage.The other two fundamental parts of GraphQL are Query and Resolver. The request to fetch a particular data is called a query and a resolver is used to tell the server from where and how to fetch the data corresponding to the given field. You can execute the GraphQL queries either by Command line or by using a GraphQL server.GraphQL works in three parts – a query to read data, a mutation to write data, and a subscription to receive real-time data over time.Now that you know the ‘What’ and ‘Where’of GraphQL, let’s dive straight into our favorite part, the development phase.Let’s Play with GraphQLTo get started with GraphQL, you need a server that serves your API and a client that connects to your service endpoints. In this section, you will learn about a step-by-step procedure of building an API using GraphQL and Express on top of Node.js. In the next section, you will be implementing these prerequisites into code and start our development for the API.Prerequisites:Understanding of GraphQLNode Package Manager (or NPM) with version 10+Knowledge of basic querying and server-side programming.We will be needing a database to store the user data and everything else that a client-side application can request for. For this, you will be using LowDB, which is a simple file based JSON database for small projects in the localhost. Then you will be needing middleware to connect our database system to the requesting frontend application. For this, you will be using the Express middleware with the GraphQL implementation of Express - the Graphql-express library. Finally, you will be making a client-side application using react which can request all the data from the local database and can perform operations on the database like read, write, and delete.So, our roadmap is simple and straightforward. Create a Database Schema > Use a middleware server to query the database > Create a frontend application to use the data. If this is too much at once for you, do not worry as this is article is being written keeping in mind that the reader is a first-timer for GraphQL and basic querying as usual. Now, let’s dive into the code.Setting up Express GraphQLLet’s begin with the basic project structure of a Node.js application. Begin a new project in a new folder.$ mkdir graphql-example $ cd graphql-exampleUse NPM to intiialize a project$ npm init -yInstall the required dependencies for Express, MongoDB (Mongoose), and some additional dependencies required for the function of Express.$ npm install express mongoose body-parser cors --saveApollo Server is a community-maintained open-source GraphQL server that works with all Node.js HTTP server frameworks, so next, you are going to download and save that.$ npm install apollo-server-express --saveThis should’ve created a package.json and a package-lock.json file within your folder. These files contain information regarding our environment, the dependencies, and the specific versions to run those dependencies.This means our environment is ready and you can now start developing the integrated server and API. We are going to write the Schema inside the index.js file. In the index.js file, start off by writing this code.const express = require('express'); const mongoose = require('mongoose'); const schema = require('./schema'); const bodyParser = require('body-parser'); const cors = require('cors'); const { ApolloServer } = require('apollo-server-express'); const url = "mongodb://localhost:27017/moviesdb"; const connect = mongoose.connect(url, { useNewUrlParser: true }); connect.then((db) => {       console.log('Connected correctly to server!'); }, (err) => {       console.log(err); }); const server = new ApolloServer({       typeDefs: schema.typeDefs,       resolvers: schema.resolvers }); const app = express(); app.use(bodyParser.json()); app.use('*', cors()); server.applyMiddleware({ app }); app.listen({ port: 4000 }, () =>   console.log(`Server ready at  http://localhost:4000${server.graphqlPath}`));In lines number 1 to 6, you’re implementing the necessary modules. Note that here you have imported the ./schema, but you haven’t created that yet. We will be doing this in the next step.In lines number 9 to 14, you are connecting the project to the MongoDB database and logging any error you face to the console.In lines number 16 to 19, you’re creating a new Apollo Server with typeDefs and Resolver. We’ll be defining those in the ./schema later in this tutorial.In lines 21 to 26, you’re firing up the Express Server at port 4000, when you will actually be able to interact with what you’re building.GraphQL has two main principles to work: types and resolvers. We defined them in Apollo Server. We’ll import them from the file you’ll create later.Next, let’s create the file models/movie.js that’ll contain the movie-Mongoose model.const mongoose = require('mongoose'); const Schema = mongoose.Schema; const movieSchema = new Schema({     name: {        type: String,        required: true     },     rating: {        type: Number,        required: true     },     producer: {        type: String,        required: true    } }, {     timestamps: true }); var Movies = mongoose.model('Movie', movieSchema); module.exports = {Movies, movieSchema};We’re going to build a simple movie app, where you can show, add, edit, and delete movies. That way you’ll get through the basics of GraphQL, which is the main goal of this tutorial.In lines 4 to 19, you’re basically determining the schema of the database that is going to hold the data of movies. Every movie is going to have a Name and a Producer of type String and a Rating of type Number.Designing the SchemaLet’s move on to the schema.js file where you’re going to build our GraphQL API.Create a new file in the root of the folder by the name of schema.js and add the following code.const { gql } = require('apollo-server-express');   const Movie = require('./models/movie').Movies;   const typeDefs = gql `    type Movie {      id: ID!      name: String!      producer: String!      rating: Float!  }  type Query {    getMovies: [Movie]    getMovie(id: ID!): Movie  }  type Mutation {      addMovie(name: String!, producer: String!, rating: Float!): Movie      updateMovie(id: ID!, name: String!, producer: String!, rating: Float): Movie      deleteMovie(id: ID!): Movie    } `In this, you’re building the schema. We defined the Movie type which will have an ID, the name of the movie and the producer, and a rating of type Float. The “!” after the types shows that these fields are necessary.Unlike the REST approach of getting different tasks done at different endpoint URLs, GraphQL can create operations in a single endpoint. That is what you have done in line 11 onwards. The type Query determines the GET operations, and type Mutation determines the modification operations like POST, DELETE, etc. In getMovies, you’re returning a list of all available movies in our database, and in getMovie, you’re getting the specific movie by the ID of that movie.Now you’re going to link these with the Mongoose Database queries that are going to perform the actions in the database. And this is done by Resolvers. Resolvers are a collection of functions that connect schema fields and types to various backends. It can read, write, and delete data from and to anywhere in the database, be it SQL, NoSQL, or Graph-based database. In simple terms, they act as a GraphQL query handler. Here’s how you’re going to implement Resolvers in our code:const resolvers = {   Query: {     getMovies: (parent, args) => {       return Movie.find({});     },     getMovie: (parent, args) => {       return Movie.findById(args.id);     }   },   Mutation: {     addMovie: (parent, args) => {       let movie = new Movie({         name: args.name,         producer: args.producer,         rating: args.rating,       });       return movie.save();     },     updateMovie: (parent, args) => {       if (!args.id) return;         return Movie.findOneAndUpdate(          {            _id: args.id          },          {            $set: {              name: args.name,              producer: args.producer,              rating: args.rating,            }          }, {new: true}, (err, Movie) => {            if (err) {              console.log('Something went wrong when updating the movie');            } else {              continue;            }          }       );     }   } } module.exports = {typeDefs,resolvers};This is the basic logic of MongoDB and CRUD applications, which doesn’t come under the scope of this article, since it is majorly focused on GraphQL. However, the logic is simple and straightforward for anyone to understand, so skim through it once.With this, you’re done with a basic Movie API that can perform all the CRUD operations on a database of movies. To test this out, you’re going to fire up our node server and open the browser in http://localhost:4000/graphql which will open the GraphQL Playground.$ node index.js Server ready at http://localhost:4000/graphqlOnce the Playground UI opens, you’re first going to create a Movie Record for the database since it would initially be empty.mutation { addMovie(name: “GraphQL Movie”, producer: “Facebook”, rating:  4.5) { id, name, rating, producer } }OUTPUT:{ “data” : { “addMovie”: { “id”: “5j2j1lnk1LNS231MLK3”, “name”: “GraphQL Movie”, “producer”: “Facebook”, “rating”: 4.5 } } }And now let’s list out all the movies in the database with only their “name” and “rating”.query { getMovies: { name, rating } }OUTPUT:{ “Data”: { “getMovies”: [ { “name”: “GraphQL Movie”, “rating”: 4.5 } ] } }So, you have successfully created a Movie API where you can perform all the CRUD operations on a single endpoint, and also ask for just the data that you want.  This results in a blazing fast API response and a developer-friendly return object that makes development fast and easy.Using GraphQL with ReactUsing GraphQL with react is super easy and can make full-stack development look like a piece of cake. We’re going to build a react app that uses the Movie API you just built to render the results on a frontend client app.Start off by installing the required dependencies.$ npm install create-react-app graphql @apollo/clientCreate a new React appnpx create-react-app movies-appLet’s start off by initializing an ApolloClient instance. In index.js let's first import the symbols you need from @apollo/client, Next, you'll initialize ApolloClient, passing its constructor a configuration object with URI and cache fields:import {   ApolloClient,   InMemoryCache,   ApolloProvider,   useQuery,   gql } from "@apollo/client"; const client = new ApolloClient({   uri: 'https://48p1r2roz4.sse.codesandbox.io',   cache: new InMemoryCache() });The URI specifies the GraphQL Server URL.That’s it! Our client app is ready to fetch data from the GraphQL server. In index.js, let’s wrap our React app with the ApolloProvider Component. Put up the ApolloProvider somewhere high in the app, above any component that might need to access GraphQL data.function App() {   return (     <div>       <h2>My first GraphQL app </h2>     </div>   ); } render(   <ApolloProvider client={client}>     <App />   </ApolloProvider>,   document.getElementById('root'), );With this being done, our client app is now ready to request data from the server and perform queries on the frontend. We can do this using the useQuery React Hook that shares the GraphQL data with the UI.In the index.js, let’s first define the query you want to execute.const MOVIES = gql`   query getMovies {      name,      producer   } `;Next, let's define a component called GetMovies that executes our getMovies query with the useQuery hook:function GetMovies() {   const { loading, error, data } = useQuery(MOVIES);   if (loading) return <p>Loading...</p>;   if (error) return <p>Error :(</p>;   return data.map(({ name, producer }) => (     <div key={name}>       <p>         {name}: Produced by {producer}       </p>     </div>   )); }Whenever this component renders, the useQuery hook automatically executes our query and binds the results to the data property on successful completion of the query.Finally, you'll add GetMovies to our existing component tree:function App() {   return (     <div>       <h2>My first Apollo app </h2>       <GetMovies />     </div>   ); }When your app reloads, you should briefly see a loading indicator, followed by a list of Movies present in the MongoDB database.Congratulations. You just made a React app that uses GraphQL to render data from the server. Give yourself a pat on the back for this one.Dev-friendly Query Languages are the FutureSo, wrapping it all up in a few more lines. In this tutorial, you learned what GraphQL is - a new age Query Language that is data specific and client-oriented, how is it different (and better) than REST architecture - it is developer friendly, blazing-fast, and easy to learn or understand. We also made a mock API of Movies using GraphQL and MongoDB and performed the CRUD operations using just one single endpoint URL - another benefit over the RESTful architecture. And finally, you went on to create a React application that uses these benefits of GraphQL and combines them with the benefits of React to give a hyper-fast, easy, and full-stack app that renders Movies on request.We hope you learned something new from this article. Once you’ve started this journey of GraphQL, it is a fun ride ahead since it is a relatively new tech and not many people out there are having this skill under their hood. So, make use of this opportunity and outshine the rest.Keep Learning.

Create GraphQL API With Example

5K
Create GraphQL API With Example

Recently, GraphQL has made a lot of buzz among the developer community, and it has been receiving a lot of attention because of its dynamic nature along with its capability to fetch data, which is a lot less redundant. In this Code Tutorial, you will get to learn about what GraphQL really is, why has it created such hype amongst new-age developers, how is it different from the REST approach, and finally you will be building our own API with GraphQL along with Code Tutorials. Let’s get started!

What is GraphQL? A quick primer

Before understanding what GraphQL is, let’s first understand what Query Languages are. Query Languages are computer languages that request the data from a database (called queries) to a client-side application through a server. A well-known example is Structured Query Language or SQL.

Coming to GraphQL, by definition - “GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data” (source: Wikipedia). Simply put, GraphQL is a new age Query Language developed by Facebook in 2012 that helps Application Programming Interfaces (APIs) fetch only that data which is requested by the client, and nothing else. This enormously reduces the redundant data at the API endpoint and making the requests blazing fast and developer friendly.

Initially, GraphQL was an internal project of Facebook and it was created for fetching specific data and reducing network usage. In 2015, it was released publicly at the React.js conference and reference implementations and specifications of GraphQL in JavaScript were open-sourced. Later most of the programming languages adopted that. New languages like Python, Node.js, Java, C#, PHP, GO, and many more, support GraphQL.

But wasn’t the same thing already being done by RESTful APIs? The answer is yes, but GraphQL is different than REST in a lot of ways.

  • GraphQL is Client-Driven, whereas REST is Server-Driven.
  • Queries are organized in terms of Schema and strict typecasting in GraphQL, whereas REST has Endpoints for that task.
  • GraphQL calls Specific data with a single call. REST calls Fixed data with multiple calls.
  • Instead of the GET, POST, PUT, DELETE operations in REST, GraphQL has Query, Mutation, and Subscription for data manipulation.

Some of the other advantages of using GraphQL are:

  • GraphQL is faster than other communication APIs.
  • GraphQL can retreat multiple resources and results with a single request.
  • It is easy to use complex systems and microservices with GraphQL as it unifies and hides their complexity.
  • It offers multiple libraries and powerful tools for various projects such as GraphiQL, GraphQL Explorer, Apollo.
  • No under and over data fetching. It fetches the amount of data that is required.

The core building block of GraphQL is its schema which is used as a middle way between server and client while defining the accessibility of the data.  A GraphQL schema is written in Schema Definition Language (SDL) and refers to the exact mutations and queries that a client can execute against your data graph. It can be built with any programming language. Simply, the schema defines the type of data that can be fetched, the relationships between these types of data, and what type of queries are allowed. The most basic components of a GraphQL schema are object types. They represent a kind of object you can fetch from your service along with the fields it has. Further, schema helps the client validate their query and eliminate unavailable data or the wrong structure stage.

The other two fundamental parts of GraphQL are Query and Resolver. The request to fetch a particular data is called a query and a resolver is used to tell the server from where and how to fetch the data corresponding to the given field. You can execute the GraphQL queries either by Command line or by using a GraphQL server.

GraphQL works in three parts – a query to read data, a mutation to write data, and a subscription to receive real-time data over time.

Now that you know the ‘What’ and ‘Where’of GraphQL, let’s dive straight into our favorite part, the development phase.

Let’s Play with GraphQL

To get started with GraphQL, you need a server that serves your API and a client that connects to your service endpoints. In this section, you will learn about a step-by-step procedure of building an API using GraphQL and Express on top of Node.js. In the next section, you will be implementing these prerequisites into code and start our development for the API.

Prerequisites:

  • Understanding of GraphQL
  • Node Package Manager (or NPM) with version 10+
  • Knowledge of basic querying and server-side programming.

We will be needing a database to store the user data and everything else that a client-side application can request for. For this, you will be using LowDB, which is a simple file based JSON database for small projects in the localhost. Then you will be needing middleware to connect our database system to the requesting frontend application. For this, you will be using the Express middleware with the GraphQL implementation of Express - the Graphql-express library. Finally, you will be making a client-side application using react which can request all the data from the local database and can perform operations on the database like read, write, and delete.

So, our roadmap is simple and straightforward. Create a Database Schema > Use a middleware server to query the database > Create a frontend application to use the data. If this is too much at once for you, do not worry as this is article is being written keeping in mind that the reader is a first-timer for GraphQL and basic querying as usual. Now, let’s dive into the code.

Setting up Express GraphQL

Let’s begin with the basic project structure of a Node.js application. Begin a new project in a new folder.

$ mkdir graphql-example 
$ cd graphql-example

Use NPM to intiialize a project

$ npm init -y

Install the required dependencies for Express, MongoDB (Mongoose), and some additional dependencies required for the function of Express.

$ npm install express mongoose body-parser cors --save

Apollo Server is a community-maintained open-source GraphQL server that works with all Node.js HTTP server frameworks, so next, you are going to download and save that.

$ npm install apollo-server-express --save

This should’ve created a package.json and a package-lock.json file within your folder. These files contain information regarding our environment, the dependencies, and the specific versions to run those dependencies.

This means our environment is ready and you can now start developing the integrated server and API. We are going to write the Schema inside the index.js file. In the index.js file, start off by writing this code.

const express = require('express'); 
const mongoose = require('mongoose'); 
const schema = require('./schema'); 
const bodyParser = require('body-parser'); 
const cors = require('cors'); 
const { ApolloServer } = require('apollo-server-express'); 

const url = "mongodb://localhost:27017/moviesdb"; 
const connect = mongoose.connect(url, { useNewUrlParser: true }); 
connect.then((db) => { 
      console.log('Connected correctly to server!'); 
}, (err) => { 
      console.log(err); 
}); 

const server = new ApolloServer({ 
      typeDefs: schema.typeDefs, 
      resolvers: schema.resolvers 
}); 

const app = express(); 
app.use(bodyParser.json()); 
app.use('*', cors()); 
server.applyMiddleware({ app }); 
app.listen({ port: 4000 }, () => 
  console.log(`Server ready at 
http://localhost:4000${server.graphqlPath}`));

In lines number 1 to 6, you’re implementing the necessary modules. Note that here you have imported the ./schema, but you haven’t created that yet. We will be doing this in the next step.

In lines number 9 to 14, you are connecting the project to the MongoDB database and logging any error you face to the console.

In lines number 16 to 19, you’re creating a new Apollo Server with typeDefs and Resolver. We’ll be defining those in the ./schema later in this tutorial.

In lines 21 to 26, you’re firing up the Express Server at port 4000, when you will actually be able to interact with what you’re building.

GraphQL has two main principles to work: types and resolvers. We defined them in Apollo Server. We’ll import them from the file you’ll create later.

Next, let’s create the file models/movie.js that’ll contain the movie-Mongoose model.

const mongoose = require('mongoose'); 

const Schema = mongoose.Schema; 
const movieSchema = new Schema({ 
    name: { 
       type: String, 
       required: true 
    }, 
    rating: { 
       type: Number, 
       required: true 
    }, 
    producer: { 
       type: String, 
       required: true 
   } 
}, { 
    timestamps: true 
}); 

var Movies = mongoose.model('Movie', movieSchema); 
module.exports = {Movies, movieSchema};

We’re going to build a simple movie app, where you can show, add, edit, and delete movies. That way you’ll get through the basics of GraphQL, which is the main goal of this tutorial.

In lines 4 to 19, you’re basically determining the schema of the database that is going to hold the data of movies. Every movie is going to have a Name and a Producer of type String and a Rating of type Number.

Designing the Schema

Let’s move on to the schema.js file where you’re going to build our GraphQL API.

Create a new file in the root of the folder by the name of schema.js and add the following code.

const { gql } = require('apollo-server-express'); 
  const Movie = require('./models/movie').Movies; 

  const typeDefs = gql ` 
   type Movie { 
     id: ID! 
     name: String! 
     producer: String! 
     rating: Float! 
 } 
 type Query { 
   getMovies: [Movie] 
   getMovie(id: ID!): Movie 
 } 
 type Mutation { 
     addMovie(name: String!, producer: String!, rating: Float!): Movie 
     updateMovie(id: ID!, name: String!, producer: String!, rating: Float): Movie 
     deleteMovie(id: ID!): Movie 
   } 
`

In this, you’re building the schema. We defined the Movie type which will have an ID, the name of the movie and the producer, and a rating of type Float. The “!” after the types shows that these fields are necessary.

Unlike the REST approach of getting different tasks done at different endpoint URLs, GraphQL can create operations in a single endpoint. That is what you have done in line 11 onwards. The type Query determines the GET operations, and type Mutation determines the modification operations like POST, DELETE, etc. In getMovies, you’re returning a list of all available movies in our database, and in getMovie, you’re getting the specific movie by the ID of that movie.

Now you’re going to link these with the Mongoose Database queries that are going to perform the actions in the database. And this is done by Resolvers. Resolvers are a collection of functions that connect schema fields and types to various backends. It can read, write, and delete data from and to anywhere in the database, be it SQL, NoSQL, or Graph-based database. In simple terms, they act as a GraphQL query handler. Here’s how you’re going to implement Resolvers in our code:

const resolvers = { 
  Query: { 
    getMovies: (parent, args) => { 
      return Movie.find({}); 
    }, 

    getMovie: (parent, args) => { 
      return Movie.findById(args.id); 
    } 
  }, 
  Mutation: { 
    addMovie: (parent, args) => { 
      let movie = new Movie({ 
        name: args.name, 
        producer: args.producer, 
        rating: args.rating, 
      }); 
      return movie.save(); 
    }, 
    updateMovie: (parent, args) => { 
      if (!args.id) return; 
        return Movie.findOneAndUpdate( 
         { 
           _id: args.id 
         }, 
         { 
           $set: { 
             name: args.name, 
             producer: args.producer, 
             rating: args.rating, 
           } 
         }, {new: true}, (err, Movie) => { 
           if (err) { 
             console.log('Something went wrong when updating the movie'); 
           } else { 
             continue; 
           } 
         } 
      ); 
    } 
  } 
} 

module.exports = {typeDefs,resolvers};

This is the basic logic of MongoDB and CRUD applications, which doesn’t come under the scope of this article, since it is majorly focused on GraphQL. However, the logic is simple and straightforward for anyone to understand, so skim through it once.

With this, you’re done with a basic Movie API that can perform all the CRUD operations on a database of movies. To test this out, you’re going to fire up our node server and open the browser in http://localhost:4000/graphql which will open the GraphQL Playground.

$ node index.js 
Server ready at http://localhost:4000/graphql

Once the Playground UI opens, you’re first going to create a Movie Record for the database since it would initially be empty.

mutation {
addMovie(name: “GraphQL Movie”, producer: “Facebook”, rating:  4.5) {
id,
name,
rating,
producer
}
}

OUTPUT:

{
“data” : {
“addMovie”: {
“id”: “5j2j1lnk1LNS231MLK3”,
“name”: “GraphQL Movie”,
“producer”: “Facebook”,
“rating”: 4.5
}
}
}

And now let’s list out all the movies in the database with only their “name” and “rating”.

query {
getMovies: {
name,
rating
}
}

OUTPUT:

{
“Data”: {
“getMovies”: [
{
“name”: “GraphQL Movie”,
“rating”: 4.5
}
]
}
}

So, you have successfully created a Movie API where you can perform all the CRUD operations on a single endpoint, and also ask for just the data that you want.  This results in a blazing fast API response and a developer-friendly return object that makes development fast and easy.

Using GraphQL with React

Using GraphQL with react is super easy and can make full-stack development look like a piece of cake. We’re going to build a react app that uses the Movie API you just built to render the results on a frontend client app.

Start off by installing the required dependencies.

$ npm install create-react-app graphql @apollo/client

Create a new React app

npx create-react-app movies-app

Let’s start off by initializing an ApolloClient instance. In index.js let's first import the symbols you need from @apollo/client, Next, you'll initialize ApolloClient, passing its constructor a configuration object with URI and cache fields:

import { 
  ApolloClient, 
  InMemoryCache, 
  ApolloProvider, 
  useQuery, 
  gql 
} from "@apollo/client"; 

const client = new ApolloClient({ 
  uri: 'https://48p1r2roz4.sse.codesandbox.io', 
  cache: new InMemoryCache() 
});

The URI specifies the GraphQL Server URL.

That’s it! Our client app is ready to fetch data from the GraphQL server. In index.js, let’s wrap our React app with the ApolloProvider Component. Put up the ApolloProvider somewhere high in the app, above any component that might need to access GraphQL data.

function App() {
  return (
    <div>
      <h2>My first GraphQL app </h2>
    </div>
  );
}

render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById('root'),
);

With this being done, our client app is now ready to request data from the server and perform queries on the frontend. We can do this using the useQuery React Hook that shares the GraphQL data with the UI.

In the index.js, let’s first define the query you want to execute.

const MOVIES = gql`
  query getMovies {
     name,
     producer
  }
`;

Next, let's define a component called GetMovies that executes our getMovies query with the useQuery hook:

function GetMovies() {

  const { loading, error, data } = useQuery(MOVIES);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return data.map(({ name, producer }) => (
    <div key={name}>
      <p>
        {name}: Produced by {producer}
      </p>
    </div>
  ));
}

Whenever this component renders, the useQuery hook automatically executes our query and binds the results to the data property on successful completion of the query.

Finally, you'll add GetMovies to our existing component tree:

function App() {
  return (
    <div>
      <h2>My first Apollo app </h2>

      <GetMovies />
    </div>
  );
}

When your app reloads, you should briefly see a loading indicator, followed by a list of Movies present in the MongoDB database.

Congratulations. You just made a React app that uses GraphQL to render data from the server. Give yourself a pat on the back for this one.

Dev-friendly Query Languages are the Future

So, wrapping it all up in a few more lines. In this tutorial, you learned what GraphQL is - a new age Query Language that is data specific and client-oriented, how is it different (and better) than REST architecture - it is developer friendly, blazing-fast, and easy to learn or understand. We also made a mock API of Movies using GraphQL and MongoDB and performed the CRUD operations using just one single endpoint URL - another benefit over the RESTful architecture. And finally, you went on to create a React application that uses these benefits of GraphQL and combines them with the benefits of React to give a hyper-fast, easy, and full-stack app that renders Movies on request.

We hope you learned something new from this article. Once you’ve started this journey of GraphQL, it is a fun ride ahead since it is a relatively new tech and not many people out there are having this skill under their hood. So, make use of this opportunity and outshine the rest.

Keep Learning.

KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

How to Become a Successful Full Stack Web Developer?

The ResponsibilitiesFull-stack developer roles are among the hottest careers in the tech space now. These talented folks can develop a whole product from scratch. A full-stack developer is a combination of a Front-end developer and a Back-end developer. These two in themselves are full-time jobs and most people make careers out of one of them. So, we will start with the Front-end roadmap and then go to the Back-end roadmap. A person interested in becoming a Full-stack developer needs to have proficiency in both the front-end and back-end tools, just like I started as a Front-end developer and later on become a Full stack developer by mastering JavaScript backend technologies and databases.Industries were relevantThe demand for Full stack developers is the highest in early-stage startups, where they want to create a Minimum Viable Product at the earliest to showcase to the investors. It is also a nice skill to have in addition to frontend technologies or backend technologies alone since an employer prefers people with both skills.What to learn & where to learnThere are a lot of technologies to learn to be a Full-Stack developer. We will discuss about them in the coming sections.   List of technologies to master to become a Full-Stack developer A full-stack developer is actually a combination of Front-end developer and Back-end developer. We need to master both, and both have different Roadmaps. Let’s start with the basics. The frontend is the website that we see and it is primarily made with HTML and CSS.  JavaScript was also used earlier but nowadays, it is created with JavaScript frameworks like ReactJS, Angular, or Vue. All these frameworks require one to learn the basics of HTML, CSS, & JavaScript. So, we need to learn the basics followed by at least one framework.In the backend, we have a lot of technologies and databases also. So, we need to choose one backend framework from Java (Spring Framework), JavaScript (NodeJS), etc, and then also learn databases. Databases are divided into two categories, which are NoSQL(MongoDB) and SQL(PostgreSQL, MySQL, Oracle) databases. So, you need to choose one of the databases.We are also required to know about DevOps, which is a practice of harmonizing development and operations whereby the entire pipeline from development, testing, deployment, continuous integration, and feedback is automated. The knowledge of either AWS or Azure-based cloud ecosystem is required, and also CI/CD like Jenkins and containerizing & orchestrating applications using Docker and Kubernetes.Frontend RoadmapLearn the BasicsPlease refer to the attached figure for the Front-end roadmap, as we will be referring to this throughout this article. We have to start our journey by learning HTML, CSS, and JavaScript which is the base for a web app or website. HTML has changed a bit over the years, with the introduction of HTML 5 and semantics tags, so make sure to update yourself. JavaScript which was released in 1995, didn’t change much during the next 20 years. But once more and more developers started using it, the ECMA committee decided to add some very nice features and enhance the language and renamed it ES6 in 2015. After that, they regularly added new features to the language and have just released ES2020 in June 2020, which has many additional features. So, learn the basic JavaScript first and then upgrade to ES6 and newer versions. CSS is what makes a website or web-app beautiful, and is often considered the hardest part by a developer. Earlier, CSS was very confusing and had a steep learning curve, because of the use of floats to create a layout. Developers usually used to work with CSS frameworks like bootstrap to design a site. But things have changed a lot with the invention of CSS Grid and Flexbox. Some of the best resources to learn the basics are -html.specdeveloper.mozilla.HTMLStyle CSSdeveloper.mozilla.CSSdeveloper.mozilla.JavaScriptGetting Deeper Now, just learning JavaScript and some basic CSS will not make you a good Front-end developer as you have to take a deep dive into JavaScript. We will discuss CSS later, after learning the essentials of JavaScript.JavaScript EssentialsThere are many things associated with JavaScript which we need to learn before moving forward.The TerminalThe first thing to learn is to work in a terminal and master some of the basic commands. If you are on a Mac, it’s already based on Linux and runs most Linux commands. If you are working on Windows then you must install git bash, which will give you a Linux environment to work with. In JavaScript frameworks, we need to run a lot of commands from the terminal, like if we want to install a third-party dependency by npm.  The basics of Linux can be learned from their official site: Linux FoundationVersion ControlNext, learning version control is very important because we should always keep our code in some remote repository like Github. The industry works on Git, which is version control software. It is completely command-based and is used heavily everywhere. Learn the basic commands which will be useful even for an individual developer. Later on, when working with teams, more advanced knowledge of the git command is required.Through the git commands, we store our code in repositories. The most popular ones are Github and Bit Bucket, so we need to learn how to store and link them.The basics of git can be learned from this awesome tutorial: Git TutorialTask Runners Task runners are applications that are used to automate tasks required in projects. These tasks include minification of JavaScript and CSS files, CSS preprocessing from SASS to CSS, image optimization, and Unit testing. The three popular task runners are npm scripts, gulp, and grunt.The npm script is nothing but the package.json file which comes with React projects or is created in a Node.js project using npm init. Gulp and Grunt are much bigger applications and also have a plugin ecosystem that is suited for large JavaScript projects. The basics for these two technologies can be learned from here:GulpGruntModule Loader and Bundler  Both module loaders and bundlers are required for large JavaScript applications. Knowledge of both is required if the project you are working is a big Vanilla JavaScript project. When a large JavaScript application consists of hundreds of files, the module loader takes care of the dependency and makes sure all the modules are loaded when the application is executed. Examples are RequireJS and SystemJS.Module bundlers also do the same thing, building it at the time of application build rather than at the runtime. Popular examples are Webpack and Rollup.The basic tutorials which can be referred are:RequireJSGithubWebpackRollupJSTesting  Testing nowadays is very important in any type of project. There are two types of testing; one is known as Unit testing and other as end-to-end testing. For unit testing we write test cases and the most popular tool nowadays is Jest. End-to-end testing is automated testing, which emulates the whole app. Suppose, an app has a login screen and then it shows posts. The testing tool will run the web app to check whether all the functionalities are done correctly. The two most popular options today are Puppeteer and Cypress. The tutorials to refer for these topics are:JestPuppeteerCypressLibraries and FrameworkThey are the most important part of the JavaScript ecosystem nowadays. It all started with the release of AngularJS in 2010. Before that period most enterprise apps were made in Java and were desktop apps. But AngularJS changed everything because it made it easy to manage big projects with JavaScript and helped to create complex web apps.React It is the most popular JavaScript library today and is used by both enterprises and startups that have a huge ecosystem. It is not a complete framework like Angular and we have to install third-party dependencies for most things. But if you want to learn a framework that will get you a job, then that framework would be ReactJS, and its demand is not going away for the next 5 years. The component approach and its easy learning curve have made React more popular than other frameworks. A good starting tutorial for React is: ReactJSState Management In React state management can sometimes become complex, when we need to share data between components. We generally take the help of external packages in it with the most popular being Redux. But we also have other state management libraries like XState and Recoil.Server-side rendering With performance becoming important nowadays, Server-Side Rendering speeds up the React projects even faster. In SSR projects, the React code is rendered on the server and the client browser directly receives the HTML, CSS, JS bundle. The only framework to do it is NextJS.Static Site Generators   A lot of sites don’t need to be updated frequently and it is the place where the only Static Site Generator for ReactJS, which is GatsbyJS shines. With the help of GatsbyJS we can create extremely fast static sites and it gets into Wordpress domain a lot with it. GatsbyJS also has a huge ecosystem of plugins, which enhances its functionalities. React Testing   Unit testing is a very important part of ReactJS projects, especially the ones which are very large. Unit testing ensures that we have lower bugs in the Production build. The two popular libraries are – Enzyme and Jest. Angular It is a complete framework and unlike React requires very few external dependencies. Everything is built within Angular and we don’t have to go outside for more features. Since it was among the earliest frameworks, older projects are in Angular and it is still widely used in enterprises. A good tutorial to learn Angular is below-AngularVue Vue is another very popular JavaScript library, which has the best features of both ReactJS and Angular and has become very popular in recent years. It is widely used in both enterprises and startups. A good tutorial to start with Vue is below-Vue  NuxtJS-   It is used for Server-Side Rendering in Vue projects and is similar to the NextJS framework used in ReactJS for SSR.  Svelte It is the newest of all frameworks/libraries and has become quite popular, but still not used much in enterprises and startups. It is different from React, Vue, and Angular and converts the app at build time rather than at run time as in the other three. Good tutorials to start with Svelte are below-SvelteSvelte handbookCSS Deep DiveA lot has changed in CSS after it included CSS Grid and Flexbox; it has become much easier for developers to work with. CSS Essentials   It is now mandatory for frontend developers to learn CSS Grid and Flexbox, because through it we can develop beautiful layouts with ease. More companies are moving away from CSS Frameworks and have started working with CSS Grid and Flexbox, which are now supported by all browsers. Good tutorials to learn Flexbox and CSS Grid are below-CSS FlexboxCSS layout FlexboxCSS GridCSS layout GridGrid GuidePreprocessors CSS preprocessors are used to add special functionalities in CSS, which it lacks. An example is Sass, which adds special features like variables and nested rules in CSS and is widely used in the industry for larger projects. The other popular one is PostCSS, in which we can use custom plugin and tools in CSS. CSS Frameworks Frameworks were very popular from the early days of CSS, when it was very complicated because of floats. Bootstrap  This is the most popular and oldest CSS framework; easy to learn and also has a wide variety of elements, templates and interfaces. Bulma   It is another CSS framework, which is very popular and much easier to use than bootstrap. Tailwind CSS   This is a fairly new CSS framework and is quite popular nowadays. It follows a different approach than the other frameworks and contains easier classes. Styled Components (React)   This is a CSS in JS library and is for React only. It is used to create components out of every style and is very popular in the React world.  CI/CDContinuous Integration/ Continuous deployment is mainly used by DevOps. But a frontend engineer should know its basics. It is used to build, test and deploy applications automatically.Github Actions    It is a freely available CI/CD pipeline, which directly integrates to your github based project and can be used in a variety of languages. Deployment It is again a task that mainly falls into the domain of Backend engineers and DevOps, but a frontend engineer should know some basic and simple tools. Static Deployment   These products are mainly used to deploy static sites, which consists of HTML, CSS, and JavaScript only. Two very popular services are Amazon S3 and Surge.sh.Node Application Deployment   The projects containing node code cannot be deployed using static deployment. Even if the project is a simple ReactJS project, it also uses node for processing. These applications require services which run the Node code and deploy it. The three most popular services are Vercel, Firebase and Netlify. Backend Roadmap (Including Storage, Services & Deployment)Understanding the BackendBackend is the part of the website that provides the functionality, allowing people to browse their favorite site, purchase a product and log into their account, for instance. All data related to a user or a product or anything else are generally stored in databases or CMS (Content Management System) and when a user visits any website, they are retrieved from there and shown. One of the responsibilities of a backend engineer involves writing APIs, which actually interact with the database and get the data. They are also involved in writing schemas of databases and creating the structure of databases. Backend EssentialsFor a backend engineer, working in a Linux environment is an essential skill. A lot of the configurations are done on the terminal. So, he or she should be very good with Linux commands.Also, they should know both commands and the use of any git powered platforms like Github or bitbucket.Languages and FrameworksAll of the popular languages have some framework, which has been used for backend development. These frameworks are generally used to create API endpoints, which are used to fetch or store data in the database. For example, when we scroll articles on Facebook, these articles are fetched from a database and we use the GET method to fetch them. Similarly, when we write an article and hit submit, it uses POST method.Now, different frameworks implement this GET, POST, and other APIs also referred to as RESTful APIs in their own way.JavaJava is by far the oldest and the most used language for backend development. It is also used for a variety of other tasks like Android development, but it shines in the backend because of its multithreading abilities. So, enterprise-grade web apps and web apps with a lot of traffic prefer Java, because it handles loads better.The most popular frameworks for backend development in Java are Spring Framework and Hibernate.JavaScriptIt is a very popular choice for backend development because on the frontend side JavaScript is the only choice. So, a lot of front-end engineers can take this choice to become Full-stack developers.Node.jsIt allows developers to use JavaScript to write server-side code, through which they can write APIs. Actually, the API part can be done by numerous frameworks of Node.js out of which Express is widely used. The other popular framework is Fastify.PythonPython is one of the most popular languages among developers and has been used in a variety of fields. The two most popular frameworks for Python are Flask and Django.C#It is a very popular programming language that was developed by Microsoft and it has the power of C++. Its popularity increased once the .NET framework was released for backend development.As Microsoft is very popular in enterprises, the .NET framework is generally preferred in enterprises.GoGo language which is also referred to as Golang, has gained popularity in recent years. It is used a lot in Backend programming and the two popular frameworks are Gin and Beego.DatabaseFor a Backend engineer, after making APIs with a framework based on language, it's time to learn about Databases. Databases are used to store most of the things which we see in a web app, from user login credentials to user posts and everything else. In the earlier days, we only used to have one type of Database and that was Relational databases, which use tables to store data. Now we have two other categories also, one being NoSQL databases and the other In-memory databases.Relational databasesRelational databases allow you to create, update and delete data stored in a table format. This type of database mostly uses SQL language to access the data, hence is also known as an SQL database.MySQLIt is one of the oldest databases and was released in 1995. It is an open-source database and was very popular in the 2000s with the rise of LAMP (Linux, Apache, MySQL, PHP) stack. It is still widely in use, but there are other popular Relational databases.A good tutorial to learn MySQL is- MySQL Tutorial.PostgreSQLPostgreSQL, which is also known as Postgres is also an old open-source Relational database, which was released in 1996. But it gained popularity recently, as it goes very well with modern stacks containing NodeJS and other backend technologies. A good tutorial to learn PostgreSQL is- PostgreSQL Tutorial.OracleOracle is the most popular and oldest relational database. It was released in 1979 and still remains the number one preference for enterprise customers. All the big banks and other organizations run on Oracle databases. So, the knowledge of Oracle is a must in many companies for an Engineer. A good tutorial to learn Oracle is- Oracle Tutorial.MS-SQLMS-SQL is also known as Microsoft SQL and is yet another commercial Relational database. It has got different editions, used by different audiences. It is also heavily used by enterprise users and powers a whole lot of big systems around the world.NoSQL databasesNoSQL databases are also called non-SQL databases. The NoSQL databases mainly store data as key-value pairs, but some of them also use a SQL-like structure.These databases have become hugely popular in the 21st century, with the rise of large web apps which have a lot of concurrent users. These databases can take huge loads, even millions of data connections, required by web apps like Facebook, Amazon, and others. Besides this, it is very easy to horizontally scale a NoSQL database by adding more clusters, which is a problem in Relational Databases.MongoDBIt is the most popular NoSQL database, used by almost every modern app. It is a free-to-use database, but the hosting is charged if we host on popular cloud services like MongoDB atlas. Its knowledge is a must for backend engineers, who work on the modern stack. MongoDB uses json like documents to store data. A good tutorial to learn MongoDB is- MongoDB Tutorial.DynamoDBDynamoDB is a proprietary database service provided by Amazon. It is quite similar to MongoDB and uses key-value pairs to store data. It is also a part of the popular AWS services. A good tutorial to learn DynamoDB is- DynamoDB Tutorial.CassandraCassandra is an open-source and free-to-use NoSQL database. It takes a different approach when compared to other NoSQL databases, because we use commands like SQL, which are known as CQL (Cassandra Query Language). A good tutorial to learn Cassandra is- Cassandra Tutorial.In-memory databasesThe in-memory database is a database that keeps all the data in the RAM. This means it is the fastest among all databases.  The most popular and widely used in-memory database is Redis.RedisRedis (Remote Dictionary Server) is an in-memory database, which stores data in RAM in a json like key-value format. It keeps the data persistent by updating everything in the transaction log, because when systems are shut down their RAM is wiped clean. A good tutorial to learn Redis is- Redis Tutorial.StorageStoring the data is an important part of any application. Although this is mainly DevOps territory, every backend developer should know the basics for the same. We need to store the database data and also the backend code. Beside this the frontend code must also be stored somewhere. Nowadays everything is stored in the cloud, which is preferred by individuals, startups and enterprises. The two most popular cloud-based storages are –Amazon S3Azure Blob StorageServices and APIsThese are theoretical concepts and are implemented by various services, but a backend engineer should know them and how to use them.Restful APIsThis is by far the most popular way to get data from a database. It was made more popular, with the rise of web apps. We do GET, PUT, POST, and DELETE operations to read, update, create or delete data from databases. We have discussed different languages and frameworks earlier, which have their own implementations for these operations.Microservices ArchitectureIn microservice architecture, we divide a large and complex project into small, independent services. Each of these is responsible for a specific task and communicates with other services through simple APIs. Each service is built by a small team from the beginning and separated by boundaries which make it easier to scale up the development effort if needed.GraphQLIt is the hottest new kid in the block, which is an alternative to the Restful APIs. The problem with Restful APIs is that if you want some data stored in database, you need to get the whole data sent by the endpoint. On the other hand, with GraphQL, you get a query type language that can return only the part of the data which you require.DevOps & DeploymentA backend engineer requires a fair bit of DevOps knowledge. So, we will next dive deep into the methodologies in DevOps.Containerization & OrchestrationContainers are a method of building, packaging, and deploying software. They are like but not the same thing as virtual machines (VMs). One of the primary differences is that containers are isolated or abstracted away from the underlying operating system and infrastructure that they run on. In the simplest terms, a container includes both an application’s code and everything that code needs to run properly.Container orchestration is the automatic process of managing the work of individual containers for applications based on microservice architecture. The popular Containerization and Orchestration tools are-KubernetesDockerDevOpsDevOps is a set of practices that combine software development (Dev) and IT operations (Ops). It aims to shorten the systems development life cycle and provide continuous delivery with high software quality. The two most popular DevOps services are AWS and Azure. Both of them are cloud based and are market leaders. Both of these platforms contain a wide variety of similar services.AWSIt consists of over 200 products and services for storage, database, analytics, deployment, serverless function and many more. AWS is the market leader as of now with 33% of market share. The AWS certifications are also one of the most in-demand certifications and a must for frontend engineers as well as Backend engineers.AzureMicrosoft Azure is second in terms of market share of cloud-based platforms, with 18% of the market. It also consists of SaaS (Software as a Service), PaaS (Platform as a Service), and IaaS (Infrastructure as a Service) like AWS.PaaS (Platform as a Service)There are several smaller players, which provide Platform as a Service and are much easier to use than services like AWS and Azure. With these services you can directly deploy your React or other web apps, by just hosting them on GitHub and pushing the code. These services are preferred a lot by freelancers, hobbyists, and small companies as they don’t require investment in learning complicated services like AWS and Azure. The three most popular PaaS services are –Digital OceanHerokuNetlifyServerlessServerless computing is an execution model where the cloud provider (AWS, Azure, or Google Cloud) is responsible for executing a piece of code by dynamically allocating resources and only charging for the number of resources used to run the code. The code is typically run inside stateless containers that can be triggered by a variety of events including HTTP requests, database events, queuing services, monitoring alerts, file uploads, scheduled events (cron jobs), etc. The code that is sent to the cloud provider for execution is usually in the form of a function.AWS LambdaIt is an event-driven, serverless platform which is part of AWS. The various languages supported by AWS Lambda are Node.js, Python, Java, Go, Ruby and .NET. AWS Lambda was designed for use cases such as updates to DynamoDB tables, responding to a website click etc. After that it will “spin down” the database service, to save resources.Azure FunctionsThey are quite similar to AWS Lambda, but are for Microsoft Azure. Azure functions have a browser-based interface to write code to respond to events generated by http requests etc. The service accepts programming languages like C#, F#, Node.js, Python, PHP and Java.Serverless FrameworkIt is an open-source web-framework written using Node.js. Popular services like AWS Lambda, Azure functions and Google cloud functions are based on it.CI/CDA backend developer should know the popular CI/CD (Continuous Integration/Continuous deployment) tools. These tools help to automate the whole process of building, testing and deployment of applications.Github ActionsIt is a freely available CI/CD pipeline, which directly integrates to your GitHub-based project and can be used in a variety of languages.JenkinsJenkins is the most popular CI/CD automation tool, which helps in the building, testing, and deployment of applications. Jenkins was written in Java and over the years has been built to support over 1400 plugins, which extend its functionalities.Circle CICircle CI is also a CI/CD automation tool, which is cloud-based and so it is different from Jenkins. It is much easier to use than Jenkins, but has a smaller community and lower user base.SecuritySecurity is an important aspect of any application. Most applications containing user personal data, like email, etc, are often targeted by hackers.OWASPThe Open Web Application Security Project (or OWASP), is a non-profit organization dedicated to web application security. They have free material available on their website, making it possible for anyone to improve their web application security.Protecting Services & databases against threatsHackers target databases of popular web apps on a regular basis to get sensitive information about their customers. This data is then sold to the highest bidder on the dark-net. When such public breaches are reported, then it's a reputation loss for the enterprise also. So, a lot of emphases should be given to Authentication, Access, Backups, and Encryption while setting up a database. The databases should also be monitored for any suspicious activities.Besides this, the API routes also need to be protected, so that the hacker cannot manipulate them.Career rolesMost of the companies hire Frontend developers, Backend developers and DevOps engineers separately. This is because most of the enterprise projects are huge, in which roles and responsibilities are distributed.But there is a huge demand for Full Stack developers in the startup sector in US and India. These companies need specialists who can get the product out as soon as possible with agile and small teams.Top companies hiringAlmost every company on the planet is hiring web-developers or outsourcing the development work. Since the past decade, the demand for developers has risen exponentially. The top technology companies which hire full stack developers are Facebook, Amazon, Apple, Netflix, Google, Uber, Flipkart, Microsoft and more.The sites of each of these companies are web apps (excluding Apple and Microsoft), with complex frontend and backend systems. The frontend generally consists of React or Angular and the backend is a combination of various technologies. The DevOps part is also quite important in these web-apps as they handle millions of concurrent connections at once.SalariesThe salary of a beginner Frontend developer in India starts from Rs. 300,000($ 3980) per year in service-based companies to Rs. 12,00,000($ 15,971) per year in the top tech companies mentioned above. The salary of a Beginner Full-Stack developer in India starts at Rs. 4,50,000 ($ 5989) per year in service companies to Rs. 12,00,000($ 15,971) per year in top tech companies.The salary for an entry level Frontend developer in USA is $ 59,213 per year and for an entry level Full stack developer is $ 61,042 per year.Below are some sources for salaries:Front End vs Back End Developer SalaryFull Stack Developer SalariesWeb-developer SalariesTop regions where there is demandThere are plenty of remote and freelancing opportunities in web-development across the world. The two countries with most developers and top tech companies are USA and India. Silicon Valley, which is the San Francisco Bay Area, in Northern California, USA is the hub of technology companies.  The top city in India to start a developer job is the Silicon Valley of India – Bengaluru. The number of jobs is more than all the other cities combined and it also has a very good startup ecosystem. Almost all the big technology companies mentioned earlier and top Indian service companies are located in the city. After Bengaluru, the city where the greatest number of technology jobs are based in Hyderabad, followed by Chennai and then Pune.Entry PointsThe demand for web-developers is high and anyone with a passion for creating apps can become a web-developer. An Engineering degree is not mandatory to land a job as a web developer.  The most in-demand skill today and for the next 5 years is React and its ecosystem. So, if you know HTML, CSS, JavaScript and React, it is impossible to not get a job.Career PathwayMost people start as an intern Front-end developer or Intern Full-Stack developer and in many cases Intern Backend developer. Many companies directly hire junior Frontend/Backend/Full-stack developers.After that, the next step is the role of Senior Frontend/Backend/Full-stack developers. Many Frontend and Backend developers become full stack developers at this level, by learning additional technologies. Senior resources in Frontend/Backend/Full-stack can then go on to assume Team Lead roles. These people manage small teams in addition to being individual contributors.After this a professional can become a Project manager, whose main responsibility is managing the team. Another role is that of Technical Project Manager, who manages the team and also has hands-on knowledge in Technology. The last role at this level is that of a Software Architect, who handles and designs big projects and has to look at every aspect of the technology to create the enterprise app. Generally Full-stack developers are preferred in this role, as they need to know all technologies.The highest career milestone is CTO or Chief Technology Officer, who handles all the technology teams and makes all technology decisions in a Technology company.Job SpecializationThere are some Full stack development specializations which I see nowadays in the industry. Full-stack developers who work with React in the Frontend and Java in the Backend are in great demand. Similarly, developers who work with Angular in the Frontend and .NET in the backend are in great demand.How KnowledgeHut can helpAll these free resources are a great place to start your Front-end or Full-Stack journey. Besides these there are many other free resources on the internet, but they may not be organized and may not have a structured approach.This is where KnowledgeHut can make a difference and serve as a one-stop-shop alternative with its comprehensive Instructor-led live classes. The courses are taught by industry experts and are perfect for aspirants who wish to become Frontend or FullStack developers.Links for some of the popular courses & bootcamps by KnowledgeHut are appended below-Project-Based Full-Stack Development BootcampFront-End Development BootcampBack-End Development BootcampHTML5 & CSS3 TrainingHTML5 CSS3 & JavaScript TrainingReact TrainingNode.js Certification CourseDevOps TrainingConclusionThis completes our article on the Full stack developer journey by combining both the Frontend and backend roadmap. There are many people who become backend developers first by working on languages like Java and then go on to learn React to become full-stack developers.Again, many developers learn front-end development first with frameworks like React and then become full-stack developers by learning Node.JS. This path is easier for developers because both React and Node.JS use the same language which is JavaScript.We hope you have found this blog useful, and can now take the right path to become a full-stack developer. Good luck on your learning journey!
6572
How to Become a Successful Full Stack Web Develope...

The ResponsibilitiesFull-stack developer roles are... Read More

Angular: Add Service to Module Code Example

What are services in an Angular app?Services is a general term broadly categorized as values, functions, or features that our application may need. Services are made to reuse codes designed for a purpose.Angular services differentiate an element from its service so that the services can be re-used. This increases the modularity of the Angular application. Service in an Angular App can be almost anything, it can be an element, a component, or it can be a module used for some specific purpose.All services in Angular App are classes with a definite purpose. It serves a purpose and serves it well.Some of the very well-known services include:Logging Service: Used for logging in, logging out.Data Fetching: Fetching Data and representing it in a formatted way.Data Service: Fetching and receiving Data.Message Bus: Used for communicating through a set of shared interfaces.Tax Calculator: Calculating Tax by synchronizing with the current Law system.EMI calculator: Easy Monthly Instalment Calculator, mainly used in calculations related to Loan. Application Configuration: Common configuration throughout the application support.ReusabilityReusability is very important when building large-scale applications. Classes built for a common purpose should not be required to be built again and again. This even causes misinterpretation of certain important classes. We need to implement separation of concerns to segregate different classes used for different purposes. This can be achieved by Angular services.In Angular 13 Framework, the services are those objects that get instantiated a maximum of one time during the entire lifetime of any Angular application or Angular module.All the Angular Services contain many methods that maintain data throughout the lifetime of an application. Thus, it has become a medium to share various responsibilities within one or multiple components.Services and Dependency InjectionServices provide us with injectable features. The Angular App provides us the decorator @Injectable for creating a service. Classes thereby created can be injected into any other module or component by calling it through service provider modules.The two-step process for creating a service in Angular application is:Use @Injectable decorator to create a class.Use Dependency Injection to inject the class or register the class with the service provider.In Angular 13 Framework, one of the ways of performing DI – Dependency Injection is by using Service injection. Dependencies are services or objects of a class that helps in performing its function. Dependency injection or DI are design patterns in which a class demands dependencies from external sources rather than constructing them.Building and providing servicesLet us build a service for keeping Records of Employees:Step 1: Install Node.js:Angular requires Node.js version 14.X.X or later. You can download it from Nodejs.org.The latest Version is : node-v16.13.1-x64Install node.js once downloaded:Once you have installed Node.js on your system, open node.js command prompt.To check your version, run node -v in a terminal/console window.Step 2: Use npm to Install Angular CLIUse the following command to install Angular CLInpm install -g @angular/cli Ornpm install -g @angular/cli@latestOrJust go to Angular CLI official website https://cli.angular.io/You will see the whole cli command to create an Angular app. You need to run the first command to install Angular CLI. These steps are same for Windows and Mac.To check Node and Angular CLI version, use ng --version command.Step 3: Create an app called ngApp4ServiceSyntax:ng new app_nameC:\>ng new ngApp4Service It asks forWould you like to add Angular routing? YesWhich stylesheet format would you like to use?> CSS….Step 4: Generate Service via CLI:Syntax for creating a service:ng generate service [options]ng g service [options]Let us generate the required service: here we are going to create “Employee” Service.Go to the app folder and install the required service: “Employee”:Step 5: Edit the service ts file:Service to store Employee Data: employee.service.tsFile name: employee.service.tsimport { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class EmployeeService { public _empList: Array = [];       constructor() {           this._empList = [{name:'Jay Choudhury', city:'Ghaziabad'}];       }        returnEmpData(): Array {           return this._empList;       }        addEmpData(item: any): void {           this._empList.push(item);       }   }Step 6: Import the employee service:Import the service in the app.module.ts:import { BrowserModule } from '@angular/platform-browser';   import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';   import { FormsModule, ReactiveFormsModule } from '@angular/forms';   import { AppComponent } from './app.component';   import { EmployeeService } from './employee.service';   @NgModule({     declarations: [       AppComponent     ],     imports: [       BrowserModule, FormsModule, ReactiveFormsModule     ],     providers: [EmployeeService],     bootstrap: [AppComponent],     schemas: [NO_ERRORS_SCHEMA]   })   export class AppModule { }Step 7: Use the service: Employee:Edit: app.component.tsimport { Component, OnInit } from '@angular/core';   import { EmployeeService } from './employee.service';   @Component({       selector: 'app-root',         templateUrl: './app.component.html',         styleUrls : ['./app.component.css']         })   export class AppComponent implements OnInit {         public model: any = {};         public source: Array;         constructor(public service: EmployeeService) {               this.source = this.service.returnEmpData();               }          ngOnInit(): void { }          public submit(): void {               if (this.validate()) {                   this.service.addEmpData(this.model);                   this.reset();               }           }         public reset(): void {          this.model = {};      }          public validate(): boolean {                  let status: boolean = true;                  if (typeof (this.model.name) === "undefined") {                         alert('Name is Blank');                         status = false;                         return status;                        }                  else if (typeof (this.model.city) === "undefined") {                         alert('City is Blank');                         status = false;                         return status;                        }                  return status;           }    }Edit app.component.html:         Employee Form             Employee Name                       City                                           Employee Details                                         Employee's Name                     City                                   {{item.name}}                         {{item.city}}                                     Step 8: Run to check the service:Go to the app folder:C:\>ng serveRun at localhost:4200/We get the Employee Form.We can add more details for the employee, and see the result.Importance of ServicesAngular App provides Angular Services as re-usable components of the application. It uses @Injectable Decorator for building a Service. A service can be called through multiple components as a common element and shared for various purposes. This helps in avoiding repetitive work and improves the speed of app development.
4986
Angular: Add Service to Module Code Example

What are services in an Angular app?Services is ... Read More

How to Create Libraries for Angular Apps?

In this Article we are going to talk about Libraries in Angular 13.  We will be covering the following topics in the blog:Reusability with Angular Libraries:Here we introduce the idea of reusability and the concept of building libraries in Angular apps.Creating a New Library:Here we will walk through steps to generate a new library using the ng generate.Rebuilding an app using libraries:Here we walk through an example where we convert a portion of an existing Angular 13 app to a library and then use it.Publishing your library:Here we walk through publishing a library, keeping Ivy related features, version compatibility etc. in mind.SummaryAbout Angular 13:Angular 13 is the latest version of the Angular family. Angular applications are basically designed for Single Page Applications, where all controls are required in single-page architecture. Angular is an application-based design framework, which provides the Cross-Platform development environment for creating the most sophisticated Single Page Applications (SPAs). These SPAs are efficient enough for giving us a component to view the model environment, making it an MVC or MVVM application.Angular provides a Progressive Web App architecture, which means that an application made in Angular gives us an App-like experience with high-performance. Angular has zero-step installation, making its up-gradation using modern web capabilities possible, even if offline. Angular has the capability of making a cross-platform Desktop App that can be created using MAC, Windows, or Linux OS using the same Angular methods. Angular can be rendered in Node.js, Microsoft .Net, PHP, and many other servers by giving the output in HTML-CSS format. This even optimizes the App for SEO. Angular framework turns our templates into JavaScript Virtual machine codes which are highly optimized. With Angular CLI, the Command-Line tools, we can build and deploy Apps faster than ever before. Angular uses Karma for unit tests and Protractor for scenario tests making the applications made in Angular more stable.According to angular.io, some of the features worth mentioning are:1. DEVELOP ACROSS ALL PLATFORMSLearn one way to build applications with Angular and reuse your code and abilities to build apps for any deployment target. For web, mobile web, native mobile, and native desktop.  2. SPEED & PERFORMANCEAchieve the maximum speed possible on the Web Platform today, and take it further, via Web Workers and server-side rendering.Angular puts you in control over scalability. Meet huge data requirements by building data models on RxJS, Immutable.js, or another push model.3. INCREDIBLE TOOLINGBuild features quickly with simple, declarative templates. Extend the template language with your own components and use a wide array of existing components.  Get immediate Angular-specific help and feedback with nearly every IDE and editor. All this comes together so you can focus on building amazing apps rather than trying to make the code work.4. LOVED BY MILLIONSFrom prototype through global deployment, Angular delivers the productivity and scalable infrastructure that supports Google's largest applications.Reusability with Angular LibrariesA Library in Angular App is a reusable code that determines Angular components, services, or projects meant to be called by other projects. These projects are like a normal application. The only difference these have over Angular applications is that these projects cannot execute on their own. We need to import these projects to use them.We make libraries to solve some generic issues like the unified user interface or data presentation or data entry issues. Angular developers create these libraries for such general-purpose solutions. Later these libraries can be adapted in different applications for re-usage of the solution.An Angular Library can be built as an Angular application, later published as an npm package. These npm packages can be shared with different applications deploying the libraries.Libraries can be published as third-party libraries or Angular Team libraries.Some of the examples are:ReactiveFormsModule from the @angular/forms library is used to add reactive forms to an Angular app. We add this library package by using ng add @angular/forms and then importing the ReactiveFormsModule from the @angular/forms.To turn an Angular App into a progressive application we add the service worker library. This turns our code into a Progressive Web App (PWA).A very large and general-purpose library is the Angular Material. It is a library or a component that helps in constructing attractive, sophisticated, functional web app and reusable, and adaptable UI components.Creating a New LibraryLet us build a Library in Angular App step-by-step:Step 1: Install Node.js:Angular requires Node.js version 14.X.X or later. You can download it from Nodejs.org.Latest Version is: node-v16.13.1-x64Install node.js once downloaded:Once you have installed Node.js on your system, open node.js command prompt.To check your version, run node -v in a terminal/console window.Step 2: Use npm to Install Angular CLIUse the following command to install Angular CLInpm install -g @angular/cli Ornpm install -g @angular/cli@latestOrJust go to Angular CLI official website Angular.io.You will see the whole cli command to create an Angular app. You need to run the first command to install Angular CLI. These steps are the same for Windows and Mac.To check Node and Angular CLI version, use ng --version command.Step 3: Create an app called ngApp4LibrarySyntax:ng new app_name C:\>ng new ngApp4Library It asks forWould you like to add Angular routing? YesWhich stylesheet format would you like to use?> CSS ….Step 4: Generate Library via CLI:Syntax: for creating a Libraryng generate library [options] ng g library [options]Let us generate the required library: here we are going to create “my-lib” Library.Go to the app folder and install the required Library: “my-lib”:ng generate library my-lbThis will create a library project my-lib into our ngApp4library project.my-lib Library will contain library module, services, components, etc.Step 5: Edit the library ts file: Give a functionality to your libraryAs you can see our library has its own module, service, and component. We can add more components, services, directives, pipes, and modules as per our needs.The Library file that we need to edit is my-lib. It appears in the folder C:\Users\ISHU\Desktop -> ngApp4Library -> projects -> my-lib -> src -> lib. The file to be edited is:  my-lib.component.tsAdd the following code:import { Component, OnInit } from '@angular/core'; @Component({   selector: 'lib-my-lib',   template: `       Username:           Password:             Login   `,   styles: [   ] }) export class MyLibComponent implements OnInit {   constructor() { }   ngOnInit(): void {   } }Rebuilding an app using librariesBefore consuming the library, we need to build an Angular library.Here we will build the library for local (same application) usage.Then we will re-build the library for global (any application) usage.Creating a New Library1. Build the library and consume it in the same application:To build the library, we run the following command:ng build Here our library name is my-lib, thus the command we need is: ng build my-libThe command will generate the library dist folderNext step is to implement the library into our current project: ngApp4Library:For this step, we need to import this library in our main app (ngApp4Library).In app.module.ts import my-lib library module as shown: app.module.ts:import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { MyLibModule } from 'my-lib'; @NgModule({   declarations: [     AppComponent   ],   imports: [     BrowserModule,     AppRoutingModule,     MyLibModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { }Now, we simply add the my-lib library in the HTML file.Please note that the selector for the library used here is: lib-my-libTo know about the selector (lib-my-lib), we can check the file: ngApp4Library -> projects -> my-lib -> src -> lib->  my-lib.component.tsNow open and edit: app.component.html from the main App folder: ngApp4Library\src\app\ app.component.html: Now we can start our application from the Node.js command line as: ng serveOpen the favourite browser and type the default Angular app URL to check the output: localhost:4200/.2. Rebuild the library and consume it from some other application:We go through the following steps to implement the Library into another project:Step 1:To Re-build the library, we run the following command:ng build Here our library name is my-lib, thus the command we need is: ng build my-libThe command will generate the library dist folderNow, create a new Angular application: ngAppClient in a new command window. We need to let the library application run.ng new ngAppClientNow from the build, check the paths destined as “to”Here, the “to” part gives us the value: C:\ Users\ ISHU\ Desktop\ ngApp4Library\ dist\ my-libSo, now copy this path: “C:\ Users\ ISHU\ Desktop\ ngApp4Library\ dist\ my-lib”Next, we open the terminal of ngAppClient project and install this library with the following command into the ngAppClient project: npm i C:\ Users\ ISHU\ Desktop\ ngApp4Library\ dist\ my-libC:\Users\ISHU\Desktop>cd ngAppClientC:\Users\ISHU\Desktop\ngAppClient>npm iC:\Users\ISHU\Desktop\ngApp4Library\dist\my-libAfter installation of the library in the client application, we can import the library into the app.module.ts of the client app. After importing the library module, we can easily use those services, components, etc.To use the library:Open Client Project -> app.module.ts file and edit it to add the library:App.module.ts:import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { MyLibModule } from 'my-lib'; @NgModule({   declarations: [     AppComponent   ],   imports: [     BrowserModule,     AppRoutingModule,     MyLibModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { } Now, we simply add the my-lib library in the client project app.component.html file.Please note that the selector for the library used here is: lib-my-libTo know about the selector (lib-my-lib), we can check the file: ngApp4Library -> projects -> my-lib -> src -> lib->  my-lib.component.tsAnd then open and edit: app.component.html from the client App folder: ngAppClient\ src\ app\ app.component.html: We can now start our client application for the Node.js command line as:ng serve.In case the Library project is running in the default port, 4200, we can change the port of the client app to 5200 by the following command:ng serve --port 5200Open the favorite browser and type the default Angular app URL to check the output: localhost:5200/.Publishing your libraryWe publish the library to make the library available on npm. For publishing the library, all we need to do is create a production build, and then run npm publish command from the library project’s dist directory.The Syntax is as follows:ng build --prod cd dist/ npm publishHere the Library project is ngApp4library, and the library is my-lib, so we run the following commands:ng build my-lib --prod cd dist/my-lib npm publishIf you have not published anything before, you will need to create an npm account first and log in into your npm account and then publish your library.The Purpose of Angular LibrariesAngular Libraries are very useful in case we want to re-use components, services, modules, etc. in our application. We just need to add the published library in our project, and that’s it, the components, modules, services, are all ready to be used in the application.To create a library, we generate it by “ng generate” command, built it by “ng build” command, publish by “npm publish” command. To use a library we install it by “ng i “ command.
5703
How to Create Libraries for Angular Apps?

In this Article we are going to talk about Librari... Read More