From 83a3903fc2722fec74a279e0c5604db0cef8bf9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Huvar?= Date: Thu, 25 Jul 2019 17:18:38 +0200 Subject: [PATCH] HTTP methods docs and REST example (#8108) * HTTP methods docs and REST example * Update packages/next/README.md Co-Authored-By: Joe Haddad * Update examples/api-routes-rest/README.md Co-Authored-By: Joe Haddad * Fix standard --- examples/api-routes-rest/README.md | 25 +++++++++++++++++++ examples/api-routes-rest/package.json | 16 ++++++++++++ .../api-routes-rest/pages/api/user/[id].js | 20 +++++++++++++++ examples/api-routes-rest/pages/api/users.js | 13 ++++++++++ examples/api-routes-rest/pages/index.js | 23 +++++++++++++++++ examples/api-routes-rest/pages/user/[id].js | 12 +++++++++ packages/next/README.md | 13 ++++++++++ 7 files changed, 122 insertions(+) create mode 100644 examples/api-routes-rest/README.md create mode 100644 examples/api-routes-rest/package.json create mode 100644 examples/api-routes-rest/pages/api/user/[id].js create mode 100644 examples/api-routes-rest/pages/api/users.js create mode 100644 examples/api-routes-rest/pages/index.js create mode 100644 examples/api-routes-rest/pages/user/[id].js diff --git a/examples/api-routes-rest/README.md b/examples/api-routes-rest/README.md new file mode 100644 index 0000000000..adfe929a0a --- /dev/null +++ b/examples/api-routes-rest/README.md @@ -0,0 +1,25 @@ +# API routes with REST + +## How to use + +### Using `create-next-app` + +Execute [`create-next-app`](https://www.npmjs.com/package/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example: + +```bash +npx create-next-app --example api-routes-rest api-routes-rest-app +# or +yarn create next-app --example api-routes-rest api-routes-rest-app +``` + +### Deploy to Now + +Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download)) + +```bash +now +``` + +## The idea behind the example + +Next.js ships with [API routes](https://github.com/zeit/next.js#api-routes), which provide an easy solution to build your own `API`. This example shows how it can be used to create your [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) api. diff --git a/examples/api-routes-rest/package.json b/examples/api-routes-rest/package.json new file mode 100644 index 0000000000..581d565303 --- /dev/null +++ b/examples/api-routes-rest/package.json @@ -0,0 +1,16 @@ +{ + "name": "api-routes-rest", + "version": "1.0.0", + "scripts": { + "dev": "next", + "build": "next build", + "start": "next start" + }, + "dependencies": { + "isomorphic-unfetch": "3.0.0", + "next": "latest", + "react": "^16.8.6", + "react-dom": "^16.8.6" + }, + "license": "ISC" +} diff --git a/examples/api-routes-rest/pages/api/user/[id].js b/examples/api-routes-rest/pages/api/user/[id].js new file mode 100644 index 0000000000..e06b755e4e --- /dev/null +++ b/examples/api-routes-rest/pages/api/user/[id].js @@ -0,0 +1,20 @@ +export default (req, res) => { + const { + query: { id, name }, + method + } = req + + switch (method) { + case 'GET': + // Get data from your database + res.status(200).json({ id, name: `User ${id}` }) + break + case 'PUT': + // Update or create data in your database + res.status(200).json({ id, name: name || `User ${id}` }) + break + default: + res.setHeader('Allow', ['GET', 'PUT']) + res.status(405).end(`Method ${method} Not Allowed`) + } +} diff --git a/examples/api-routes-rest/pages/api/users.js b/examples/api-routes-rest/pages/api/users.js new file mode 100644 index 0000000000..f7714a89f2 --- /dev/null +++ b/examples/api-routes-rest/pages/api/users.js @@ -0,0 +1,13 @@ +// Fake users data +const users = [ + { + id: 1 + }, + { id: 2 }, + { id: 3 } +] + +export default (req, res) => { + // Get data from your database + res.status(200).json(users) +} diff --git a/examples/api-routes-rest/pages/index.js b/examples/api-routes-rest/pages/index.js new file mode 100644 index 0000000000..e7e53d1caf --- /dev/null +++ b/examples/api-routes-rest/pages/index.js @@ -0,0 +1,23 @@ +import fetch from 'isomorphic-unfetch' +import Link from 'next/link' + +const Index = ({ users }) => ( + +) + +Index.getInitialProps = async () => { + const response = await fetch('http://localhost:3000/api/users') + const users = await response.json() + + return { users } +} + +export default Index diff --git a/examples/api-routes-rest/pages/user/[id].js b/examples/api-routes-rest/pages/user/[id].js new file mode 100644 index 0000000000..5a52a78e6a --- /dev/null +++ b/examples/api-routes-rest/pages/user/[id].js @@ -0,0 +1,12 @@ +import fetch from 'isomorphic-unfetch' + +const User = ({ user }) =>
{user.name}
+ +User.getInitialProps = async ({ query: { id } }, res) => { + const response = await fetch(`http://localhost:3000/api/user/${id}`) + const user = await response.json() + + return { user } +} + +export default User diff --git a/packages/next/README.md b/packages/next/README.md index 4b38969520..d9f96f6186 100644 --- a/packages/next/README.md +++ b/packages/next/README.md @@ -1041,6 +1041,7 @@ export default withRouter(MyLink)
  • API routes with micro
  • API routes with middleware
  • API routes with GraphQL server
  • +
  • API routes with REST
  • @@ -1064,6 +1065,18 @@ export default (req, res) => { - `res` refers to [NextApiResponse](https://github.com/zeit/next.js/blob/v9.0.0/packages/next-server/lib/utils.ts#L168-L178) which extends [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) +To handle different HTTP methods for API calls you can access `req.method` in your resolver function: + +```js +export default (req, res) => { + if (req.method === 'POST') { + // Process your POST request + } else { + // Handle the rest of your HTTP methods + } +} +``` + > **Note**: API Routes [do not specify CORS headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), so they'll be **same-origin only** by default. > You can customize this behavior by wrapping your export with CORS middleware. > We provide an [example of this below](#api-middlewares).