Skip to main content
Version: 4.0.0

API Development

Routing​

In Midway Hooks, you can quickly create interfaces through the Api() function provided by @midwayjs/hooks.

Hello World example:

/src/hello.ts
import {
Api
Get
} from '@midwayjs/hooks';

export default Api (
Get(), // Http Path: /api/hello
async () => {
return 'Hello World!';
}
);

An API interface consists of the following parts:

  • Api(): defines an API function.
  • Get(path?: String): specifies the Http trigger, the request method is set to GET, and the optional path is the path of the interface. If you do not specify a path, the path is generated based on the function name and file name. By default, the path is prefixed with /API.
  • Handler: async (...args: any[]) => { ... }: user logic, processes requests and returns results

You can also specify the path, as shown in the following example.

/src/hello.ts
import {
Api
Get
} from '@midwayjs/hooks';

export default Api (
Get('/hello'), // Http Path: /hello
async () => {
return 'Hello World!';
}
);

Request context (Context / Request / Response)​

You can get the request context object through the useContext provided by @midwayjs/hooks.

Taking Koa framework as an example, the useContext will return Koa's Context object.

Basic example:

  1. Get the request Method and Path
import {
Api
Get
useContext
} from '@midwayjs/hooks';
import { Context } from '@midwayjs/koa';

export default Api(Get(), async () => {
const ctx = useContext<Context>();
return {
method: ctx.method
path: ctx.path
};
});
  1. Set the returned Header
import {
Api
Get
useContext
} from '@midwayjs/hooks';

export default Api(Get(), async () => {
const ctx = useContext<Context>();
ctx.set('X-Powered-By', 'Midway');
return 'Hello World!';
});

At the same time, we can also set Header by SetHeader().

Http trigger​

TriggerNotes
All(path?: string)Accept all Http Method requests
Get(path?: string)Accept GET request
Post(path?: string)Accept POST request
Put(path?: string)Accept PUT request
Delete(path?: string)Accept DELETE request
Patch(path?: string)Accept PATCH request
Head(path?: string)Accept HEAD request
Options(path?: string)Accept OPTIONS request

Request​

Pass parameter Data​

In Midway Hooks, the input parameter of the interface is the parameter that declares the function.

The basic example is as follows:

import {
Api
Post
} from '@midwayjs/hooks';

export default Api (
Post(), // Http Path: /api/say
async (name: string) => {
return 'Hello ${name}!';
}
);

You can call the interface in two ways.

  1. Full stack project: based on zero Api, import interface and call
  2. Manual call: Use fetch to Handler(...args: any[]) input parameters under Http, and you can pass parameters by setting the args parameter of Http Body during manual request.
import say from './api';

const response = await say('Midway');
console.log(response); // Hello Midway!

Query parameter Query​

You can use the Query<T> parameter to pass the parameter to the URL.

If you want the interface path to be /articles? Page = 0 & limit = 10, you can write like this.

import {
Api
Get
Query
useContext
} from '@midwayjs/hooks';

export default Api (
Get()
Query< {
page: string;
limit: string;
}>(),
async () => {
const ctx = useContext();
return {
page: ctx.query.page
limit: ctx.query.limit
};
}
);

Front-end call

import getArticles from './api';
const response = await getArticles({
query: { page: '0', limit: '10'}
});
console.log(response); // { page: '0', limit: '10'}

Path parameter Params​

Path parameters can realize the functions of dynamic paths and obtaining parameters from paths. When you use this feature, you must manually set the path and use Params<T> to declare the type.

If you want the interface path to be /article/100 and get a value with id 100, you can write as follows:

import {
Api
Get
Params
useContext
} from '@midwayjs/hooks';

export default Api (
Get('/article/:id')
Params<{ id: string }>()
async () => {
const ctx = useContext();
return {
article: ctx.params.id
};
}
);

Front-end call

import getArticle from './api/article';
const response = await getArticle({
params: { id: '100'}
});
console.log(response); // { article: '100'}

Request header Headers​

The request header can realize the function of passing parameters through Http Headers. When using this function, the type must be declared by Headers<T>.

If you want to request /auth and pass token in the Request Headers, you can write as follows:

import {
Api
Get
Headers
useContext
} from '@midwayjs/hooks';

export default Api (
Get('/auth')
Headers<{ token: string }>()
async () => {
const ctx = useContext();
return {
token: ctx.headers.token
};
}
);

Front-end call

import getAuth from './api/auth';
const response = await getAuth({
headers: { token: '123456'}
});
console.log(response); // { token: '123456'}

Response Response​

Status code HttpCode​

HttpCode(status: number) is supported.

import {
Api
Get
HttpCode
} from '@midwayjs/hooks';

export default Api (
Get()
HttpCode(201)
async () => {
return 'Hello World!';
}
);

Response header SetHeader​

SetHeader(key: string, value: string)

import {
Api
Get
SetHeader
} from '@midwayjs/hooks';

export default Api (
Get()
SetHeader('X-Powered-By', 'Midway')
async () => {
return 'Hello World!';
}
);

Redirect Redirect​

Support: Redirect(url: string, code?: number = 302)

import {
Api
Get
Redirect
} from '@midwayjs/hooks';

export default Api (
Get('/demo')
Redirect('/hello')
async () => {}
);

Return value type ContentType​

Supported: ContentType(type: string).

import {
Api
Get
ContentType
} from '@midwayjs/hooks';

export default Api (
Get()
ContentType('text/html')
async () => {
return '<h1>Hello World! </h1>';
}
);