{"id":26470169,"url":"https://github.com/graphql-hive/sofa","last_synced_at":"2025-10-04T14:58:18.466Z","repository":{"id":37601872,"uuid":"160542305","full_name":"graphql-hive/SOFA","owner":"graphql-hive","description":"The best way to create REST APIs - Generate RESTful APIs from your GraphQL Server","archived":false,"fork":false,"pushed_at":"2025-09-25T23:17:04.000Z","size":9194,"stargazers_count":1107,"open_issues_count":36,"forks_count":92,"subscribers_count":14,"default_branch":"master","last_synced_at":"2025-09-26T00:44:15.967Z","etag":null,"topics":["api","graphql","openapi","rest","swagger"],"latest_commit_sha":null,"homepage":"https://www.the-guild.dev/graphql/sofa-api","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/graphql-hive.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2018-12-05T15:53:57.000Z","updated_at":"2025-09-25T23:17:08.000Z","dependencies_parsed_at":"2023-02-19T06:15:40.056Z","dependency_job_id":"6dc61419-3959-49b9-966a-92538447a807","html_url":"https://github.com/graphql-hive/SOFA","commit_stats":{"total_commits":1513,"total_committers":49,"mean_commits":"30.877551020408163","dds":0.5446133509583608,"last_synced_commit":"d760c60c7cf22a5fd4c8e373482c29944bbc28d5"},"previous_names":["graphql-hive/sofa","urigo/sofa"],"tags_count":27,"template":false,"template_full_name":null,"purl":"pkg:github/graphql-hive/SOFA","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-hive%2FSOFA","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-hive%2FSOFA/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-hive%2FSOFA/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-hive%2FSOFA/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/graphql-hive","download_url":"https://codeload.github.com/graphql-hive/SOFA/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/graphql-hive%2FSOFA/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":278328167,"owners_count":25968900,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-04T02:00:05.491Z","response_time":63,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","graphql","openapi","rest","swagger"],"created_at":"2025-03-19T17:30:40.335Z","updated_at":"2025-10-04T14:58:18.446Z","avatar_url":"https://github.com/graphql-hive.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![GraphQLConf 2024 Banner: September 10-12, San Francisco. Hosted by the GraphQL Foundation](https://github.com/user-attachments/assets/bdb8cd5d-5186-4ece-b06b-b00a499b7868)](https://graphql.org/conf/2024/?utm_source=github\u0026utm_medium=sofa\u0026utm_campaign=readme)\n\n\u003c!-- Uncomment when we remove GraphQL Conf banner --\u003e\n\u003c!-- [![sofa](https://user-images.githubusercontent.com/25294569/63839869-bfac8300-c988-11e9-978e-6b6c16c350de.gif)](https://www.sofa-api.com) --\u003e\n\n[![npm version](https://badge.fury.io/js/sofa-api.svg)](https://npmjs.com/package/sofa-api)\n[![Discord Chat](https://img.shields.io/discord/625400653321076807)](https://discord.gg/xud7bH9)\n[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)\n[![renovate-app badge](https://img.shields.io/badge/renovate-app-blue.svg)](https://renovateapp.com/)\n\nThe best way to create REST APIs (is GraphQL).\n\n## Installation\n\n    yarn add sofa-api\n    # or\n    npm install sofa-api\n\n## Getting Started\n\nHere's complete example with no dependency on frameworks, but also integratable with any of them:\n\n```js\nimport http from 'http';\nimport getStream from 'get-stream';\nimport { useSofa } from 'sofa-api';\n\nconst server = http.createServer(\n  useSofa({\n    basePath: '/api',\n    schema,\n  })\n);\n```\n\nAnother example with builtin express-like frameworks support\n\n```js\nimport { useSofa } from 'sofa-api';\nimport express from 'express';\n\nconst app = express();\n\napp.use(\n  '/api',\n  useSofa({\n    basePath: '/api',\n    schema,\n  })\n);\n\n// GET /api/users\n// GET /api/messages\n```\n\n## How it works\n\nSofa takes your GraphQL Schema, looks for available queries, mutations and subscriptions and turns all of that into REST API.\n\nGiven the following schema:\n\n```graphql\ntype Chat {\n  id: ID\n  text: String\n}\n\ntype Query {\n  chat(id: ID): Chat\n  chats: [Chat]\n  me: Chat\n  recentChats: [Chat]\n}\n```\n\nRoutes that are being generated:\n\n```\nGET /chat/:id\nGET /chats\nGET /me\nGET /recent-chats\n```\n\n### Nested data and idea behind Models\n\nSofa treats some types differently than others, those are called Models.\n\nThe idea behind Models is to not expose full objects in every response, especially if it's a nested, not first-level data.\n\nFor example, when fetching a list of chats you don't want to include all messages in the response, you want them to be just IDs (or links). Those messages would have to have their own endpoint. We call this type of data, a Model. In REST you probably call them Resources.\n\nIn order to treat particular types as Models you need to provide two queries, one that exposes a list (with no non-optional arguments) and the other to fetch a single entity (id field as an argument). The model itself has to have an `id` field. Those are the only requirements.\n\n```graphql\n# Message is treated as a Model\ntype Query {\n  messages: [Message]\n  message(id: ID): Message\n}\n\ntype Message {\n  id: ID\n  # other fields ...\n}\n```\n\n### Provide a Context\n\nIn order for Sofa to resolve operations based on a Context, you need te be able to provide some. Here's how you do it:\n\n```ts\napi.use(\n  '/api',\n  useSofa({\n    basePath: '/api',\n    schema,\n    async context({ req }) {\n      return {\n        req,\n        ...yourContext,\n      };\n    },\n  })\n);\n```\n\n\u003e You can pass a plain object or a function.\n\n### Use full responses instead of IDs\n\nThere are some cases where sending a full object makes more sense than passing only the ID. Sofa allows you to easily define where to ignore the default behavior:\n\n```ts\napi.use(\n  '/api',\n  useSofa({\n    basePath: '/api',\n    schema,\n    ignore: ['Message.author'],\n  })\n);\n```\n\nWhenever Sofa tries to resolve an author of a message, instead of exposing an ID it will pass whole data.\n\n\u003e Pattern is easy: `Type.field` or `Type`\n\n### Customize endpoint's HTTP Method, path and response status code\n\nSofa allows you to cutomize the http method, path and response status. For example, in case you need `POST` instead of `GET` method in one of your query, you do the following:\n\n```typescript\napi.use(\n  '/api',\n  useSofa({\n    schema,\n    routes: {\n      'Query.feed': { method: 'POST' },\n    },\n  })\n);\n```\n\nWhen Sofa tries to define a route for `feed` of `Query`, instead of exposing it under `GET` (default for Query type) it will use `POST` method.\n\n\u003e Pattern is easy: `Type.field` where `Type` is your query or mutation type.\n\nYou can also specify `path` with dynamic params support (for example `/feed/:offset/:limit`) and `responseStatus`.\n\n### Custom depth limit\n\nSofa prevents circular references by default, but only one level deep. In order to change it, set the `depthLimit` option to any number:\n\n```ts\napi.use(\n  '/api',\n  useSofa({\n    basePath: '/api',\n    schema,\n    depthLimit: 2,\n  })\n);\n```\n\n### Custom execute phase\n\nBy default, Sofa uses `graphql` function from `graphql-js` to turn an operation into data but it's very straightforward to pass your own logic. Thanks to that you can even use a remote GraphQL Server (with Fetch or through Apollo Links).\n\n```ts\napi.use(\n  '/api',\n  useSofa({\n    basePath: '/api',\n    schema,\n    async execute(args) {\n      return yourOwnLogicHere(args);\n    },\n  })\n);\n```\n\n### Subscriptions as webhooks\n\nSofa enables you to run GraphQL Subscriptions through WebHooks. It has a special API to start, update and stop a subscription.\n\n- `POST /webhook` - starts a subscription\n- `DELETE /webhook/:id` - stops it\n- `POST /webhook/:id`- updates it\n\n#### Starting a subscription\n\nTo start a new subscription you need to include following data in request's body:\n\n- `subscription` - subscription's name, matches the name in GraphQL Schema\n- `variables` - variables passed to run a subscription (optional)\n- `url` - an url of your webhook receiving endpoint\n\nAfter sending it to `POST /webhook` you're going to get in return a unique ID that is your started subscription's identifier.\n\n```json\n{\n  \"id\": \"SUBSCRIPTION-UNIQUE-ID\"\n}\n```\n\n#### Stoping a subscription\n\nIn order to stop a subscription, you need to pass its id and hit `DELETE /webhook/:id`.\n\n#### Updating a subscription\n\nUpdating a subscription looks very similar to how you start one. Your request's body should contain:\n\n- `variables` - variables passed to run a subscription (optional)\n\nAfter sending it to `POST /webhook/:id` you're going to get in return a new ID:\n\n```json\n{\n  \"id\": \"SUBSCRIPTION-UNIQUE-ID\"\n}\n```\n\n#### Example\n\nGiven the following schema:\n\n```graphql\ntype Subscription {\n  onBook: Book\n}\n```\n\nLet's start a subscription by sending that to `POST /webhook`:\n\n```json\n{\n  \"subscription\": \"onBook\",\n  \"variables\": {},\n  \"url\": \"https://app.com/new-book\"\n}\n```\n\nIn return we get an `id` that we later on use to stop or update subscription:\n\n    DELETE /webhook/:id\n\n### OpenAPI and Swagger\n\nThanks to GraphQL's Type System Sofa is able to generate OpenAPI (Swagger) definitions out of it. Possibilities are endless here. You get all the information you need in order to write your own definitions or create a plugin that follows any specification.\n\n```ts\nimport { useSofa, OpenAPI } from 'sofa-api';\nimport { writeFileSync } from 'fs';\n\nconst openApi = OpenAPI({\n  schema,\n  info: {\n    title: 'Example API',\n    version: '3.0.0',\n  },\n});\n\napp.use(\n  '/api',\n  useSofa({\n    basePath: '/api',\n    schema,\n    onRoute(info) {\n      openApi.addRoute(info, {\n        basePath: '/api',\n      });\n    },\n  })\n);\n\n// writes every recorder route\nwriteFileSync('./swagger.json', JSON.stringify(openApi.get(), null, 2));\n```\n\nOpenAPI (Swagger) with Bearer Authentication\n\n```ts\nimport { useSofa, OpenAPI } from 'sofa-api';\nimport { writeFileSync } from 'fs';\n\nconst openApi = OpenAPI({\n  schema,\n  info: {\n    title: 'Example API',\n    version: '3.0.0',\n  },\n  components: {\n    securitySchemes: {\n      bearerAuth: {\n        type: 'http',\n        scheme: 'bearer',\n        bearerFormat: 'JWT',\n      },\n    },\n  },\n  security: [\n    {\n      bearerAuth: [],\n    },\n  ],\n});\n\napp.use(\n  '/api',\n  useSofa({\n    basePath: '/api',\n    schema,\n    onRoute(info) {\n      openApi.addRoute(info, {\n        basePath: '/api',\n      });\n    },\n  })\n);\n\n// writes every recorder route\nwriteFileSync('./swagger.json', JSON.stringify(openApi.get(), null, 2));\n```\n\nOpenAPI (Swagger) with custom tags, summary and description\n\n```ts\nconst openApi = OpenAPI({\n  schema,\n  info: {\n    title: 'Example API',\n    version: '3.0.0',\n  },\n  tags: [\n    {\n      name: 'Book',\n      description: 'Book related operations',\n    },\n    {\n      name: 'Author',\n      description: 'Author related operations',\n    },\n  ],\n});\n```\n\n```ts\n@Resolver(Book)\nexport class BookResolver {\n  @Query(() =\u003e Book, { description: 'Get book by id' }) // custom summary tag\n  getBookById(@Arg('id', () =\u003e Int) id: number) {\n    return 'book';\n  }\n}\n```\n\n```ts\nconst routes: SofaConfig['routes'] = {\n  'Query.getBookById': {\n    method: 'POST',\n    path: '/book/:id',\n    tags: ['Book'],\n    description: 'This is a custom detailed description for getBookById',\n  },\n};\n\nconst createSofaMiddleware = (\n  schema: GraphQLSchema,\n  openApi: ReturnType\u003ctypeof OpenAPI\u003e,\n  basePath = ''\n): ReturnType\u003ctypeof useSofa\u003e =\u003e {\n  return useSofa({\n    routes,\n    basePath,\n    schema,\n    onRoute(info) {\n      openApi.addRoute(info, { basePath });\n    },\n  });\n};\n// writes every recorder route\nopenApi.save('./swagger.yml');\n```\n\n## License\n\n[MIT](https://github.com/Urigo/sofa/blob/master/LICENSE) © Uri Goldshtein\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgraphql-hive%2Fsofa","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgraphql-hive%2Fsofa","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgraphql-hive%2Fsofa/lists"}