Professional Documents
Culture Documents
1 // Next.js - pages/api/country/[id].js
2
3 export default (req, res) => {
4 const {
5 query: { id },
6 method,
7 body
8 } = req;
9
10 switch (method) {
11 // Read Action
12 case "GET":
13 res.json({
14 id: id
15 })
16
17 // Update Action
18 case "PUT":
19 res.json({
20 id: id,
21 ...body
22 })
23
24 // Delete Action
25 case "DELETE":
26 res.status(204).end()
27
28 default:
29 res.setHeader("Allow", "GET, PUT, DELETE")
30 res.status(405).end()
31 }
32 }
1 // Nest.js
2
3 import { v4 as uuidV4 } from 'uuid';
4 import { NestFactory } from '@nestjs/core';
5 import { Transform } from 'class-transformer';
6 import { IsNotEmpty, IsOptional } from 'class-validator';
7 import { SwaggerModule, DocumentBuilder, ApiProperty, ApiTags } from '@nestjs/swagger';
8 import { Module, Injectable, Controller, Get, Post, Put, Delete, Body, Param, ParseUUIDPipe,
9 ValidationPipe, HttpCode, HttpStatus as Status } from '@nestjs/common';
10
11 class CountryDto {
12 @IsOptional()
13 id: string;
14
15 @ApiProperty()
16 @IsNotEmpty()
17 @Transform(
18 ({ value }) => value.trim()
19 )
20 name: string;
21
22 @ApiProperty()
23 @IsNotEmpty()
24 @Transform(
25 ({ value }) => value.trim()
26 )
27 capital: string;
28 }
29
30 @Injectable()
31 class CountryService {
32 // List Action
33 getIndex() {
34 return [];
35 }
36
37 // Create Action
38 getStore(country: CountryDto) {
39 country.id = uuidV4();
40 return country;
41 }
42
43 // Read Action
44 getShow(id: string) {
45 return { id: id }
46 }
47
48 // Update Action
49 getUpdate(id: string, country: CountryDto) {
50 country.id = id;
51 return country;
52 }
53
54 // Delete Action
55 getDelete(id: string) {}
56 }
57
58 @ApiTags('Country')
59 @Controller('api/v1/country')
60 class CountryController {
61
62
63 constructor(private readonly service: CountryService) {}
64
65 // List Route
66 @Get()
67 index() {
68 return this.service.getIndex();
69 }
70
71 // Create Route
72 @Post()
73 store(@Body() body: CountryDto ) {
74 return this.service.getStore(body);
75 }
76
77 // Read Route
78 @Get(':id')
79 show(@Param('id', new ParseUUIDPipe({ version: '4' })) id: string) {
80 return this.service.getShow(id);
81 }
82
83 // Update Route
84 @Put(':id')
85 update(@Param('id', new ParseUUIDPipe({ version: '4' })) id: string, @Body() body:
CountryDto) {
86 return this.service.getUpdate(id, body);
87 }
88
89 // Delete Route
90 @Delete(':id')
91 @HttpCode(Status.NO_CONTENT)
92 delete(@Param('id', new ParseUUIDPipe({ version: '4' })) id: string) {
93 return this.service.getDelete(id);
94 }
95 }
96
97 @Module({
98 imports: [],
99 controllers: [CountryController],
100 providers: [CountryService],
101 })
102 class AppModule {}
103
104 // Main Function
105 (async function () {
106 const app = await NestFactory.create(AppModule);
107 const oasConfig = new DocumentBuilder().addTag('Country').build();
108 const oasDocument = SwaggerModule.createDocument(app, oasConfig);
109
110 SwaggerModule.setup('docs', app, oasDocument);
111
112 app.useGlobalPipes(new ValidationPipe({
113 whitelist: true,
114 }));
115
116 await app.listen(8080);
117 })()
1 // ASP.Net Core Controller
2
3 using System;
4 using System.Collections.Generic;
5 using Microsoft.AspNetCore.Mvc;
6 using Microsoft.AspNetCore.Http;
7
8 namespace ASPAPI.Controllers
9 {
10 [ApiController]
11 [Route("api/v1/country")]
12 public class CountryController : ControllerBase
13 {
14 // List Action
15 [HttpGet]
16 public IActionResult
17 index()
18 {
19 return Ok(new List<CountryModel>());
20 }
21
22 // Create Action
23 [HttpPost]
24 public CountryModel
25 store(CountryModel country)
26 {
27 Response.StatusCode = StatusCodes.Status201Created;
28 country.id = Guid.NewGuid();
29 return country;
30 }
31
32 // Read Action
33 [HttpGet("{id:Guid}")]
34 public Dictionary<string, Guid>
35 show(Guid id)
36 {
37 return new Dictionary<string, Guid>()
38 {
39 { "id", id }
40 };
41 }
42
43 // Update Action
44 [HttpPut("{id:Guid}")]
45 public ActionResult<CountryModel>
46 update(Guid id, CountryModel country)
47 {
48 country.id = id;
49 return country;
50 }
51
52 // Delete Action
53 [HttpDelete("{id:Guid}")]
54 public IActionResult
55 delete(Guid id)
56 {
57 return NoContent();
58 }
59 }
60 }
1 // ASP.Net Core Model
2
3 using System;
4 using System.ComponentModel.DataAnnotations;
5
6 namespace ASPAPI
7 {
8 public class CountryModel
9 {
10 public Guid id { get; set; }
11
12 [Required]
13 public string name { get; set; }
14
15 [Required]
16 public string capital { get; set; }
17 }
18 }
1 // Fastify
2
3 const uuid = require('uuid');
4 const fastify = require('fastify');
5
6 const app = fastify({ logger: true });
7
8 app.register(require('fastify-swagger'), {
9 exposeRoute: true,
10 routePrefix: '/docs',
11 });
12
13 const isBlank = { pattern: '^$|[ ]+' }
14
15 const idSchema = {
16 type: 'object',
17 properties: {
18 id: {
19 type: 'string',
20 format: 'uuid'
21 }
22 }
23 };
24
25 const countrySchema = {
26 type: 'object',
27 properties: {
28 name: {
29 type: 'string',
30 not: isBlank
31 },
32 capital: {
33 type: 'string',
34 not: isBlank
35 }
36 },
37 required: ['name', 'capital'],
38 additionalProperties: false
39 };
40
41 const valid = rules => ({ schema: rules });
42
43 async function countryRouter(app) {
44 // List Action
45 app.get('/', async () => {
46 return [];
47 });
48
49 // Create Action
50 app.post('/', valid({ body: countrySchema }), async (req, res) => {
51 res.status(201).send({
52 id: uuid.v4(),
53 ...req.body
54 });
55 });
56
57 // Read Action
58 app.get('/:id', valid({ params: idSchema }), async (req, _) => {
59 return { id: req.params.id };
60 });
61
62
63 // Update Action
64 app.put('/:id', valid({ params: idSchema, body: countrySchema }), async (req, _) => {
65 return {
66 id: req.params.id,
67 ...req.body
68 };
69 });
70
71 // Delete Action
72 app.delete('/:id', valid({ params: idSchema }), async (_, res) => {
73 res.status(204).send();
74 });
75 }
76
77 app.register(countryRouter, { prefix: '/api/v1/country' });
78
79 app.listen(3000, "0.0.0.0");
1 # Python Bottle
2
3 from uuid import uuid4
4 from http import HTTPStatus as Status
5 from bottle import Bottle, run, default_app, request, response, HTTPResponse
6
7 country_app = Bottle()
8
9 # Route Params Validation
10 def uuid_filter(config):
11 regexp = r"(?i)[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}"
12
13 def to_python(match):
14 return match
15
16 def to_url(ext):
17 return ext
18
19 return regexp, to_python, to_url
20
21 country_app.router.add_filter('uuid', uuid_filter)
22
23 # List Action
24 @country_app.get("/")
25 def index():
26 return { "message": "Hello World!" }
27
28 # Create Action
29 @country_app.post("/")
30 def store():
31 response.status = Status.CREATED
32 return {
33 "id": str(uuid4()),
34 **request.json
35 }
36
37 # Read Action
38 @country_app.get("/<id:uuid>")
39 def show(id):
40 return { "id": id }
41
42 # Update Action
43 @country_app.put("/<id:uuid>")
44 def update(id):
45 return {
46 "id": id,
47 **request.json
48 }
49
50 # Delete Action
51 @country_app.delete("/<id:uuid>")
52 def delete(id):
53 return HTTPResponse(status=Status.NO_CONTENT)
54
55 default_app().mount(prefix="/api/v1/country", app=country_app)
56
57 run(host="0.0.0.0", port="8080")
1 # Ruby Sinatra
2
3 require 'json'
4 require 'sinatra'
5 require 'sinatra/namespace'
6 require 'securerandom'
7
8 set :protection, :except => [:frame_options, :json_csrf]
9 set :bind, '0.0.0.0'
10
11 namespace '/api/v1' do
12 before do
13 if request.body.size > 0
14 request.body.rewind
15 @json_data = JSON.parse request.body.read
16 end
17 end
18
19 after do
20 content_type :json
21 response.body = response.body.to_json
22 end
23
24 namespace '/country' do
25 # List Action
26 get '/?' do
27 { message: 'Hello World!' }
28 end
29
30 # Create Action
31 post '/?' do
32 status 201 # Created
33 @json_data.merge({ id: SecureRandom.uuid })
34 end
35
36 # Read Action
37 get '/:id' do |id|
38 { id: id }
39 end
40
41 # Update Action
42 put '/:id' do |id|
43 @json_data.merge({ id: id })
44 end
45
46 # Delete Action
47 delete '/:id' do |id|
48 status 204 # No Content
49 end
50 end
51 end