1. はじめに
- ローカル環境にGraphQLサーバを構築したい
- IDEはVSCodeを使用したい
2. 開発環境
- Apollo Server 5.4.0
- GraphQl 16.13.0
- Node.js 24.12.0
- Visual Studio Code
- JavaScript
- Windows 11
3. GrapQLサーバ用のプロジェクトの作成
3.1. プロジェクトの作成
- 任意のフォルダで新しいプロジェクト用のディレクトリを作成する
mkdir graphql-server-example
cd graphql-server-example
3.2. Visual Studio Codeの起動
code .
3.3. Node.jsプロジェクトの初期化
npm init --yes && npm pkg set type="module"
3.4. Apollo ServerとGraphQLのインストール
npm install @apollo/server graphql graphql-tag
4. package.jsonの編集
- JavaScriptファイルをESモジュールとして読み込むため、package.jsonのtypeフィールドをmoduleに設定する
- "scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
- },
+ "scripts": {
+ "start": "node index.js"
+ },
5. index.jsの作成
- srcフォルダ内にindex.jsを作成し、スキーマ、データ、リゾルバを定義する
src/index.js
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";
import { gql } from "graphql-tag";
// GraphQL schema definition
const typeDefs = gql`
type Query {
hello: String
}
`;
// Resolvers define
const resolvers = {
Query: {
hello: () => "Hello, world!",
},
};
// Create an instance of ApolloServer
const server = new ApolloServer({ typeDefs, resolvers });
// Start the server
startStandaloneServer(server).then(({ url }) => {
console.log(`Server ready at ${url}`);
});
6. サーバの起動
node .\src\index.js
7. クエリの実行
- ブラウザで http://localhost:4000 にアクセスし、GraphQL Playgroundを開く
- ExampleQueryボタンをクリックして、レスポンスが帰ってくることを確認する
8. 参考文献



