All Projects → sauerbraten → Crudapi

sauerbraten / Crudapi

Go implementation of a RESTful JSON API exposing CRUD functionality relying on a custom storage.

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to Crudapi

Api Client Generator
Angular REST API client generator from Swagger YAML or JSON file with camel case settigs
Stars: ✭ 92 (-23.97%)
Mutual labels:  api, json
Jam Api
Parse web pages using CSS query selectors
Stars: ✭ 1,375 (+1036.36%)
Mutual labels:  api, json
Behat Api Extension
API extension for Behat, used to ease testing of JSON-based APIs
Stars: ✭ 92 (-23.97%)
Mutual labels:  api, json
Mirth Transforms
Welcome to Datica's open-source repository of Mirth Transforms and supplementary resources!
Stars: ✭ 77 (-36.36%)
Mutual labels:  api, json
Json Serverless
Transform a JSON file into a serverless REST API in AWS cloud
Stars: ✭ 108 (-10.74%)
Mutual labels:  api, json
Tortilla
Wrapping web APIs made easy.
Stars: ✭ 1,215 (+904.13%)
Mutual labels:  api, json
Rki Covid Api
🦠🇩🇪📈 An API for the spread of covid-19 in Germany. Data from Robert-Koch-Institut.
Stars: ✭ 98 (-19.01%)
Mutual labels:  api, json
Jokeapi
A REST API that serves uniformly and well formatted jokes in JSON, XML, YAML or plain text format that also offers a great variety of filtering methods
Stars: ✭ 71 (-41.32%)
Mutual labels:  api, json
Httpbin
HTTP Request & Response Service, written in Python + Flask.
Stars: ✭ 10,423 (+8514.05%)
Mutual labels:  api, json
Invoice As A Service
💰 Simple invoicing service (REST API): from JSON to PDF
Stars: ✭ 106 (-12.4%)
Mutual labels:  api, json
Sec Edgar Financials
Extract financial data from the SEC's EDGAR database
Stars: ✭ 73 (-39.67%)
Mutual labels:  api, json
Golang Gin Realworld Example App
Exemplary real world application built with Golang + Gin
Stars: ✭ 1,780 (+1371.07%)
Mutual labels:  api, crud
Covid19
JSON time-series of coronavirus cases (confirmed, deaths and recovered) per country - updated daily
Stars: ✭ 1,177 (+872.73%)
Mutual labels:  api, json
Pager Api
Easy API pagination for Rails
Stars: ✭ 86 (-28.93%)
Mutual labels:  api, json
Fipe Json
🚘 FIPE API - Listagem com preço médio de veículos: carro, moto e caminhão.
Stars: ✭ 71 (-41.32%)
Mutual labels:  api, json
Parse Google Docs Json
Authenticates with Google API and parse Google Docs to JSON or Markdown
Stars: ✭ 100 (-17.36%)
Mutual labels:  api, json
Countries States Cities Database
🌍 World countries, states, regions, provinces, cities, towns in JSON, SQL, XML, PLIST, YAML, and CSV. All Countries, States, Cities with ISO2, ISO3, Country Code, Phone Code, Capital, Native Language, Timezones, Latitude, Longitude, Region, Subregion, Flag Emoji, and Currency. #countries #states #cities
Stars: ✭ 1,130 (+833.88%)
Mutual labels:  api, json
Dictfier
Python library to convert/serialize class instances(Objects) both flat and nested into a dictionary data structure. It's very useful in converting Python Objects into JSON format
Stars: ✭ 67 (-44.63%)
Mutual labels:  api, json
Flickr Sdk
Almost certainly the best Flickr API client in the world for node and the browser
Stars: ✭ 104 (-14.05%)
Mutual labels:  api, json
Symfony Jsonapi
JSON API Transformer Bundle for Symfony 2 and Symfony 3
Stars: ✭ 114 (-5.79%)
Mutual labels:  api, json

CRUD API

A router-independent implementation of a minimalist RESTful JSON API offering Create, Read, Update, and Delete (CRUD) handlers.

For more information, check out the wikipedia aticles for CRUD and RESTful.

package main

import (
	"log"
	"net/http"

	"gopkg.in/sauerbraten/crudapi.v2"
)

