• Stars
    star
    293
  • Rank 137,535 (Top 3 %)
  • Language
    Haskell
  • License
    MIT License
  • Created almost 9 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A brief example of Servant with Persistent

servant-persistent

Build Status

Servant is an awesome Haskell library for writing web APIs. It uses the type system in a way that can only be described as magic to generate type safe routes as well as clients.

Persistent is another awesome Haskell library for querying databases. It manages migrations, your schema, and querying to make data transactions mostly painless.

For some reason, no one had created an example on how to use these guys together. I put together this minimal example to show an example implementation, along with some resource management and basic error handling.

I wrote a blog post that goes into a bit more detail.

Requirements:

Haskell

You can use stack to get started:

  1. stack build
  2. stack exec perservant

Alternatively, cabal can be used:

  1. cabal sandbox init
  2. cabal install --dependencies-only && cabal configure && cabal build
  3. cabal run

Database:

You will need PostgreSQL installed and listening on port 5432. The default configuration uses a database name perservant with username/password test:test.

These steps work on Ubuntu:

$ apt install postgres libpq-dev
$ sudo -u postgres createuser -se test
$ sudo -u postgres psql -c "alter role test with password 'test'"
$ sudo -u postgres psql -c "create database perservant"

These following steps worked on Arch Linux:

# install postgres
$ sudo pacman -S postgres

# The installation process should have created the postgres system user for us.
# Become that user in order to initialize the DB.  This is required before
# running the postgres service.
$ sudo -i -u postgres

# As the postgres user, initialize the database.
[postgres]$ initdb --locale en_US.UTF-8 -E UTF8 -D '/var/lib/postgres/data'
# Exit to go back to your normal user.
[postgres]$ exit

# As your normal user start the postgres service.
$ sudo systemctl start postgres.service

# When that starts successfully, then we need to become the postgres system
# user again to create the "test" user and perservant database.
$ sudo -i -u postgres
[postgres]$ createuser --interactive
Enter name of role to add: test
Shall the new role be a superuser? (y/n) y
[postgres]$ createdb perservant -U test
# Exit to go back to your normal user.
[postgres]$ exit

# As your normal user you can log in and play around with the DB:
$ psql -d perservant -U test
psql (9.4.4)
Type "help" for help.

perservant=#

The API:

  • GET /users returns a list of all users in the database
  • GET /users/:name returns the first user whose name is :name, and returns 404 if the user doesn't show up.
  • POST /users with JSON like { "name": "String", "email": "String" } to create a User.

Playing with the API from the command line

Once the compiled perservant binary is running, you can use curl like below to play with the API from the command line.

# create a new user
$ curl --verbose --request POST --header "Content-Type: application/json" \
    --data '{"name": "foo", "email": "[email protected]"}' \
	http://localhost:8081/users

# get all users in database
$ curl --verbose --request GET --header "Content-Type: application/json" \
	http://localhost:8081/users

# get certain user in database
$ curl --verbose --request GET --header "Content-Type: application/json" \
	http://localhost:8081/users/foo

src/Main.hs

main starts off by pulling some settings from the environment, creating a connection pool, running the migrations, and finally running the app.

src/Api.hs

This source contains the actual API definition.

src/Config.hs

Contains the runDb, makePool, and Config definitions.

src/Models.hs

Contains fairly typical Persistent schema definitions.

More Repositories

1

intero-neovim

A neovim plugin for Intero, forked from ghcmod-vim
Vim Script
216
star
2

parsonsmatt.github.io

My Github pages website
SCSS
68
star
3

purs-architecture-tutorial

A port of the Elm Architecture Tutorial to PureScript
PureScript
55
star
4

rowdy

A convenient DSL for describing web routes
Haskell
43
star
5

hasktuts

A collection of introductory tutorials on Haskell libraries
43
star
6

QuickLift

Web application to quickly and easily log your weightlifting sessions
Haskell
38
star
7

garlic-bread

Leave delicious breadcrumbs to make your errors easier to understand.
Haskell
37
star
8

