GraphQL between Angular and Symfony

Slimen Arnaout
4 min readMay 6, 2020

--

Since the last few years GraphQL has been growing in popularity among developers and a lot of companies started adopting this “Query Language” to build their APIs, and became something very important to learn it and use it, and don’t worry https://www.howtographql.com/ is your favorite place to get started with it.

What is GraphQl ?

As a short answer: it’s a query language for APIs. Think of it like SQL for databases.

SQL is a query language for database that allows you to get exactly what you want from the database (columns, rows count, etc..). You get what you want and how much of it.

Now GraphQL in the other hands behaves the same way, you simply send a query to a single endpoint (keep that in mind “single endpoint”) of the server and ask him the data you want to get and the amount of it.

Unlike REST where you have to write and prepare an endpoint (URL) for each request you want, example:

let’s say you have a page where you want to display a specific author with ID 1 and his 5 last blogs

Using REST you have 2 options:

  1. You write an API (/api/author/1/with-last-5-blogs) to get the author and his 5 last blogs together and this API will be used only for this particular page (which is a very bad solution)

2. You run two requests, the first one to get the author (/api/authors/1) and the second one to get his blogs (/api/authohrs/1/blogs)

Now using GraphQL you can be flexible as much as you want and in this case you send a query that tells the server to return the author with ID 1 and his last 5 blogs like so:

{
author(id: "1"){
blogs(last: 5){
edges{
node{
title
}
}
}
}
}

and BOOM, like a boss! 😎

as you can see we get the author with his last 5 blogs, and from the blogs we get only the title of each one.

Now let’s see how to add GraphQL to Symfony and Angular and see how they work together shall we ? 😁.

Add GraphQL to Symfony:

Here I’m going to use API Platfrom since we can easly add GraphQL endpoint with it, so let’s get started:

  1. create a new Symfony project
$ composer create symfony/skeleton graphql-api

2. add needed dependencies

$ cd graphql-api
$ composer req orm # add doctrine ORM
$ composer req maker # to create entities, controllers, etc...
$ composer req api # API Platform
$ composer req webonyx/graphql-php # graphql dependency

now GraphQL’s endpoint will be available at http://path/to/project/api/grahql.

3. Create 2 entities Author and Blog

$ php bin/console make:entity # create entities and add fields

4. add @ApiResource() to both entities to expose them

/**
*
@ApiResource()
*
@ORM\Entity(repositoryClass="App\Repository\AuthorRepository")
*/
class Author
{...}
/**
*
@ApiResource()
*
@ORM\Entity(repositoryClass="App\Repository\BlogRepository")
*/
class Blog
{...}

And that’s it for symfony side, if you open the borwser and navigate to “http://path/to/project/api/graphql” you will find the GraphiQL IDE where you can play a bit with GraphQL

GrahiQL IDE

5. Prepare .env file

$ composer dump-env dev # this will generate .env.local.php file where you can define your database config
================================================================
# .env.local.php file
<?php

// This file was generated by running "composer dump-env dev"

return array (
'APP_ENV' => 'dev',
'APP_SECRET' => 'c3921fd23875ac47abca6b24bc3521ad',
// here I'm going to use sqlite database to speed things up
'DATABASE_URL' => 'sqlite:///%kernel.project_dir%/var/data.db',
'CORS_ALLOW_ORIGIN' => '^https?://(localhost|127\\.0\\.0\\.1)(:[0-9]+)?$',
);

6. Prepare your database

$ php bin/console d:d:c # create database
$ php bin/console d:s:u --force # update database schema

Add GraphQL to Angular

For Angular we will use apollo-angular dependency.

  1. create new Angular project
ng new graphql-client

2. add apollo-angular dependency

ng add apollo-angular

3. add GraphQL endpoint to Angular, so open the file src/app/graphql.module.ts and set the endpoint value for the variable uri like so:

import {NgModule} from '@angular/core';import {ApolloModule, APOLLO_OPTIONS} from 'apollo-angular';import {HttpLinkModule, HttpLink} from 'apollo-angular-link-http';import {InMemoryCache} from 'apollo-cache-inmemory';const uri = 'http://path/to/project/api/graphql'; // <-- add the URL of the GraphQL server here

Now everything is ready and our Angular app can communicate with Symfony using GraphQL, so let’s give it a try.

Add this code to your app.component.tsfile

app.component.ts

and add this to your app.component.html file:

Now we are able to get list of blogs and their authors using GraphQL

To add new Author we can use mutation like so:

mutation CreateAuthor{
createAuthor(input:{
firstName: "Jack",
lastName: "Preacher"
}){
author{
id
lastName
firstName
}
}
}

Here we create a new Author and in return we get his id, lastName and firstName as result.

For more advanced usage of GraphQL with API Platform take a look at this page: https://api-platform.com/docs/core/graphql/#graphql-support

That’s it, I hope you find this useful and thanks for reading 🙂

--

--

Slimen Arnaout

Senior Software Engineer @MaibornWolff, I help with software renovation and cloud migration, love soccer and video games .. and no, I don’t like cooking