I had recently started working on a new project at work, which have GraphQL with React and it queries the GraphQL server using Apollo Client.
But i wanted to build something quick to refresh the concept and i found a free course on YouTube from another of my favorite teacher Brad Traversy and decided to follow it to make this app.
We will be building an web-app to show all the launches and other data from my favorite company SpaceX. It will be built using the public APIs provided by them.
So, open the terminal and goto an empty folder and do npm init. Enter in most of the case, except in some of them enter values as in screenshot below.
Once, you type yes and press enter above a package.json file will be created in the folder.
Next, we will do npm install of the required packages from the terminal.
Now, also install the famous nodemon package as dev dependency so that we don’t have to restart our server after every change.
Now, let’s open the folder in VSCode and edit the package.json to include the scripts to start the server.
Next, we will create the file server.js in the root directory and add this content in it. It is a express code and we are calling a common endpoint called /graphql in it. This is where GraphQL is different then NodeJs and we call only one endpoint.
We will create our schema.js . The content will replicate from what we need from spacex API. The docs are here.
This is what the GET request for launches will return us.
We are using only some of the fields out of the many things returned by SpaceX launches API in schema.js and they are flight_number, mission_name, launch_year, launch_date_local, launch_success
One thing to notice is that since rocket is an Object in the API, we are making it into a different type and then using rocket_id, rocket_name and rocket_type in it.
Next, we will add the root query to schema.js. Here we have to hit the API endpoint through axios to get the data.
Now, in terminal run nodemon server.js to start the server.
Next, we can run the query in GraphiQL to get the data. We can get all the fields or some of the fields and that the benefit of GraphQL over REST.
Next, we will also create the code for a single launch. As per the docs, we need to pass flight_number in it.
Now, the below GraphQL query will show the data for single launch.
Next, we will also add code to get data for rockets and single rocket. But, let’s first update two more fields wikipedia and description in RocketType.
Next, we will add the code to get rockets and rocket from it’s endpoint using axios.
Next, we will use the below query in Graphiql to get our data.