Rest API
Documentation OpenAPI
- API Core
- API GIS
- API Itree
- API Ecommerce(Замовлення)
- API Ecommerce(Взаємодія)
Naming convintion
- https://restfulapi.net/resource-naming/
- https://nordicapis.com/10-best-practices-for-naming-api-endpoints/
!!! Example
``` js
// crud
HTTP GET http://api.example.com/api/managed-devices //Get all devices
HTTP POST http://api.example.com/api/managed-devices //Create new Device
HTTP GET http://api.example.com/api/managed-devices/{id} //Get device for given Id
HTTP PUT http://api.example.com/api/managed-devices/{id} //Update device for given Id
HTTP DELETE http://api.example.com/api/managed-devices/{id} //Delete device for given Id
// query param
HTTP GET http://api.example.com/api/managed-devices?region=USA
HTTP GET http://api.example.com/api/managed-devices?region=USA&ord=cdate
```
Status code
Code
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
- Successful responses (200–299)
- Redirection messages (300–399)
- Client error responses (400–499)
- Server error responses (500–599)
- code softpro (520+)
Додатково
Auth
No auth
- публічний доступ до API беAPI key
- видається ключ який передається або в query&api_key=ApiKEY
абоHeaders {Authorization:ApiKEY}
Bearer token
-Headers {Authorization:Bearer Token}
- токен може бути статичний або отриманий за допомогою OAuth,JWTBasic auth
-Headers {Authorization:base64(user pass)}
- для авторизацій закритих nginx паролемOAuth 2.0
- Стандарт визначає способи отримання токену, даліBearer token
OAuth 2.0
авторизація для додатків, які мають серверну частину - сервер авторизації
grant_type=authorization_code
авторизація по логіну і паролю
grant_type=password
авторизація для повністю клієнтських додатків - сервер авторизації
відновлення попередньої авторизації
refresh_token
https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/
https://learning.postman.com/docs/sending-requests/authorization/
https://developer.atlassian.com/cloud/jira/platform/understanding-jwt-for-connect-apps/
👀 example "JWT"
// token
`${base64url(header)}.${base64url(payload)}.${signature}`
// api call
Authorization: Bearer {token}
app.post('/api/auth', (req, res) => {
const user = getUser(req.query.user,req.query.pass);
let head = Buffer.from(JSON.stringify({ alg:'HS256',typ:'jwt'})).toString('base64');
let body = Buffer.from(JSON.stringify({uid:user.uid})).toString('base64');
let signature = crypto.createHmac('SHA256',tokenKey).update(`${head}.${body}`)
.digest('base64');
return res.status(200).json({
id: user.id,
login: user.login,
token: `${head}.${body}.${signature}`,
})
})
:::example "OAUTH"
password
POST /oauth/token HTTP/1.1
grant_type=password&client_id=31337&client_secret=deadbeef&username=user&
password=qwerty
HTTP/1.1 200 OK
Content-Type: application/json
{
"access_token":"SlAV32hkKG",
"token_type":"bearer",
"expires_in":86400,
"refresh_token":"8xLOxBtZp8",
}
authorization_code (Auth Server)
# Get Token
curl --request POST \
--url 'https://auth.atlassian.com/oauth/token' \
--header 'Content-Type: application/json' \
--data '{"grant_type": "authorization_code","client_id": "YOUR_CLIENT_ID",
"client_secret": "YOUR_CLIENT_SECRET","code": "YOUR_AUTHORIZATION_CODE",
"redirect_uri": "https://YOUR_APP_CALLBACK_URL"}'
# Call the API
curl --request GET \
--url https://api.atlassian.com/ex/jira/11223344-a1b2-3b33-c444-def123456789/rest/api/2/project \
--header 'Authorization: Bearer aBCxYz654123' \
--header 'Accept: application/json'
:::
Version
import * as express from 'express';
// v1/get-ride.js
const router = express.Router();
router.post('/rides/:id', dep.verifyToken(), (req, res) => {
// Your code
});
app.use('/api/v1', router);
// v2/get-ride.js
const router = express.Router();
router.post('/rides/:id', dep.verifyToken(), (req, res) => {
// Your code
});
app.use('/api/v2', router);
- https://stackoverflow.com/questions/51513715/node-js-rest-api-versioning-the-right-way
- https://apisyouwonthate.com/blog/api-evolution-for-rest-http-apis
- https://apisyouwonthate.com/blog/api-versioning-has-no-right-way
- https://www.mnot.net/blog/2012/12/04/api-evolution.html
- https://medium.com/@pengyeng/api-versioning-with-node-js-47ddd2956715
- https://www.mickpatterson.com.au/blog/api-versioning-with-nodejs-and-express
GraphQL
- https://hygraph.com/blog/graphql-vs-rest-apis
- https://senior.ua/articles/rest-api-vs-graphql-chto-vybrat-dlya-konkretnogo-proekta
gRPC
Не HTTP Протокол підходить для створення мікросервісів
- https://www.trendmicro.com/en_ae/devops/22/f/grpc-api-tutorial.html
- https://daily.dev/blog/build-a-grpc-service-in-nodejs
- https://grpc.io/blog/state-of-grpc-web/
- https://blog.logrocket.com/creating-a-crud-api-with-node-express-and-grpc/
- https://habr.com/ru/post/565020/
- https://auth0.com/blog/beating-json-performance-with-protobuf/
HTTP 1.1 - 2 - 3
Про роботу HTTP протоколу
Різниця між HTTP протоколоами v1.1,2,3