GraphQL Server
Now that you have a GraphQL schema, and you understand the concept of GraphQL schema and a GraphQL query, it’s time to create a real GraphQL server.
You are going to use the HTTP protocol to serve the GraphQL server, but note that there are other options for serving GraphQL - you can use WebSocket, SSE (Server-Sent Events) and basically any network transport protocol that you wish! (You can find a list of transport implementations at the end of this page)
Creating a GraphQL HTTP Server with Yoga
In this tutorial, we will be using GraphQL Yoga for building our Node.js GraphQL HTTP server.
Yoga can also run on other platforms, such as Cloudflare Workers, AWS Lambda, or Deno. We recommend checking out the integrations section in our documentation after finishing the tutorial.
You’ll need the graphql-yoga
package available in your project (if you have not yet installed in
the last step), so install it using the following command:
npm i --save-exact graphql-yoga@5.x.x
Now, update src/main.ts
to create a simple GraphQL HTTP server on port 4000
:
import { createServer } from 'node:http'
import { createYoga } from 'graphql-yoga'
import { schema } from './schema'
function main() {
const yoga = createYoga({ schema })
const server = createServer(yoga)
server.listen(4000, () => {
console.info('Server is running on http://localhost:4000/graphql')
})
}
main()
Now, try to run your server again with
npm run dev
open your browser and navigate to http://localhost:4000/graphql
.
Type in the following operation in the left editor section and press the Play
button for executing
the operation against the GraphQL server.
query {
hello
}
Unsurprisingly, the result looks like the following:
{ "data": { "hello": "Hello World!" } }
Of course, it is also possible to send requests to the service without GraphiQL, e.g. by using
curl
.
In another terminal window, run the following command in order to execute the same query operation.
curl -X POST http://localhost:4000/graphql -H "Content-type: application/json" --data-raw '{"query": "query { hello }"}'
Oh wonder, the result looks like the following:
{ "data": { "hello": "Hello World!" } }