在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:ttu/dotnet-fake-json-server开源软件地址:https://github.com/ttu/dotnet-fake-json-server开源编程语言:C# 98.8%开源软件介绍:Fake JSON Server
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.
Why would I use this instead of other Fake Servers?
Features
Developed with
Table of contentsClick to here to see contents
Get startedStart 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 toolServer can be installed as a dotnet global tool. Settings files are then located at # 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 DockerIf 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 # 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 ApplicationThe self-contained application archive contains Fake JSON Server, .NET runtime and all required third-party dependencies. No installation or prerequisites are needed.
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 filesFake 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 projectRedux TodoMVC example modified to use Fake JSON Server as a Back End. Example queriesExample queries are in Insomnia workspace format in FakeServer_Insomnia_Workspace.json. FeaturesAuthenticationFake REST API supports Token and Basic Authentication. Authentication can be disabled from Add allowed usernames/passwords to "Authentication": {
"Enabled": true,
"AuthenticationType": "token",
"Users": [
{ "Username": "admin", "Password": "root" }
],
"ApiKey": "abcd1234"
} Token AuthenticationAPI has a token provider middleware which provides an endpoint for token generation 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 $ 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
Add base64 encoded username:password to authorization header e.g. $ 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 AuthenticationAdd key set to Authentication settings to $ curl -H 'X-API-KEY: abcd1234' http://localhost:57602/api WebSocketsAPI will send the latest update's method ( { "method": "PATCH", "path": "/api/users/2", "collection": "users", "itemId": 2 } wwwroot\index.html has a WebSocket example. CORSCORS is enabled and it allows everything. Static Files
Returns static files from wwwroot or defined location. Default file is Check how to serve static files from defined location. SwaggerSwagger is configured to endpoint Caching and avoiding mid-air collisions with ETagCaching can be disabled from "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 resourcesIf a request contains the $ curl -H "If-None-Match: \"5yZCXmjhk5ozJyTK4-OJkkd_X18\"" 'http://localhost:57602/api/users?age=40' Avoiding mid-air collisionsIf the Content NegotiatonClient can determine what type of representation is desired with Supported types are JSON, CSV and XML.
Get all users in CSV $ curl -H "Accept: text/csv" http://localhost:57603/api/users If content types is not supported Routes, Functionalities and Examples
Collections and objectsFake 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": {}
} RoutesDynamic routes are defined by the name of item's collection and id: If 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 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
"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 Return codesAsynchoronous operations follow the REST CookBook guide. Updates will return Method return codes are specified in REST API Tutorial. OPTIONS methodOPTIONS method will return $ curl -X OPTIONS -v http://localhost:57602/api/ 200 OK
Headers:
Allow: GET, POST, OPTIONS HEAD methodHEAD 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 nameName of the Id-field used by Data Store can be configure from "DataStore": {
"IdField": "id"
} Eager data reloadBy default Data Store updates its internal data on every request by reading the data from the JSON file.
"DataStore": {
"EagerDataReload": true
} For performance reasons If ReloadReload 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. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论