• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ttu/dotnet-fake-json-server: Fake JSON Server is a Fake REST API that can be use ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

ttu/dotnet-fake-json-server

开源软件地址:

https://github.com/ttu/dotnet-fake-json-server

开源编程语言:

C# 98.8%

开源软件介绍:

Fake JSON Server

NuGet

Build server Platform Build status
Travis Linux / macOS Build Status
AppVeyor Windows Build status

Fake JSON Server is a Fake REST API that can be used as a Back End for prototyping or as a template for a CRUD Back End. Fake JSON Server also has an experimental GraphQL query and mutation support.

  • No need to define types for resources, uses dynamic typing
  • No need to define routes, routes are handled dynamically
  • No database, data is stored to a single JSON file
  • No setup required, just start the server and API is ready to be used with any data
Why would I use this instead of other Fake Servers?
  1. API is built following the best practices and can be used as a reference when building your own API
  2. Can be run on Windows, Linux and macOS without any installation or prerequisites from executable or with Docker
  3. See features listed below

Features

  • Supported HTTP methods #
    • All methods for CRUD operations (GET, PUT, POST, PATCH, DELETE)
    • Methods for fetching resource information (HEAD, OPTIONS)
  • Async versions of update operations with long running operations and queues #
  • REST API follows best practices from multiple guides
    • Uses correct Status Codes, Headers, etc.
    • As all guides have slightly different recommendations, this compilation is based on our opinions
  • Token, Basic and API key Authentication #
  • WebSocket update notifications #
  • Simulate delay and errors for requests #
  • Static files #
  • Swagger #
  • CORS #
  • Content Negotiation (output formats JSON, CSV and XML) #
  • Caching and avoiding mid-air collisions with ETag #
  • Configurable custom response transformation #
  • Experimental GraphQL query and mutation support #
Developed with
  • .NET 5
  • Uses JSON Flat File Data Store to store data
  • Can be installed as a dotnet global tool #
  • Can be used without .NET
    • Docker #
    • Self-contained Application #

Table of contents

Click to here to see contents

Get started

Start with .NET CLI

# Get source code from GitHub
$ git clone https://github.com/ttu/dotnet-fake-json-server.git

$ cd dotnet-fake-json-server/FakeServer
$ dotnet run

Start server with defined data-file and url (optional arguments)

# Optional arguments:
#   --file <FILE>    Data store's JSON file (default datastore.json)
#   --urls <URL>     Server url (default http://localhost:57602)      
#   --serve <PATH>   Serve static files (default wwwroot)
#   --version        Prints the version of the app

$ dotnet run --file data.json --urls http://localhost:57602

Install as a dotnet global tool

Server can be installed as a dotnet global tool. Settings files are then located at %USERPROFILE%\.dotnet\tools (Windows) and $HOME/.dotnet/tools (Linux/macOS). By default data stores's JSON file will be created to execution directory.

# install as a global tool
$ dotnet tool install --global FakeServer

# Example: Start server
$ fake-server --file data.json --urls http://localhost:57602

# Update to the newest version
$ dotnet tool update --global FakeServer

Docker

If you don't have .NET installed, you can run the server with Docker.

# Get source code from GitHub
$ git clone https://github.com/ttu/dotnet-fake-json-server.git

$ cd dotnet-fake-json-server
$ docker build -t fakeapi .

# Run in foreground
$ docker run -it -p 57602:57602 --name fakeapi fakeapi

# Run in detached mode (run in background)
$ docker run -it -d -p 57602:57602 --name fakeapi fakeapi

# Start stopped container (remove -a to run in background)
$ docker start -a fakeapi

Copy JSON-file to/from container. Filename is datastore.json

# Copy file from host to container
$ docker cp datastore.json fakeapi:/app/datastore.json

# Copy file from container to host
$ docker cp fakeapi:/app/datastore.json datastore.json

Self-contained Application

The self-contained application archive contains Fake JSON Server, .NET runtime and all required third-party dependencies. No installation or prerequisites are needed.

  1. Go to Latest Release
  2. Download correct archive matching your OS
  3. Extract files and execute

E.g. download and execute version 0.11.0 for macOS

$ mkdir FakeServer && cd FakeServer
$ wget https://github.com/ttu/dotnet-fake-json-server/releases/download/0.11.0/fakeserver-osx-x64.tar.gz
$ tar -zxvf fakeserver-osx-x64.tar.gz
$ chmod +x FakeServer
$ ./FakeServer

Serve static files

Fake Server can serve static files. Location of files can be absolute or relative to the current location.

