Building a GraphQL API with Phoenix and React
In this tutorial, we’ll explore how to create a GraphQL API using Phoenix and connect it to a React app. We’ll use schemas and contexts to build our business logic and Docker to spin up PostgreSQL and Adminer instantly.
Prerequisites
- Basic understanding of JavaScript, React, and Docker
- Familiarity with Elixir syntax
- Knowledge of client-server interaction
Environment Setup
To set up our environment, we need to install the following:
- Elixir: a functional, concurrent programming language
- Hex: a package manager for running Phoenix apps and installing dependencies
- Docker: a containerization tool used to package and run apps in an isolated environment
- Docker Compose: a tool for spinning up multiple Docker containers that communicate through a bridge network
Installing Dependencies
Run the following commands to install the required dependencies:
“`bash
Install Elixir
sudo apt-get update
sudo apt-get install elixir
Install Hex
mix local.hex
Install Docker and Docker Compose
sudo apt-get install docker.io
sudo apt-get install docker-compose
“`
Phoenix Application Setup
Create a new Phoenix application using the following command:
bash
mix phx.new booklist --no-html
Installing Absinthe and Absinthe Plug
Add the following dependencies to your mix.exs
file:
elixir
defp deps do
[
{:absinthe, "~> 1.5"},
{:absinthe_plug, "~> 1.5"}
]
end
Run the following command to install the dependencies:
bash
mix deps.get
Configuring Routes
Add the following routes to your router.ex
file:
“`elixir
defmodule BooklistWeb.Router do
use BooklistWeb, :router
scope “/gql” do
pipe_through :api
forward "/", Absinthe.Plug,
schema: BooklistWeb.Schema
end
scope “/” do
pipe_through :browser
get "/", BooklistWeb.PageController, :index
end
end
“`
Creating a Schema
Create a new file called schema.ex
in the lib/booklist_web
directory:
“`elixir
defmodule BooklistWeb.Schema do
use Absinthe.Schema
query do
field :books, list_of(:book)
end
object :book do
field :title, :string
field :author, :string
end
end
“`
Creating a React App
Create a new React app using the following command:
bash
npx create-react-app my-gql-project
Installing Apollo Client
Install the Apollo Client using the following command:
bash
npm install @apollo/client graphql
Connecting to the GraphQL API
Create a new file called client.js
in the src
directory:
“`javascript
import { ApolloClient, InMemoryCache } from ‘@apollo/client’;
const client = new ApolloClient({
uri: ‘http://localhost:4000/gql’,
cache: new InMemoryCache(),
});
export default client;
“`
Using the Apollo Client in the React App
Create a new file called App.js
in the src
directory:
“`javascript
import React from ‘react’;
import { ApolloProvider } from ‘@apollo/client’;
import client from ‘./client’;
function App() {
return (
My GQL Project