Commit 264fc019 authored by Lukáš Huvar's avatar Lukáš Huvar Committed by JJ Kasper

API routes documentation (#7562)

* API routes examples and documentation

* Update examples/api-routes-micro/README.md
Co-Authored-By: 's avatarLuis Fernando Alvarez D. <luis@zeit.co>

* Update examples/api-routes/README.md
Co-Authored-By: 's avatarLuis Fernando Alvarez D. <luis@zeit.co>

* Apply suggestions from code review
Co-Authored-By: 's avatarLuis Fernando Alvarez D. <luis@zeit.co>

* Update API routes docs

* Improve example to reflect dynamic routes

* Update readme to reflect API routes changes

* Apply suggestions from review
parent b0b1c320
# API routes with Micro example
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/segmentio/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-micro api-routes-micro-app
# or
yarn create next-app --example api-routes-micro api-routes-micro-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/api-routes-micro
cd api-routes-micro
```
Install it and run:
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
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 their usage alongside [Micro](https://github.com/zeit/micro), an `http` server for microservices
{
"name": "api-routes-micro",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"isomorphic-unfetch": "3.0.0",
"micro": "9.3.5-canary.1",
"next": "8.1.1-canary.69",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"license": "ISC"
}
import micro from 'micro'
const posts = [
{
title: 'Next.js is awesome'
},
{
title: 'API support is really great'
}
]
export default micro((req, res) => {
res.status(200).json(posts)
})
import fetch from 'isomorphic-unfetch'
const Index = ({ posts }) => (
<ul>
{posts.map((post, i) => (
<li key={i}>{post.title}</li>
))}
</ul>
)
Index.getInitialProps = async () => {
const response = await fetch('http://localhost:3000/api/posts')
const posts = await response.json()
return { posts }
}
export default Index
# Basic API routes example
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/segmentio/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 api-routes-app
# or
yarn create next-app --example api-routes api-routes-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/api-routes
cd api-routes
```
Install it and run:
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
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 provides an easy solution to build your own `API`. This example shows how to create multiple `API` endpoints with serverless functions, which can execute independently.
import Link from 'next/link'
export default ({ person }) => (
<li>
<Link href={`/person?id=${person.id}`}>
<a>{person.name}</a>
</Link>
</li>
)
export const people = [
{
id: '1',
name: 'Luke Skywalker',
height: '172',
mass: '77',
hair_color: 'blond',
skin_color: 'fair',
eye_color: 'blue',
gender: 'male'
},
{
id: '2',
name: 'C-3PO',
height: '167',
mass: '75',
hair_color: 'n/a',
skin_color: 'gold',
eye_color: 'yellow',
gender: 'n/a'
},
{
id: '3',
name: 'R2-D2',
height: '96',
mass: '32',
hair_color: 'n/a',
skin_color: 'white, blue',
eye_color: 'red',
gender: 'n/a'
},
{
id: '4',
name: 'Darth Vader',
height: '202',
mass: '136',
hair_color: 'none',
skin_color: 'white',
eye_color: 'yellow',
gender: 'male'
},
{
id: '5',
name: 'Leia Organa',
height: '150',
mass: '49',
hair_color: 'brown',
skin_color: 'light',
eye_color: 'brown',
gender: 'female'
},
{
id: '6',
name: 'Owen Lars',
height: '178',
mass: '120',
hair_color: 'brown, grey',
skin_color: 'light',
eye_color: 'blue',
gender: 'male'
},
{
id: '7',
name: 'Beru Whitesun lars',
height: '165',
mass: '75',
hair_color: 'brown',
skin_color: 'light',
eye_color: 'blue',
gender: 'female'
},
{
id: '8',
name: 'R5-D4',
height: '97',
mass: '32',
hair_color: 'n/a',
skin_color: 'white, red',
eye_color: 'red',
gender: 'n/a'
},
{
id: '9',
name: 'Biggs Darklighter',
height: '183',
mass: '84',
hair_color: 'black',
skin_color: 'light',
eye_color: 'brown',
gender: 'male'
},
{
id: '10',
name: 'Obi-Wan Kenobi',
height: '182',
mass: '77',
hair_color: 'auburn, white',
skin_color: 'fair',
eye_color: 'blue-gray',
gender: 'male'
}
]
{
"name": "api-routes",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"isomorphic-unfetch": "3.0.0",
"next": "8.1.1-canary.69",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"license": "ISC"
}
import { people } from '../../../data'
export default ({ query: { id } }, res) => {
const filtered = people.filter(p => p.id === id)
// User with id exists
if (filtered.length > 0) {
res.status(200).json(filtered[0])
} else {
res.status(404).json({ message: `User with id: ${id} not found.` })
}
}
import { people } from '../../../data'
export default (req, res) => {
res.status(200).json(people)
}
import Person from '../components/Person'
import fetch from 'isomorphic-unfetch'
const Index = ({ people }) => (
<ul>
{people.map((p, i) => (
<Person key={i} person={p} />
))}
</ul>
)
Index.getInitialProps = async () => {
const response = await fetch('http://localhost:3000/api/people')
const people = await response.json()
return { people }
}
export default Index
import fetch from 'isomorphic-unfetch'
const Person = ({ data, status }) =>
status === 200 ? (
<table>
<thead>
<tr>
<th>Name</th>
<th>Height</th>
<th>Mass</th>
<th>Hair color</th>
<th>Skin color</th>
<th>Eye color</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr>
<td>{data.name}</td>
<td>{data.height}</td>
<td>{data.mass}</td>
<td>{data.hair_color}</td>
<td>{data.skin_color}</td>
<td>{data.eye_color}</td>
<td>{data.gender}</td>
</tr>
</tbody>
</table>
) : (
<p>{data.message}</p>
)
Person.getInitialProps = async ({ query }) => {
const response = await fetch(`http://localhost:3000/api/people/${query.id}`)
const data = await response.json()
return { data, status: response.status }
}
export default Person
...@@ -45,6 +45,10 @@ ...@@ -45,6 +45,10 @@
- [Prefetching Pages](#prefetching-pages) - [Prefetching Pages](#prefetching-pages)
- [With `<Link>`](#with-link-1) - [With `<Link>`](#with-link-1)
- [Imperatively](#imperatively-1) - [Imperatively](#imperatively-1)
- [API Routes](#api-routes)
- [Dynamic routes support](#dynamic-routes-support)
- [API Middlewares](#api-middlewares)
- [Helper Functions](#helper-functions)
- [Custom server and routing](#custom-server-and-routing) - [Custom server and routing](#custom-server-and-routing)
- [Disabling file-system routing](#disabling-file-system-routing) - [Disabling file-system routing](#disabling-file-system-routing)
- [Dynamic assetPrefix](#dynamic-assetprefix) - [Dynamic assetPrefix](#dynamic-assetprefix)
...@@ -1033,6 +1037,74 @@ class MyLink extends React.Component { ...@@ -1033,6 +1037,74 @@ class MyLink extends React.Component {
export default withRouter(MyLink) export default withRouter(MyLink)
``` ```
### API Routes
<details>
<summary><b>Examples</b></summary>
<ul>
<li><a href="/examples/api-routes">Basic API routes</a></li>
<li><a href="/examples/api-routes-micro">API routes with micro</a></li>
</ul>
</details>
API routes provides a straightforward solution to build your `API` with `Next.js`. Start by creating the `api` folder inside the `pages` folder. Every file inside `api` is mapped to `/api/*`, for example `api/posts.js` will be mapped to `/api/posts`. Here's how an `api` route looks like:
```js
export default (req, res) => {
res.setHeader('Content-Type', 'application/json')
res.statusCode = 200
res.end(JSON.stringify({ name: 'Nextjs' }))
}
```
**Note: API routes are compiled just for the server, there's no overhead added to the client bundle and every route is its own separated bundle.**
#### Dynamic routes support
API pages support [dynamic routing](#dynamic-routing), so you can use all benefits mentioned already above.
Consider the following page `pages/api/post/[pid].js`, here is how you get parameters inside the resolver method:
```js
export default (req, res) => {
const {
query: { pid },
} = req
res.end(`Post: ${pid}`)
}
```
#### API Middlewares
API routes provides built in `middlewares` which parse the incoming `req`. Those middlewares are:
- `req.cookies` - an object containing the cookies sent by the request. Defaults to `{}`
- `req.query` - an object containing the [query string](https://en.wikipedia.org/wiki/Query_string). Defaults to `{}`
- `req.body` - an object containing the body parsed by `content-type`, or `null` if no body is sent
Body parsing is always on by default. However, if you don't want to parse body or you want to consume the body as `stream`. It's possible to opt-out from it. To disable body parsing you need to provide `config` option bellow inside page.
```js
export const config = {
api: {
bodyParser: false,
},
}
```
#### Helper Functions
We're providing a set of `Express.js`-like methods to improve the developer experience and increase the speed of creating new `API` endpoints:
```js
export default (req, res) => {
res.status(200).json({ name: 'Nextjs' })
}
```
- `res.status(code)` - a function to set the status code. `code` must be a valid [HTTP status code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes)
- `res.json(json)` - Sends a `JSON` response. `json` must be a valid `JSON` object
- `res.send(body)` - Sends the HTTP response. `body` can be a `string`, an `object` or a `Buffer`
### Custom server and routing ### Custom server and routing
<details> <details>
...@@ -2028,6 +2100,15 @@ Page.getInitialProps = async ({ req }) => { ...@@ -2028,6 +2100,15 @@ Page.getInitialProps = async ({ req }) => {
export default Page export default Page
``` ```
For [API routes](#api-routes) types, we provide `NextApiRequest` and `NextApiResponse`, which extend the `Node.js` request and response objects.
```ts
import { NextApiRequest, NextApiResponse } from 'next'
export default (req: NextApiRequest, res: NextApiResponse) => {
res.status(200).json({ title: 'Next.js' })
```
For `React.Component` you can use `NextPageContext`: For `React.Component` you can use `NextPageContext`:
```tsx ```tsx
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment