Skip to content

ภาษาพื้นฐานของ Rest API คือ HTTP Methods

HTTP
http
POST /user/signup HTTP/1.1
Host: galaxy.scalar.com
Content-Type: application/json

{
  "name": "Marc",
  "email": "[email protected]",
  "password": "i-love-scalar"
}

::: ผมทดลองใน Scalar Client ให้ดู ::: GET www.google.com faviconhttps://www.google.com/

GET jsonplaceholder.typicode.com faviconhttps://jsonplaceholder.typicode.com/comments

GET letsenhance.io faviconhttps://letsenhance.io/static/73136da51c245e80edc6ccfe44888a99/1015f/MainBefore.jpg

GET bitcoin.org faviconhttps://bitcoin.org/bitcoin.pdf

แต่เราสามารถแปลงมันเป็น Language ต่างๆได้

js
fetch('https://galaxy.scalar.com/user/signup', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Marc',
    email: '[email protected]',
    password: 'i-love-scalar'
  })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
js
// Using fetch in Next.js
const response = await fetch('/api/user', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    name: 'Marc',
    email: '[email protected]',
    password: 'i-love-scalar'
  })
})
const data = await response.json()
js
// Using $fetch in Nuxt.js
const { data } = await useFetch('/api/user', {
  method: 'POST',
  body: {
    name: 'Marc',
    email: '[email protected]',
    password: 'i-love-scalar'
  }
})
js
// Using $fetch with Nitro
const { data } = await $fetch('/api/user', {
  method: 'POST',
  body: {
    name: 'Marc',
    email: '[email protected]',
    password: 'i-love-scalar'
  }
})
ts
// pages/api/signup.ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method === 'POST') {
    const { name, email, password } = req.body
    
    try {
      // Process signup logic here
      res.status(201).json({ success: true, message: 'User created' })
    } catch (error) {
      res.status(400).json({ success: false, message: 'Signup failed' })
    }
  } else {
    res.setHeader('Allow', ['POST'])
    res.status(405).json({ message: `Method ${req.method} Not Allowed` })
  }
}
ts
// server/api/signup.ts
import { defineEventHandler, readBody } from 'h3'

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const { name, email, password } = body
  
  try {
    // Process signup logic here
    return { success: true, message: 'User created' }
  } catch (error) {
    event.node.res.statusCode = 400
    return { success: false, message: 'Signup failed' }
  }
})
python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    name: str
    email: str
    password: str

@app.post("/user/signup")
async def signup(user: User):
    try:
        # Process signup logic here
        return {"success": True, "message": "User created"}
    except Exception as e:
        raise HTTPException(status_code=400, detail="Signup failed")
rust
use actix_web::{post, web, HttpResponse, Result};
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct SignupRequest {
    name: String,
    email: String,
    password: String,
}

#[derive(Serialize)]
struct SignupResponse {
    success: bool,
    message: String,
}

#[post("/user/signup")]
async fn signup(user: web::Json<SignupRequest>) -> Result<HttpResponse> {
    // Process signup logic here
    let response = SignupResponse {
        success: true,
        message: "User created".to_string(),
    };
    
    Ok(HttpResponse::Created().json(response))
}