$ dotnet run -s/--serve [fullpath/relative path]
# e.g.
$ dotnet run -s build

# Use Fake Server as a global tool
$ fake-server -s/--serve [fullpath/relative path]]
# e.g.
$ fake-server --serve c:\temp\react_app\build
$ fake-server --serve /home/user/app/dist
$ fake-server --serve ./build

When user defines static files, it is assumed that user is serving a single page app and then REST API is not working. If API is needed, start other instance of Fake Server.

Quick example

# List collections (should be empty, if data.json didn't exist before)
$ curl http://localhost:57602/api

# Insert new user
$ curl -H "Content-type: application/json" -X POST -d '{ "name": "Phil", "age": 20, "location": "NY" }' http://localhost:57602/api/users/

# Insert another user
$ curl -H "Content-type: application/json" -X POST -d '{ "name": "James", "age": 40, "location": "SF" }' http://localhost:57602/api/users/

# List users
$ curl http://localhost:57602/api/users

# List users from NY
$ curl http://localhost:57602/api/users?location=NY

# Get User with Id 1
$ curl http://localhost:57602/api/users/1

...

# Add users to data.json manually

# Get all users
$ curl http://localhost:57602/api/users/
...

# Or open url http://localhost:57602/swagger/ with browser and use Swagger

Example project

Redux TodoMVC example modified to use Fake JSON Server as a Back End.

Example queries

Example queries are in Insomnia workspace format in FakeServer_Insomnia_Workspace.json.

Features

Authentication

Fake REST API supports Token and Basic Authentication.

Authentication can be disabled from appsettings.json by setting Enabled to false. AuthenticationType options are token, basic and apikey.

Add allowed usernames/passwords to Users-array. Add optional API key to ApiKey-property.

"Authentication": {
  "Enabled": true,
  "AuthenticationType": "token",
  "Users": [
      { "Username": "admin", "Password": "root" }
  ],
  "ApiKey": "abcd1234"
}

Token Authentication

API has a token provider middleware which provides an endpoint for token generation /token. Endpoint supports 'content-type: multipart/form-data and content-type: application/json. Username and password must be in username and password fields.

Get token:

# content-type: multipart/form-data
$ curl -X POST -H 'content-type: multipart/form-data' -F username=admin -F password=root http://localhost:57602/token

# content-type: application/json
$ curl -X POST -H 'content-type: application/json' -d '{ "username": "admin", "password": "root" }' http://localhost:57602/token

Token can be fetch also using Client Credentials grant type (see example from Insomnia workspace):

$ curl -X POST -d "grant_type=client_credentials&client_id=admin&client_secret=root" http://localhost:57602/token

Add token to Authorization header:

$ curl -H 'Authorization: Bearer [TOKEN]' http://localhost:57602/api

Token authentication has also a logout functionality. By design tokens do not support token invalidation, so logout is implemented by blacklisting tokens.

$ curl -X POST -d '' -H 'Authorization: Bearer [TOKEN]' http://localhost:57602/logout

The implementation is quite similiar to SimpleTokenProvider and more info on that can be found from GitHub and StormPath's blog post.

Basic Authentication

NOTE: It is not recommended to use Basic Authentication in production as base64 is a reversible encoding

Add base64 encoded username:password to authorization header e.g. 'Authorization: Basic YWRtaW46cm9vdA=='.

$ curl -u admin:root http://localhost:57602/api
# -u argument creates Authorization header with encoded username and password
$ curl -H 'Authorization: Basic YWRtaW46cm9vdA==' http://localhost:57602/api

API key Authentication

Add key set to Authentication settings to X-API-KEY header e.g. X-API-KEY: abcd1234'.

$ curl -H 'X-API-KEY: abcd1234' http://localhost:57602/api

WebSockets

API will send the latest update's method (POST, PUT, PATCH, DELETE), path, collection and optional item id with WebSocket.

{ "method": "PATCH", "path": "/api/users/2", "collection": "users", "itemId": 2 }

wwwroot\index.html has a WebSocket example.

CORS

CORS is enabled and it allows everything.

Static Files

GET /

Returns static files from wwwroot or defined location. Default file is index.html.

Check how to serve static files from defined location.

Swagger

Swagger is configured to endpoint /swagger and Swagger UI opens when project is started from IDE.

Caching and avoiding mid-air collisions with ETag

Caching can be disabled from appsettings.json by setting ETag.Enabled to false.

"Caching": {
  "ETag": { 
    "Enabled": true 
  }
}

If caching is enabled, ETag is added to response headers.

$ curl -v 'http://localhost:57602/api/users?age=40'
200 OK