kale

A quick, easy, and declarative task runner for Haskell code to destroy your boiler plate!
Haskell
33
star
9

monad-metrics

haskell metrics
Haskell
30
star
10

annotated-exception

Machinery for throwing and catching exceptions with some annotation.
Haskell
28
star
11

persistent-typed-db

A type and helpers for typesafe SQL access in the presence of many databases.
Haskell
23
star
12

encoding-via

type classes and deriving via for encoding
Haskell
22
star
13

hotel-california

A tool for OpenTelemetry tracing on the command line
Haskell
21
star
14

purescript-routing-example

An example of purescript-routing and purescript-halogen
PureScript
20
star
15

plucky

Plucky errors and exceptions
Haskell
19
star
16

require-callstack

Require that callers propagate `HasCallStack` constraints
Haskell
19
star
17

prairie

First Class Record Fields in Haskell
Haskell
17
star
18

persistent-pagination

Efficient and correct pagination!
Haskell
16
star
19

ql-purs

QuickLift frontend in PureScript
PureScript
15
star
20

hedgehog-fakedata

A compatibility library for `hedgehog` and `fakedata`
Haskell
15
star
21

beginner-error-messages

Informative error messages for common beginner misunderstandings with Haskell
Haskell
15
star
22

persistent-documentation

DSL for attaching documentation to persistent entities
Haskell
14
star
23

smoltok

An implementation of Smalltalk 80 in Rust
Rust
13
star
24

prio

Plucky Runtime IO
Haskell
13
star
25

yesod-minimal

A tiny, single-file yesod app that can be used as a base for reproducing bugs
Haskell
12
star
26

ghc-compile-stats

stupid lil program to parse GHC/cabal output and tell you how long stuff takes
Haskell
10
star
27

record-wrangler

Alter datatypes at your leisure!
Haskell
8
star
28

modalities

Repository for my independent study at UGA
TeX
8
star
29

gear-tracker

An application that helps cyclists track their gear
Haskell
8
star
30

monad-logger-prefix

Easily add a prefix to your MonadLogger output.
HTML
7
star
31

data-diff

An approach to diffing values and records.
Haskell
7
star
32

ghc-cache-buster

Haskell
7
star
33

pureflowy

A workflow management tool written in Haskell and PureScript
PureScript
7
star
34

unification

implementation of the first order logic unification algorithm in Haskell
Haskell
6
star
35

beethoven

A gem for class composition in Ruby
Ruby
6
star
36

purescript-trees

Rose trees
PureScript
6
star
37

scotty-persistent-example

Repository to go along with a blog post
Haskell
6
star
38

packedbits

are you worried about space? ME TOO! SPACE IS VERY CONCERNING
Haskell
6
star
39

callstacks-what-even

callstacks in ghc are weird
Haskell
6
star
40

exceptiot

A type `ExceptIOT` which uses `IO` for the `MonadError` instance, allowing a `MonadUnliftIO` instance
Haskell
5
star
41

exception-via

Derive hierarchical exception instances for your datatypes
Haskell
5
star
42

performance-debugging

An adventure in debugging the performance of a Haskell data structure
Haskell
5
star
43

big-government

When you want to give the State more responsibility and power
Haskell
5
star
44

command-pattern

JavaScript
5
star
45

hash-rekt

An extensible record library based on HashMaps.
Haskell
5
star
46

lift-type

Lift a type into a Template Hasell Type.
Haskell
5
star
47

record-impl

Haskell
5
star
48

incremental-servant

Replace your old API with a Servant one!
Haskell
5
star
49

oncet

A library for defining lazy recipes with components that are only run once
Haskell
5
star
50

callstack-examples

Haskell
5
star
51

liboath-hs

Haskell bindings to the liboath library.
Haskell
4
star
52

yo-dawg

Haskell API in Haskell website
Haskell
4
star
53

sincify

Generate `since` annotations for a package.
Makefile
4
star
54

coerce-role

Derive fearlessly in the face of roles
Haskell
4
star
55

