Giter Site home page Giter Site logo

ttu / dotnet-fake-json-server Goto Github PK

View Code? Open in Web Editor NEW
384.0 16.0 79.0 545 KB

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.

Home Page: https://ttu.github.io/dotnet-fake-json-server/

License: MIT License

C# 98.63% HTML 0.65% Batchfile 0.28% Shell 0.27% Dockerfile 0.17%
csharp webapi dotnet-core dynamic json fake-data graphql prototyping fake-server

dotnet-fake-json-server's People

Contributors

5wdgjibxs7dee avatar antoniaelek avatar arashjfz avatar aschuhardt avatar blueberryking avatar chekkan avatar erichoog avatar frenzyfunky avatar herariom avatar kashifsoofi avatar kjaek avatar leplaekevin avatar lucarine avatar mat-czernek avatar maymike321 avatar phaniva avatar seleregb avatar sunithapatel avatar thebinaryguy avatar ttu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dotnet-fake-json-server's Issues

DELETE operations put server in Bad State

DELETE /api/{collection}/{id}
succeeds only once. If there are other collections, server will return 500.

Sample data.json:

{
  "tests": [
    {
      "value": [
        "Test1"
      ],
      "id": 0
    }
  ],
  "items": [
    {
      "description": "some_description",
      "createdDate": "0001-01-01T00:00:00",
      "id": 0
    }
  ],
  "programs": [
    {
      "id": 0,
      "canOverride": false,
      "enabled": true,
      "version": null
    }
  ]
}

Operation 1
DELETE /api/tests/0
result: 204

Operation 2
DELETE /api/items/0
result: 500

Support numeric string for collection identifiers

If a collection has an item with "id": "MTgwODA3MA" and another item with "id": "510". Then GET /api/collection/510 will throw an exception in DynamicController.GetItem on the lamba method ObjectHelper.GetFieldValue(e, _dsSettings.IdField) == id :

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Operator '==' cannot be applied to operands of type 'string' and 'int''

Do you think it would be interesting to support collections with such numeric string as identifiers?

Thank you very much for this library. It's very interesting, I use it for learning purposes and prototyping.

Specifying a data file with the "--file" argument causes a duplicate key exception

Steps to reproduce:

  1. Clone the repo
  2. cd into the dotnet-fake-json-server/FakeServer directory
  3. Create a file called "test.json"
  4. Run the application with the following command: dotnet run --file "test.json"

I received the following trace after dotnet crashed:

PS C:\Users\aschuhardt\dotnet-fake-json-server\FakeServer> dotnet run --file "test.json"
Using launch settings from C:\Users\aschuhardt\dotnet-fake-json-server\FakeServer\Properties\launchSettings.json...
File: test.json

Unhandled Exception: System.ArgumentException: An item with the same key has already been added. Key: file
   at System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(Object key)
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at FakeServer.Program.Main(String[] args) in C:\Users\aschuhardt\dotnet-fake-json-server\FakeServer\Program.cs:line 38

Cause:

This line adds a key "file" regardless of whether one has been added as a result of the command-line argument

HEAD methods don't return ETag header

HEAD method should use same method as GET from DynamicController, so ETagMiddleware has the response body and can add ETag header. Framework will remove the body later.

Extend support for static files

Current functionality serves files from wwwroot
https://github.com/ttu/dotnet-fake-json-server#static-files

Should work same way as e.g. Node's Serve
https://www.npmjs.com/package/serve

$ npm install -g serve

# Server all files from root
$ serve -s .

Usage could be like this:

$ dotnet install --global FakeServer

# Server files from root
$ fake-server --serve .

# Server files from specific folder
$ fake-server --serve ./files
$ fake-server -s ./files
$ fake-server -s C:\temp\files
$ fake-server -s /home/timmy/app/dist

Create new appsettings.json from command line

Add init command line parameter that will create default appsettings.json

$ fake-server --init

$ dotnet run --init

This command should be used with global tool as then appsettings.json is not located in the startup directory.

Add functionality - REST: Sort & direction

Follow guide from Zalando:

sort โ€” comma-separated list of fields to sort. To indicate sorting direction, fields my prefixed with + (ascending) or - (descending, default), e.g. /sales-orders?sort=+id

Sort user by age (descending)

/users?sort=age
/users?sort=-age

Sort user by age (ascending)

/users?sort=+age

GET /api/{object} support

It works well with collections but it really needs to support JSON objects as endpoint like so:

We have data.json file:

`{
  "my_test_request": {
    "has_access": true,
    "token": "09832145kndse89745",
    "name": "Instagram Honey",
    "data_array": [
     "beer", "disco", "fun"
    ]
  }
}`

GET http://localhost:57602/api/my_test_request

And as response:

 {
    "has_access": true,
    "token": "09832145kndse89745",
    "name": "Instagram Honey",
    "data_array": [
     "beer", "disco", "fun"
    ]
  }

Upgrade McMaster.Extensions.CommandLineUtils to version 4.x