Headers:
ETag: "5yZCXmjhk5ozJyTK4-OJkkd_X18"

Caching of unchanged resources

If a request contains the If-None-Match header, the header's value is compared to the response's body and if the value matches to the body's checksum then 304 Not Modified is returned.

$ curl -H "If-None-Match: \"5yZCXmjhk5ozJyTK4-OJkkd_X18\"" 'http://localhost:57602/api/users?age=40'

Avoiding mid-air collisions

If the PUT request contains the If-Match header, the header's value is compared to the item to be updated. If the value matches to the item's checksum then items is updated, else 412 Precondition Failed is returned.

Content Negotiaton

Client can determine what type of representation is desired with Accept header. By default data is returned in JSON (text/json, application/json).

Supported types are JSON, CSV and XML.

text/json
application/json
text/csv
text/xml
application/xml

Get all users in CSV

$ curl -H "Accept: text/csv" http://localhost:57603/api/users

If content types is not supported 406 Not Acceptable is returned.

Routes, Functionalities and Examples

GET      /
POST     /token
POST     /logout
POST     /admin/reload

GET      /api
HEAD     /api
GET      /api/{collection/object}
HEAD     /api/{collection/object}
POST     /api/{collection}
GET      /api/{collection}/{id}
HEAD     /api/{collection}/{id}
PUT      /api/{collection}/{id}
PATCH    /api/{collection}/{id}
DELETE   /api/{collection}/{id}
PUT      /api/{object}
PATCH    /api/{object}
DELETE   /api/{object}
OPTIONS  /api/*

GET      /async/queue/{id}
DELETE   /async/queue/{id}
POST     /async/{collection}
PUT      /async/{collection}/{id}
PATCH    /async/{collection}/{id}
DELETE   /async/{collection}/{id}
OPTIONS  /async/*

POST     /graphql

Collections and objects

Fake JSON Server is designed for prototyping, so by default it supports only resources in a collection.

If the JSON-file has a single object on a root level, then the route from that property is handled like a single object.

{
  "collection": [],
  "object": {}
}

Routes

Dynamic routes are defined by the name of item's collection and id: api/{collection}/{id}. All examples below use users as a collection name.

If /api or /async are needed to change to something different, change ApiRoute or AsyncRoute from Config.cs.

public class Config
{
    public const string ApiRoute = "api";
    public const string AsyncRoute = "async";
    public const string GraphQLRoute = "graphql";
    public const string TokenRoute = "token";
    public const string TokenLogoutRoute = "logout";
}

For example, if api-prefix is not wanted in the route, then remove api from ApiRoute.

public const string ApiRoute = "";
# Query with default route
$ curl 'http://localhost:57602/api/users?skip=5&take=20'
# Query with updated route
$ curl 'http://localhost:57602/users?skip=5&take=20'

Identifiers

id is used as the identifier field. By default Id field's type is integer. POST will always use integer as id field's type.

"users":[
  { "id": 1 }
],
"sensors": [
  { "id": "E:52:F7:B3:65:CC" }
]

If string is used as the identifiers type, then items must be inserted with PUT and UpsertOnPut must be set to true from appsettings.json.

Return codes

Asynchoronous operations follow the REST CookBook guide. Updates will return 202 with location header to queue item. Queue will return 200 while operation is processing and 303 when job is ready with location header to changed or new item.

Method return codes are specified in REST API Tutorial.

OPTIONS method

OPTIONS method will return Allow header with a list of HTTP methods that may be used on the resource.

$ curl -X OPTIONS -v http://localhost:57602/api/
200 OK

Headers:
Allow: GET, POST, OPTIONS

HEAD method

HEAD method can be used to get the metadata and headers without receiving response body.

E.g. get user count without downloading large response body.

$ curl -X HEAD -v http://localhost:57602/api/users
200 OK

Headers:
X-Total-Count: 1249

Data Store Id-field name

Name of the Id-field used by Data Store can be configure from appsettings.json. Default name for the id-field is id.

"DataStore": {
  "IdField": "id"
}

Eager data reload

By default Data Store updates its internal data on every request by reading the data from the JSON file.

EagerDataReload can be configured from appsettings.json.

"DataStore": {
  "EagerDataReload": true
}

For performance reasons EagerDataReload can be changed to false. Then the data is reloaded from the file only when Data Store is initialized and when the data is updated.

If EagerDataReload is false and JSON file is updated manually, reload endpoint must be called if new data will be queried before any updates.

Reload

Reload endpoint can be used to reload JSON data from the file to Data Store. Endpoint is in Admin controller, so it is usable also with Swagger.


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap