WebAPI.jl
WebAPI.jl copied to clipboard
Make REST APIs quickly and simply.
WebAPI.jl
WebAPI.jl is a abstraction of two Julia packages: HTTP.jl and JSON3.jl. These abstractions allow you to develop APIs in Julia in a simpler and more readable way.
Example:
using WebAPI
function bhaskara(a, b, c)
Δ = b^2 - 4*a*c
Δ < 0 && (Δ = complex(Δ))
x₁ = (-b + √Δ) / 2a
x₂ = (-b - √Δ) / 2a
return x₁, x₂
end
const app = App()
add_post!(app, "/bhaskara") do req
a = req.body.a
b = req.body.b
c = req.body.c
x₁, x₂ = bhaskara(a, b, c)
return Dict("x1" => "$x₁", "x2" => "$x₂")
end
serve(app) #Deafult: ip = localhost, port = 8081
More complex example:
using WebAPI
function bhaskara(a, b, c)
Δ = b^2 - 4*a*c
Δ < 0 && (Δ = complex(Δ))
x₁ = (-b + √Δ) / 2a
x₂ = (-b - √Δ) / 2a
return x₁, x₂
end
const app = App()
add_get!(app, "/bhaskara/:a/:b/:c") do req
a = parse(Int, req.params.a)
b = parse(Int, req.params.b)
c = parse(Int, req.params.c)
x₁, x₂ = bhaskara(a, b, c)
return Dict("x1" => "$x₁", "x2" => "$x₂")
end
add_get!(app, "/bhaskara") do req
verifykeys(req.query, (:a, :b, :c)) || return Res(400, "Incorrect Query.")
a = parse(Int, req.query.a)
b = parse(Int, req.query.b)
c = parse(Int, req.query.c)
x₁, x₂ = bhaskara(a, b, c)
return (x1 = "$x₁", x2 = "$x₂")
end
add_post!(app, "/bhaskara") do req
verifykeys(req.body, ["a", "b", "c"]) || return Res(400, "Incorrect JSON.")
a = req.body.a
b = req.body.b
c = req.body.c
x₁, x₂ = bhaskara(a, b, c)
return Res(201, (x1 = "$x₁", x2 = "$x₂"))
end
serve(app) #Deafult: ip = localhost, port = 8081
The above code running:
App running at:
http://localhost:8081/
Method Route
==============================================
POST /bhaskara
GET /bhaskara/:a/:b/:c
GET /bhaskara
Testing the API using HTTPie:
➜ ~ http GET localhost:8081/bhaskara/1/3/-4
HTTP/1.1 200 OK
Access-Control-Allow-Headers: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: *
Content-Type: application/json
Transfer-Encoding: chunked
{
"x1": "1.0",
"x2": "-4.0"
}
➜ ~ http GET localhost:8081/bhaskara a==1 b==3 c==-4
HTTP/1.1 200 OK
Access-Control-Allow-Headers: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: *
Content-Type: application/json
Transfer-Encoding: chunked
{
"x1": "1.0",
"x2": "-4.0"
}
➜ ~ http POST localhost:8081/bhaskara a:=1 b:=3 c:=-4
HTTP/1.1 201 Created
Access-Control-Allow-Headers: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: *
Content-Type: application/json
Transfer-Encoding: chunked
{
"x1": "1.0",
"x2": "-4.0"
}