func main() {
	// storage
	storage := NewStorage()

	// create CRUD API routes
	api := crudapi.New(storage)

	// mount the API
	http.Handle("/api/", http.StripPrefix("/api", api))

	// mount a custom handler if you want
	http.HandleFunc("/", hello)

	// start listening
	log.Println("server listening on localhost:8080/")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func hello(resp http.ResponseWriter, req *http.Request) {
	resp.Write([]byte("Hello there!\n"))
}

Usage

Get the package:

$ go get gopkg.in/sauerbraten/crudapi.v2

Import the package:

import (
	"gopkg.in/sauerbraten/crudapi.v2"
)

Storage Backend

You need to specify where you want to store data. To do so, you have to implement crudapi.Storage. There is an example implementation of that interface using maps.

Authentication & Authorization

For access control, use appropriate middleware for your router.

Routing

crudapi.New returns an http.Handler, so you can use the package with any router you want. Using the standard library, mounting the API routes could look like this:

api := crudapi.New(storage)

http.Handle("/api/", http.StripPrefix("/api", api))

http.ListenAndServe(":8080", nil)

Using chi, mounting might be done like this:

r := chi.NewRouter()
api := crudapi.New(storage)

r.Mount("/api", api)

http.ListenAndServe(":8080", r)

Using chi or another more powerful router than the standard library's DefaultMux will also be helpful for namespacing the API under a version path prefix and access control.

This will create the following CRUD routes:

  • POST /{collection}: Creates a resource of this collection and stores the data you POSTed, then returns the ID
  • GET /{collection}: Returns all resources of this collection
  • GET /{collection}/{id}: Returns the resource of this collection with that ID
  • PUT /{collection}/{id}: Updates the resource of this collection with that ID
  • DELETE /{collection}: Deletes all resources of this collection
  • DELETE /{collection}/{id}: Deletes the resource of this collection with that ID

HTTP status codes

The status codes are set by your Storage implementation; MapStorage for example uses the folllowing:

  • 201 Created when creating,
  • 200 OK when getting, updating and deleting.
  • 404 Not Found if either the collection of data you are POSTing to (for example artists and albums in the URLs) is unkown or you tried to get a non-existant resource (with a wrong ID). In that case MapStorage also sets the error, which is then returned in the JSON response, i.e.: {"error":"resource not found"} or {"error":"collection not found"}.

There are two status codes that are returned by the API handlers:

  • 400 Bad Request is returned when either the POSTed or PUTted JSON data is malformed and cannot be parsed or when you are PUTting without an id in the URL.
  • 405 Method Not Allowed when the HTTP method isn't supported by the endpoint, e.g. when POSTing to a specific resource instead of a collection.

Your auth middleware is responsible for sending 401 Unauthorized or 403 Forbidden when appropriate.

Response Body

Server responses are always a JSON object, containing zero or more of the following fields:

  • "error": specifies the error that occured, if any
  • "id": the ID of the newly created resource (only used when POSTing)
  • "result": the requested resource (GET /collection/id) or an array of resources (GET /collection/)

Example

Change into example/ and execute go run *.go. When the server is running, check out the index page and try the following commands in a terminal:

Create

Create Gorillaz as artist:

$ curl -i -X POST -d '{"name":"Gorillaz","albums":[]}' http://localhost:8080/api/artists
HTTP/1.1 201 Created
[...]

{"id":"7774218119985532862"}

The ID in the reply is created by your storage implementation, typically a wrapper for a database, so when you insert something you get the ID of the inserted data. The MapStorage we use here simply uses random numbers (which is definitely not recommended).

Create Plastic Beach as album:

$ curl -i -X POST -d '{"title":"Plastic Beach","songs":["On Melancholy Hill","Stylo"]}' http://localhost:8080/api/albums
HTTP/1.1 201 Created
[...]

{"id":"5972287258414936807"}

Read

Retrieve the Gorillaz artist object:

$ curl -i -X GET http://localhost:8080/artists/api/7774218119985532862
HTTP/1.1 200 OK
[...]

{"result":{"name":"Gorillaz","albums":[]}}

Update

Update the Gorillaz object and add the Plastic Beach album:

$ curl -i -X PUT -d '{"name":"Gorillaz","albums":["5972287258414936807"]}' http://localhost:8080/api/artists/7774218119985532862
HTTP/1.1 200 OK
[...]

Again, retrieve the Gorillaz artist object:

$ curl -i -X GET http://localhost:8080/api/artists/7774218119985532862
HTTP/1.1 200 OK
[...]

{"result":{"albums":["5972287258414936807"],"name":"Gorillaz"}}

Delete

Delete the Gorillaz object:

$ curl -i -X DELETE http://localhost:8080/api/artists/7774218119985532862
HTTP/1.1 200 OK
[...]

Let's check if it's really gone:

$ curl -i -X GET http://localhost:8080/api/artists/7774218119985532862
HTTP/1.1 404 Not Found
[...]

{"error":"resource not found"}

Documentation

Full package documentation on GoDoc.

License

Copyright (c) 2013-2018 The crudapi Authors. All rights reserved.

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].