HTTP methods docs and REST example (#8108)
* HTTP methods docs and REST example * Update packages/next/README.md Co-Authored-By: Joe Haddad <timer150@gmail.com> * Update examples/api-routes-rest/README.md Co-Authored-By: Joe Haddad <timer150@gmail.com> * Fix standard
This commit is contained in:
parent
f8b56da7e1
commit
83a3903fc2
7 changed files with 122 additions and 0 deletions
25
examples/api-routes-rest/README.md
Normal file
25
examples/api-routes-rest/README.md
Normal file
|
@ -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.
|
16
examples/api-routes-rest/package.json
Normal file
16
examples/api-routes-rest/package.json
Normal file
|
@ -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"
|
||||
}
|
20
examples/api-routes-rest/pages/api/user/[id].js
Normal file
20
examples/api-routes-rest/pages/api/user/[id].js
Normal file
|
@ -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`)
|
||||
}
|
||||
}
|
13
examples/api-routes-rest/pages/api/users.js
Normal file
13
examples/api-routes-rest/pages/api/users.js
Normal file
|
@ -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)
|
||||
}
|
23
examples/api-routes-rest/pages/index.js
Normal file
23
examples/api-routes-rest/pages/index.js
Normal file
|
@ -0,0 +1,23 @@
|
|||
import fetch from 'isomorphic-unfetch'
|
||||
import Link from 'next/link'
|
||||
|
||||
const Index = ({ users }) => (
|
||||
<ul>
|
||||
{users.map(user => (
|
||||
<li key={user.id}>
|
||||
<Link href='/user/[id]' as={`/user/${user.id}`}>
|
||||
<a>{`User ${user.id}`}</a>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
|
||||
Index.getInitialProps = async () => {
|
||||
const response = await fetch('http://localhost:3000/api/users')
|
||||
const users = await response.json()
|
||||
|
||||
return { users }
|
||||
}
|
||||
|
||||
export default Index
|
12
examples/api-routes-rest/pages/user/[id].js
Normal file
12
examples/api-routes-rest/pages/user/[id].js
Normal file
|
@ -0,0 +1,12 @@
|
|||
import fetch from 'isomorphic-unfetch'
|
||||
|
||||
const User = ({ user }) => <div>{user.name}</div>
|
||||
|
||||
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
|
|
@ -1041,6 +1041,7 @@ export default withRouter(MyLink)
|
|||
<li><a href="/examples/api-routes-micro">API routes with micro</a></li>
|
||||
<li><a href="/examples/api-routes-middleware">API routes with middleware</a></li>
|
||||
<li><a href="/examples/api-routes-graphql">API routes with GraphQL server</a></li>
|
||||
<li><a href="/examples/api-routes-rest">API routes with REST</a></li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
|
@ -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).
|
||||
|
|
Loading…
Reference in a new issue