persistent-discover

Discover your Persistent Models with Ease
Haskell
4
star
56

split-persistent

An example on splitting up a persistent models file (see PRs)
Haskell
4
star
57

mesa-verde

Scrap your Persistent quasiquoter!
Haskell
4
star
58

abstract-fork

A type class for forking threads
Haskell
4
star
59

glob-imports

A utility for package metaprogramming imports
Haskell
4
star
60

HASKELL_TEMPLATE

a template repository for my haskell projects
Makefile
3
star
61

rails-box

Barebones box for Rails development.
Shell
3
star
62

discover-instances

A TemplateHaskell helper that discovers type class instances for you
Haskell
3
star
63

dpll

An implementation of the DPLL algorithm in Haskell, using an 'exploratory coding' methodology.
Haskell
3
star
64

cis194

Homework for the Haskell course: http://www.seas.upenn.edu/~cis194/spring13/lectures.html
Haskell
3
star
65

wyas

Write Yourself a Scheme!
Haskell
3
star
66

WifiWizardDemo

Demo phonegap application for WifiWIzard
Java
3
star
67

esqueleto-compat

Compatibility operators and exports to make importing Esqueleto and Persistent easier
Haskell
3
star
68

some-dict-of

A Haskell library for packaging and using constraints, existentially.
Haskell
3
star
69

exceptional-haskell

A talk on exceptions and errors in Haskell.
JavaScript
3
star
70

websockets-example

A test app of websockets
PureScript
3
star
71

purescript-pux-undo

Convenient undo/redo functionality for your Pux application
PureScript
3
star
72

metricord

A web application for recording metrics and doing aggregations
Haskell
3
star
73

defer-diagnostics-reproduction

This repo gives a reproduction for defer diagnostics on GHC 9.4.2
Makefile
2
star
74

currb

Presentation on currying and function composition in Ruby
JavaScript
2
star
75

gamma

maybe this is a programming language?
Haskell
2
star
76

abstract-effects

A package for abstract effects in Haskell
2
star
77

servant-ruby

Generate Ruby clients from your Servant API!
Haskell
2
star
78

hspec-yesod

Forked from `yesod-test` to support idiomatic `hspec` testing
Haskell
2
star
79

spellcards

a silly little Haskell app to print out some cards for D&D spells
Haskell
2
star
80

distributed

Playing with Cloud Haskell
Haskell
2
star
81

write-buffer

If single writes are slowing you down, who you gonna call? WRITE BUFFER!
Haskell
2
star
82

design-patterns-math

Design Patterns from Abstract Math
JavaScript
2
star
83

haskell-parser

A parser for Haskell implemented in Rust.
Rust
1
star
84

multicast

Toy implementation of a multicast chat server
Haskell
1
star
85

disc-inst-bug

reproduction for a GHC bug #20563
Haskell
1
star
86

squirrell

kinda magical query objects
Ruby
1
star
87

pux-repro

reproduction of issue purescript-pux#14
PureScript
1
star
88

hlift

Haskell weightlifting utility
Haskell
1
star
89

require-callstack-talk

Haskell
1
star
90

slowlift

yet another weightlifitng app
Haskell
1
star
91

purescript-zippers

Zippers for PureScript
PureScript
1
star
92

routerhs

playing with nesting RESTful routes in Haskell
Haskell
1
star
93

logic

Haskell
1
star
94

gol

implementation of Game of Life in Haskell
Haskell
1
star
95

tiger

Working through the Appel book in Haskell
Haskell
1
star
96

cardano-wallet

fork of cardano-wallet from when i worked at iohk
Haskell
1
star
97

require-callstack-repro

A reproduction of an issue with implicit params and type errors
Haskell
1
star
98

hailgun

fork of hailgun
Haskell
1
star
99

OkFilter

OkFilter is a Ruby script that helps to make your OkCupid experience better by filtering out poor matches.
Ruby
1
star
100

bike-geo

i need help fitting my bike lmao
Haskell
1
star