Error when upgrading from current version 3.1.0 to 4.0.2

FakeServer
  Program.cs(136, 44): [CS0411] The type arguments for method 'ConfigurationExtensions.Add<TSource>(IConfigurationBuilder, Action<TSource>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
  Program.cs(137, 44): [CS0411] The type arguments for method 'ConfigurationExtensions.Add<TSource>(IConfigurationBuilder, Action<TSource>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
  Program.cs(156, 54): [CS1061] 'IReadOnlyList<string>' does not contain a definition for 'ToArray' and no accessible extension method 'ToArray' accepting a first argument of type 'IReadOnlyList<string>' could be found (are you missing a using directive or an assembly reference?)

https://github.com/ttu/dotnet-fake-json-server/blob/master/FakeServer/Program.cs#L136

Find the correct way to add arguments. Maybe will work with app.Arguments.Add ?

Controller Path/Tree Support

using a web service tree with controller paths like:

garage/v3.0/storage/Bins
garage/v3.0/storage/Shelves
garage/v3.0/workbench/Tools

I haven't been able to figure out how to mock these, even manually editing datastore.json as follows and calling Reload:

{ "garage/v3.0/storage/Bins": [ { "Type": "Large", "id": 0 }, { "Type": "Small", "id": 1 } ] }

I see there is support for nested items, but this requires specifying an item ID at each level which will not match the paths used by the real service.

Release unreleased features

Could you release the unreleased features? I'm especially eager to use the "Content negotiation with Accept-header and support for CSV and XML" feature.

Travis CI test (Linux) fail with "System.IO.IOException: The configured user limit (128) on the number of inotify instances has been reached ..."

Unit tests on Travis (Linux) fail with

System.IO.IOException : The configured user limit (128) on the number of inotify instances has been reached, or the per-process limit on the number of open file descriptors has been reached.

Example failing test run:
https://app.travis-ci.com/github/ttu/dotnet-fake-json-server/builds/251835568

Example stack trace:

