12/04/2026 18:18pm

EP.33 Using GraphQL with WebSocket in Go to Build Real-Time APIs
#GraphQL
#WebSocket
#Go
#Golang
#GraphQL Subscriptions
#Real-Time API
#GraphQL API
#WebSocket API
#API Development
#Go Programming
GraphQL and WebSocket – Why Use Them Together?
GraphQL is an API Query Language that allows clients to retrieve only the data they need. WebSocket is a protocol that enables Full-Duplex or Real-Time communication. When combined, we can create APIs that support real-time data updates using GraphQL Subscriptions.
Using GraphQL Subscriptions with WebSocket
GraphQL Subscriptions allow clients to "subscribe" to data changes, and the server will automatically push updates to the client when the data changes.
Example GraphQL Subscription:
subscription {
newMessage {
id
content
sender
}
}When a new message (newMessage) is added, the server sends the updated data to the client in real-time.
Example Code for Using WebSocket with GraphQL in Go
1. Installing Required Libraries
go get github.com/99designs/gqlgen
go get github.com/gorilla/websocket2. Creating GraphQL Schema
File: schema.graphql
type Query {
messages: [Message!]!
}
type Subscription {
messageAdded: Message!
}
type Message {
id: ID!
content: String!
sender: String!
}3. Implementing GraphQL Resolver
File: resolver.go
package main
import (
"context"
"fmt"
"sync"
)
type Message struct {
ID string
Content string
Sender string
}
type Resolver struct {
mu sync.Mutex
messages []Message
subscribers map[string]chan Message
}
func NewResolver() *Resolver {
return &Resolver{
messages: []Message{},
subscribers: make(map[string]chan Message),
}
}
func (r *Resolver) Subscription_messageAdded(ctx context.Context) (<-chan Message, error) {
id := fmt.Sprintf("%d", len(r.subscribers))
r.mu.Lock()
ch := make(chan Message)
r.subscribers[id] = ch
r.mu.Unlock()
go func() {
<-ctx.Done()
r.mu.Lock()
delete(r.subscribers, id)
close(ch)
r.mu.Unlock()
}()
return ch, nil
}Challenge!
Try building a real-time notification system using GraphQL Subscriptions and WebSocket to notify users when new messages arrive!
Next Episode
In EP.34, we will explore how to create a fully functional chat system using GraphQL and WebSocket to support real-time communication! Stay tuned 🚀