[xUnit.net 00:02:53.56]     FakeServer.Test.Authentication.TokenAuthenticationSpecs.GetToken_InvalidJsonData [FAIL]
  Failed FakeServer.Test.Authentication.TokenAuthenticationSpecs.GetUsers_Authorized_Logout(tokenType: Json) [1 ms]
  Error Message:
   System.IO.IOException : The configured user limit (128) on the number of inotify instances has been reached, or the per-process limit on the number of open file descriptors has been reached.
  Stack Trace:
     at System.IO.FileSystemWatcher.StartRaisingEvents()
   at Microsoft.Extensions.FileProviders.Physical.PhysicalFilesWatcher.TryEnableFileSystemWatcher()
   at Microsoft.Extensions.FileProviders.Physical.PhysicalFilesWatcher.CreateFileChangeToken(String filter)
   at Microsoft.Extensions.Primitives.ChangeToken.OnChange(Func`1 changeTokenProducer, Action changeTokenConsumer)
   at Microsoft.Extensions.Configuration.FileConfigurationProvider..ctor(FileConfigurationSource source)
   at Microsoft.Extensions.Configuration.Json.JsonConfigurationSource.Build(IConfigurationBuilder builder)
   at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.BuildCommonServices(AggregateException& hostingStartupErrors)
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at Microsoft.AspNetCore.TestHost.TestServer..ctor(IWebHostBuilder builder, IFeatureCollection featureCollection)
   at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateServer(IWebHostBuilder builder)
   at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.EnsureServer()
   at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateDefaultClient(DelegatingHandler[] handlers)
   at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateClient(WebApplicationFactoryClientOptions options)
   at FakeServer.Test.IntegrationFixture.StartServer(String authenticationType) in /home/travis/build/ttu/dotnet-fake-json-server/FakeServer.Test/IntegrationTestCollection.cs:line 69
   at FakeServer.Test.Authentication.TokenAuthenticationSpecs..ctor(IntegrationFixture fixture) in /home/travis/build/ttu/dotnet-fake-json-server/FakeServer.Test/Authentication/TokenAuthenticationSpecs.cs:line 24

Reqeust to console and/or file?

Great job on the .NET global tool! Works great!

Is there an option to tell fake server to simply output the request to the console or file?

If not, I'll be happy to try and help. Just point a finger in the best spot to implement the code and I'll make it happen.

Fix XML element naming for collections and single items

Regardless of collection naming, elements in XML should be singularized / pluralized.

E.g. for endpoints
/api/family
/api/families

XML should be:

<families>
  <family>
    <id>

Current implementation has e.g. for /api/families

<families>
  <families_0>
    <id>

for /api/family

<family>
  <family_0>
    <id>

Implementation:

var itemName = ObjectHelper.GetCollectionFromPath(context.HttpContext.Request.Path.Value);

var children = itemCollection.Select((i, idx) => ((ExpandoObject)i).Aggregate(new XElement($"{name}_{idx}"), HandleExpandoField));

var children = innerList.Select((i, idx) => ((ExpandoObject)i).Aggregate(new XElement($"{fields.Key}_{idx}"), HandleExpandoField));

Mayble library like https://www.nuget.org/packages/Pluralize.NET.Core/ will do the trick?

GraphQL should also support request with POST method and Content-Type: application/json

Request handling is in FakeServer/GraphQL/GraphQLMiddleware.cs.

Now middleware supports:

If the "application/graphql" Content-Type header is present, treat the HTTP POST body contents as the GraphQL query string.

Should also support this:

If the "application/json " Content-Type header is present, treat the HTTP POST body contents as a JSON with parameter query having the GraphQL query string.

Method: POST 
Content-Type: application/json 
Body: { "query": "{users{name}}" }

Broken Auth in Swagger UI

On branch update-to-core-30 the endpoints under Authentification tag in Swagger UI are unusable with various symptoms on the following browsers :

  • On Windows 10 with Chrome
  • On Windows 10 with Firefox
  • On MacOS with Chrome

Those endpoints work fine with cURL commands. The problem comes from Swagger UI.

Note: on branch master with .NET Core 2.2, despite the web browser receives the auth token, the Swagger UI does not display the response. Is it important to fix that, or should we focus our effort on .NET Core 3?

Update to .NET Core 3.1

Migration guide: https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio

Branch: https://github.com/ttu/dotnet-fake-json-server/tree/update-to-core-30

New System.Text.Json doesn't support all serializations required by Fake Server, so have to use NewtonsoftJson.

TODO:
[ ] Fix Swagger Authentication filters
[x] Fix InputFormatters / Consumes attribute to accept different media types (merge json)
[x] ETagMiddleware doesn't work with PUT methods. Middleware can't change request's method to GET and verify original data.

GraphQL should support requests with GET and POST method and query in the query parameter

Full specification: http://graphql.org/learn/serving-over-http/

Request handling is in FakeServer/GraphQL/GraphQLMiddleware.cs.

Now middleware supports case:

If the "application/graphql" Content-Type header is present, treat the HTTP POST body contents as the GraphQL query string.

Should also support these:

Method: GET
When receiving an HTTP GET request, the GraphQL query should be specified in the "query" query string

/graphql?query={users{name}}

Method: POST
If the "query" query string parameter is present (as in the GET example above), it should be parsed and handled in the same way as the HTTP GET case.

/graphql?query={users{name}}

Merge patch should support nested properties

Should be able to update e.g. only parent with id 1

PATCH /api/families/19/parents/1

{
  "name": "Kyle",
  "work": {
    "companyName": "PAWNAGRA",
    "address": "679 Ebony Court, Loma, Puerto Rico, 7716"
  }
}

Current implementation supports patch only from the root-level e.g. /api/families/19.

Using Id located somewhere else

Hi,

Is there a way to reference an idea inside a collection rather than a straight forward property?
Using your "users" as an example:

"users": [
    {
      "id": 1,
      "name": "James",
      "age": 40,
      "location": "NY",
      "work": {
        "name": "ACME",
        "location": "NY",
        "rating": 2.3
      }
]

To access it I can user users/1 but what if my Id is inside one of the propeties? for eg:

"users": [
    {
      "name": "James",
      "age": 40,
      "location": "NY",
      "work": {
        "id": 1,
        "name": "ACME",
        "location": "NY",
        "rating": 2.3
      }
    }
]

Is there a way to access this record with "users/{id} but when it gets executed it points to "users/work/{id}" ?

Thanks

Add Swagger URL to startup output

Current output

Datastore file: datastore.json
Datastore location: /home/tomi/src/github/dotnet-fake-json-server/FakeServer
Static files: default wwwroot
Hosting environment: Development
Content root path: /home/xxxx/dotnet-fake-json-server/FakeServer
Now listening on: http://localhost:57603
Application started. Press Ctrl+C to shut down.

Add Swagger Open API as a last line.

Now listening on: http://localhost:57603
Application started. Press Ctrl+C to shut down.
Swagger Open API is available on: http://localhost:57603/swagger  

Pretty likely this needs to be done in Startup.cs as we need to be able to check what is the current port in use.

Bad XML tags occuring when getting single family

When using the command "curl -H "Accept: text/xml" http://localhost:57602/api/families/1", it appears that an errant <friends />" tag (not </friends>) appears right before a </child> tag.

      </friends>
    </child>
    <child>
      <name>Katheryn</name>
      <gender>female</gender>
      <age>9</age>
      <friends />
    </child>
  </children>

For the command "curl -H "Accept: text/xml" http://localhost:57602/api/families/0", an errant <children /> tag occurs after </parents>

    </parent>
  </parents>
  <children />
  <address>
    <postNumber>147</postNumber>
    <street>Melba Court</street>

I did some testing and was able to replicate this problem before the changes in XML pluralization, but I wasn't able to find an immediate cause.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.